How to Mock OpenAI Tool Call Messages in Python
Create an assistant message with a function tool call in OpenAI's chat format, useful for testing and mocking.
pip install openai
Python code
30 linesfrom openai import OpenAI
def mock_tool_call(tool_name: str, arguments: dict) -> dict:
"""Simulate a tool call message in OpenAI style."""
return {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_" + "a1b2c3d4e5f6",
"type": "function",
"function": {
"name": tool_name,
"arguments": __import__("json").dumps(arguments, ensure_ascii=False),
},
}
],
}
if __name__ == "__main__":
# Example usage with a weather lookup tool
message = mock_tool_call(
tool_name="get_weather",
arguments={"city": "Paris", "unit": "celsius"},
)
print(message)
print("Tool name:", message["tool_calls"][0]["function"]["name"])
print("Arguments:", message["tool_calls"][0]["function"]["arguments"])
Output
{'role': 'assistant', 'content': None, 'tool_calls': [{'id': 'call_a1b2c3d4e5f6', 'type': 'function', 'function': {'name': 'get_weather', 'arguments': '{"city": "Paris", "unit": "celsius"}'}}]}
Tool name: get_weather
Arguments: {"city": "Paris", "unit": "celsius"}
How it works
The function builds a dictionary that matches the structure OpenAI expects for assistant messages with tool calls. It uses json.dumps to serialize the arguments into a string, as required by the API. This mock is handy for unit tests where you need to simulate an assistant requesting a tool without calling the LLM. The __import__("json") trick keeps the code self-contained, but importing json directly is cleaner.
Common mistakes
- Omitting `content` field or setting it to a non-None value when tool_calls are present.
- Not serializing the arguments dictionary to a string with `json.dumps`.
- Using a fake tool call ID that doesn't match OpenAI's format (should start with 'call_').
Variations
- Use `json.dumps(arguments)` with `ensure_ascii=False` to preserve Unicode characters.
- Create a helper class to manage multiple tool calls in a single message.
Real-world use cases
- Testing your agent logic without calling the OpenAI API to save costs.
- Simulating a tool-call step in a retrieval-augmented generation (RAG) pipeline.
- Setting up fixtures for integration tests of function-calling flows.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.