Core Fundamentals ⏱ 10 min read 📁 examples/05_tool_calling.mjs

Lesson 04: Function Calling and Tool Control

Master the 7 tool-loop patterns: automated agentic loop, parallel function calls, manual generator iteration, forced tool_choice, named control, thinking budgets, and staged review.

1. Why This Feature Exists

Real-world agents require fine-grained control over when and how tools are invoked. Merci SDK lets you toggle between high-level autonomous loops (.run()) and low-level step-by-step generators (.step()), complete with reasoning stream visibility.

2. Key Symbols and Exports

session.withTools(tools)
Registers executable tool definitions with JSON schemas and execute handlers.
session.run(prompt)
Automated multi-turn agent loop that invokes tools and feeds results back to the model.
toolChoiceAuto / toolChoiceForced
Controls whether tool invocation is optional, forbidden, or strictly required.
withParameters({ reasoningEffort })
Configures thinking budgets (low, medium, high) and reasoning tokens.
executeTools(tools, calls)
Executes parallel tool calls concurrently with error boundaries.

3. Implementation Walkthrough

import {
    ProviderType,
    resolveProvider,
    initializeClient,
    loadCredentials,
    getToolModel
} from 'merci-sdk';

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

const weatherTool = {
    name: 'get_weather',
    description: 'Get weather for a location',
    parameters: {
        type: 'object',
        properties: { location: { type: 'string' } },
        required: ['location']
    },
    execute: async ({ location }) => ({ temp: 22, condition: 'Sunny', location })
};

const session = client.session(getToolModel({ provider: PROVIDER }))
    .withTools([weatherTool] });

// Autonomous execution: handles tool calls, tool results, and final text
const answer = await session.run('What is the weather in Prague right now?');
console.log('Final Answer:', answer);

4. Wire and Telemetry Mechanics

The SDK transmits tool definitions in provider-specific schemas. When the model emits tool_calls, the SDK dispatches 'tool_start' events, runs the execute function, formats tool result messages with matching tool_call_id, and resends the history until a terminal text response is reached.

5. Run the Example

Execute the runnable example directly from the repository root:

node examples/05_tool_calling.mjs

Read the full example: examples/05_tool_calling.mjs →

Expected Output: Demonstrates 7 distinct tool patterns sequentially, displaying thinking traces, tool invocation arguments, and result payloads.