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.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 14 views 0 copies

Requires third-party packages — install first
pip install openai

Python code

30 lines
Python 3.9+
from 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

stdout
{'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

  1. Use `json.dumps(arguments)` with `ensure_ascii=False` to preserve Unicode characters.
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.