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
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.mjsRead the full example: examples/05_tool_calling.mjs →