Route Tool Call Name to Python Handler Dict
Routes a tool call name to the correct Python handler function using a dictionary lookup, returning an error for unknown tools.
Python code
29 linesdef get_name():
return {"name": "Alice"}
def get_age():
return {"age": 30}
def get_email():
return {"email": "alice@example.com"}
handlers = {
"get_name": get_name,
"get_age": get_age,
"get_email": get_email,
}
def route(tool_call):
handler = handlers.get(tool_call["name"])
if handler is None:
return {"error": f"Unknown tool: {tool_call['name']}"}
return handler()
if __name__ == "__main__":
tool_calls = [
{"name": "get_name"},
{"name": "get_email"},
{"name": "unknown_tool"},
]
for call in tool_calls:
print(f"{call['name']}: {route(call)}")
Output
get_name: {'name': 'Alice'}
get_email: {'email': 'alice@example.com'}
unknown_tool: {'error': "Unknown tool: unknown_tool"}
How it works
This pattern maps AI tool-call names to Python functions using a dictionary. The get method safely returns None when the key is missing, letting us return a helpful error. Each handler is a callable that receives no arguments here, but you can extend handlers to accept parameters from the tool call. This approach is central to building reliable agentic workflows where LLM requests trigger specific backend operations.
Common mistakes
- Forgetting to include the `if __name__ == '__main__':` guard in production scripts.
- Assuming every tool name exists without using `.get()` and returning a fallback.
- Passing extra arguments to handlers that don't accept them.
Variations
- Use `functools.partial` to pre-bind arguments for handlers that need parameters.
- Use a `match` statement with `case` blocks if you prefer explicit branching over a dict.
Real-world use cases
- Routing LLM-generated function calls to backend services in a chatbot.
- Mapping API endpoint names to serverless handlers in a microservice gateway.
- Dispatching user commands to plugin functions in a CLI application.
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.