Lesson 11: Multi-Turn Tool Use & Clarification
This advanced lesson demonstrates how to build a robust agent that can ask clarifying questions when a user's request is ambiguous, ensuring it has all the necessary information before calling a tool.
Code: lesson_11_multi_turn_clarification.mjs
This script uses the low-level .stream()
method in a loop. It manually processes events, checking if the model responded with text (a clarifying question) or a tool call. This gives us fine-grained control over the conversation flow.
// lesson_11_multi_turn_clarification.mjs
import { MerciClient, executeTools, /* ...message helpers... */ } from \'../lib/merci.2.14.0.mjs\';
import * as readline from \'node:readline/promises\';
async function main() {
const chatSession = client.chat.session(MODEL).withTools([calendarTool]);
const messages = [];
let userInput = \"Can you add an event to my calendar?\";
while (true) {
if (userInput) messages.push(createUserMessage(userInput));
let toolCalls = [];
let currentTurnText = \'\';
for await (const event of chatSession.stream(messages)) {
if (event.type === \'text\') currentTurnText += event.content;
if (event.type === \'tool_calls\') toolCalls = event.calls;
}
if (currentTurnText) messages.push(createAssistantTextMessage(currentTurnText));
if (toolCalls.length > 0) {
const toolResults = await executeTools(toolCalls, [calendarTool]);
// ...add tool call and result messages to history...
userInput = null; // Loop again to get the model\'s summary
continue;
}
userInput = await rl.question(\'👤 You > \');
if (userInput.toLowerCase() === \'exit\') break;
}
}
main();
Expected Output
The agent correctly identifies missing information (title, date, time) and asks clarifying questions before it has enough context to call the tool.
--- Merci SDK Lesson 11: Multi-Turn Tool Clarification (Model: google-chat-gemini-flash-2.5) ---
Type 'exit' or 'quit' to end the conversation.
[STEP 1] Initializing client and configuring session...
👤 You > Can you add an event to my calendar?
🤖 Assistant > I can do that. What is the title of the event?
👤 You > Team sync
🤖 Assistant > Okay, and on what date and time?
👤 You > Tomorrow at 10am for 45 minutes
🤖 Assistant >
[TOOL EXECUTE] ✅ Success! Creating event: "Team sync" on 2024-10-29 at 10:00 for 45 minutes.
OK. I've added "Team sync" to your calendar for tomorrow at 10:00 AM.