BasicsFunction CallingMessagesOpenAIAnthropicGoogle
Problem
Implement format_tool_message(call_id, result) returning {"role": "tool", "tool_call_id": call_id, "content": content_str}. If result is already a str, use it directly; otherwise serialize it deterministically with json.dumps(result, sort_keys=True).
Why It Matters: OpenAI, Anthropic, and Gemini tool-calling APIs require tool outputs to be strings linked to their originating tool_call_id.
Function Signature
import json
def format_tool_message(call_id: str, result) -> dict:
"""Format a tool result into a standard role='tool' message dict."""
Sample Input & Output
Example 1: Dict Result Serialized Deterministically
Input:
call_id = "call_1", result = {"temp": 22, "city": "LA"}
Expected Output:
{"role": "tool", "tool_call_id": "call_1", "content": '{"city": "LA", "temp": 22}'}
Explanation: Non-string dicts are JSON-serialized with sort_keys=True for deterministic caching and testing.
Example 2: Plain String Result
Input:
call_id = "call_2", result = "File saved successfully."
Expected Output:
{"role": "tool", "tool_call_id": "call_2", "content": "File saved successfully."}
Explanation: Strings are inserted directly without double-quoting them via json.dumps.
Constraints & Edge Cases
- Return
{'role': 'tool', 'tool_call_id': call_id, 'content': str}. - Use
isinstance(result, str)before callingjson.dumps. - Pass
sort_keys=Truetojson.dumps.
Constraints & Evaluation Criteria
- Return `{'role': 'tool', 'tool_call_id': call_id, 'content': str}`.
Hints
Learn the Concept First
Resilient Tool Execution: Exponential Backoff, Circuit Breakers & Fallbacks
Agentic AI · Visual Chapter
Voice, Realtime & Multimodal Agents: VAD, Barge-In & Streaming Loops
Agentic AI · Visual Chapter
Stateful Agent Graphs (LangGraph Style): Nodes, Conditional Edges & Time-Travel Checkpoints
Agentic AI · Visual Chapter
Python 3⌘/Ctrl+Enter to Run · ⌘/Ctrl+Shift+Enter to Submit
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
call_1, {'temp': 22}Expected Output / Criteria
JSON content string