Format a Tool Observation Message

Basics
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 calling json.dumps.
  • Pass sort_keys=True to json.dumps.

Constraints & Evaluation Criteria

  • Return `{'role': 'tool', 'tool_call_id': call_id, 'content': str}`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
call_1, {'temp': 22}
Expected Output / Criteria
JSON content string