Tool Invocation Patterns in LLM Agents: From Simple to Complex
Briefly
Step-by-step guide to designing and implementing tool invocation in LLM agents: from simple function calling to complex multi-agent scenarios with routing and validation.
1. Defining the Tool Schema
Each tool is described by a JSON schema. Minimum set of fields: name, description, parameters (JSON Schema).
Example schema for knowledge base search:
{
"name": "search_kb",
"description": "Search the knowledge base. Returns relevant fragments.",
"parameters": {
"type": "object",
"properties": {
"query": { "type": "string", "description": "Search query" },
"limit": { "type": "integer", "default": 5 }
},
"required": ["query"]
}
}
2. Basic Tool Invocation Cycle
Classic cycle: the model decides which tool to call, the agent executes, and the result is returned to the model.
import json
from openai import OpenAI
client = OpenAI()
def search_kb(query: str, limit: int = 5) -> list[dict]:
# here is the call to vector DB or search API
return [{"title": "Example", "text": "Fragment text"}]
tools = [
{
"type": "function",
"function": {
"name": "search_kb",
"description": "Search the knowledge base",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"limit": {"type": "integer"}
},
"required": ["query"]
}
}
}
]
messages = [{"role": "user", "content": "Find information about RAG"}]
for _ in range(5): # maximum 5 iterations
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
msg = response.choices[0].message
messages.append(msg)
if msg.tool_calls:
for tc in msg.tool_calls:
args = json.loads(tc.function.arguments)
if tc.function.name == "search_kb":
result = search_kb(**args)
else:
result = {"error": "Unknown tool"}
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"content": json.dumps(result, ensure_ascii=False)
})
else:
break
print(msg.content)
3. Error Handling and Retries
Tools may fail. Return an error to the model so it can correct the request.
def safe_call(func, **kwargs):
try:
return func(**kwargs)
except Exception as e:
return {"error": str(e), "suggestion": "Try changing the parameters"}
4. Argument Validation
Before invoking a tool, validate the arguments against the schema. Use the jsonschema library.
from jsonschema import validate, ValidationError
def validate_args(schema, args):
try:
validate(instance=args, schema=schema)
return True, None
except ValidationError as e:
return False, str(e)
5. Routing Between Tools
When there are many tools, the model may make incorrect choices. Use a semantic router for pre-filtering.
from sentence_transformers import SentenceTransformer
import numpy as np
model = SentenceTransformer('all-MiniLM-L6-v2')
def route_query(query: str, tool_descriptions: dict) -> str:
q_vec = model.encode(query)
best_tool = None
best_score = -1
for name, desc in tool_descriptions.items():
d_vec = model.encode(desc)
score = np.dot(q_vec, d_vec) / (np.linalg.norm(q_vec) * np.linalg.norm(d_vec))
if score > best_score:
best_score = score
best_tool = name
return best_tool
6. Multi-Agent Orchestration
With many tools, break them into groups and assign each group to a sub-agent. The orchestrator decides which agent to pass the request to.
graph TD
A[User] --> B[Orchestrator]
B --> C[Search Agent]
B --> D[Analytics Agent]
B --> E[Action Agent]
C --> F[Search Tools]
D --> G[Analytics Tools]
E --> H[Action Tools]
7. Observability
Log each call: tool name, arguments, result, execution time. Use tracing for debugging.
import logging
logger = logging.getLogger(__name__)
def log_call(name, args, result, duration):
logger.info({"tool": name, "args": args, "result": result, "duration_ms": duration})
8. Testing
Write unit tests for each tool and integration tests for the invocation cycle. Use a mock server to simulate LLM API.
def test_search_kb():
result = search_kb("RAG")
assert len(result) > 0
9. Conclusion
Tool invocation patterns are the foundation of agent systems. Start with a simple cycle, add validation, routing, and observability as complexity grows. Related materials: agent memory, error handling, tool selection.