Core Fundamentals ⏱ 8 min read 📁 examples/02_conversation.mjs

Lesson 02: Multi-Turn Chat and Parameter Handling

Build an interactive multi-turn REPL chat while mastering parameter normalization, thought signature persistence, message deduplication, and turn boundary tracking.

1. Why This Feature Exists

Different LLM providers have conflicting parameter names (e.g. max_tokens vs maxOutputTokens) and inconsistent requirements for multi-turn history. Merci SDK's ParameterBuilder accepts uniform options and automatically maps them to provider-specific keys while pruning unsupported fields to prevent 400 Bad Request errors.

2. Key Symbols and Exports

session.withParameters(params)
Unified parameter builder with automatic wire translation (temperature, maxTokens, topP).
MERCI_ID_KEY & dedupeMessages
Guarantees message uniqueness across conversation histories without mutation.
thoughtSignature
Preserves reasoning context across turns for models with extended thinking capabilities.
normalizeHistory()
Sanitizes message arrays to satisfy strict provider requirements (e.g., alternating user/assistant turns).

3. Implementation Walkthrough

import {
    createUserMessage,
    ProviderType,
    resolveProvider,
    initializeClient,
    loadCredentials,
    getDefaultModel,
    dedupeMessages
} from 'merci-sdk';

const PROVIDER = resolveProvider();
const { client } = await initializeClient({ provider: PROVIDER, options: loadCredentials({ provider: PROVIDER }) });

let messages = [];
let thoughtSig = null;

// Configure session with parameters
const session = client.session(getDefaultModel({ provider: PROVIDER }))
    .withSystemMessage('You are a concise engineering assistant.')
    .withParameters({
        temperature: 0.7,
        maxTokens: 1024
    });

// Multi-turn turn execution: replace history with finalState.messages
const userMsg = createUserMessage({ provider: PROVIDER, content: 'What is idempotent execution?' });
const gen = session.step({ messages: [...messages, userMsg], options: { thoughtSignature: thoughtSig } });

for await (const event of gen) {
    if (event.type === 'text') process.stdout.write(event.content);
}

const finalState = (await gen.next()).value ?? {};
messages = dedupeMessages(finalState.messages ?? messages);
thoughtSig = finalState.thoughtSignature ?? thoughtSig;

4. Wire and Telemetry Mechanics

Every turn sends the full array of normalized messages. If the model generates a thought signature (e.g. Gemini 2.0 / Claude 3.7 reasoning), the SDK captures it and threads it into subsequent requests, maintaining multi-turn chain-of-thought coherence without leaking thoughts into final text.

5. Run the Example

Execute the runnable example directly from the repository root:

node examples/02_conversation.mjs

Read the full example: examples/02_conversation.mjs →

Expected Output: Interactive REPL prompt. Enter messages to chat with the model. Notice the history growth counter and token estimates logged after every turn.