Tool Use Patterns
🎯 Trigger Conditions
Use when asked about tool use, function calling, or external API integration with DSPy.
📚 Prerequisites
dspypackage installed- Tools/APIs available
- Tool schema defined
🛠️ Tool Use Patterns
1. Basic Tool Use
from dspy import Tool
# Define tool
def search_web(query):
"""Search the web for information."""
results = web_search(query)
return results[:5]
# Register tool
tools = {
"search": Tool(
name="search",
fn=search_web,
description="Search the web"
)
}
# Use with DSPy
class ToolUseProgram(dspy.Module):
def __init__(self):
self.tool_use = dspy.ToolUse(tools=tools)
def forward(self, question):
return self.tool_use(question=question)
2. Tool Chaining
class ToolChaining(dspy.Module):
def __init__(self):
self.search = Tool(name="search", fn=search_web)
self.summarize = Tool(name="summarize", fn=summarize_text)
self.translate = Tool(name="translate", fn=translate_text)
def forward(self, question):
# Chain tools
results = self.search(question)
summary = self.summarize(results)
translated = self.translate(summary, target_lang="es")
return translated
3. Conditional Tool Use
class ConditionalToolUse(dspy.Module):
def __init__(self):
self.classifier = dspy.Predict("question -> tool")
self.tools = {
"search": search_web,
"calculate": calculate,
"translate": translate_text
}
def forward(self, question):
# Classify which tool to use
tool_name = self.classifier(question=question).tool
tool = self.tools[tool_name]
return tool(question)
4. Parallel Tool Execution
import asyncio
async def parallel_tool_use(tools, inputs):
# Execute tools in parallel
tasks = [tool(input) for tool, input in zip(tools, inputs)]
results = await asyncio.gather(*tasks)
return results
# Use with DSPy
class ParallelToolUse(dspy.Module):
def __init__(self, tools):
self.tools = tools
async def forward(self, inputs):
return await parallel_tool_use(self.tools, inputs)
⚠️ Pitfalls
- Tool reliability: External tools can fail or return errors
- Latency: Tool calls add latency to responses
- Security: Tool inputs can be malicious
- Cost: Tool usage may incur costs