Spaces:
Running
Running
File size: 6,727 Bytes
3193174 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | """
Agent with tools β built-in and custom.
Demonstrates:
1. Custom tools via the ``@tool`` decorator (fibonacci, is_prime, calculate)
2. Built-in ``code_interpreter`` tool
3. Built-in ``shell`` tool
4. Built-in ``file_search`` tool
Configure your LLM via environment variables:
LLM_API_KEY, LLM_BASE_URL, LLM_MODEL
Run:
python -m examples.agent_with_tools_example
"""
import math
import os
from builder import GraphBuilder
from execution import MACPRunner
from tools import (
CodeInterpreterTool,
FileSearchTool,
ShellTool,
create_openai_caller,
get_registry,
tool,
)
# ββ Constants βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
MIN_PRIME_NUMBER = 2
# ββ Custom tools βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@tool
def fibonacci(n: int) -> str:
"""Calculate the n-th Fibonacci number."""
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return str(a)
@tool
def is_prime(n: int) -> str:
"""Check if a number is prime. Returns 'True' or 'False'."""
if n < MIN_PRIME_NUMBER:
return "False"
for i in range(MIN_PRIME_NUMBER, math.isqrt(n) + 1):
if n % i == 0:
return "False"
return "True"
@tool
def calculate(expression: str) -> str:
"""Evaluate a safe math expression (sqrt, sin, cos, pi, e)."""
allowed = {"sqrt": math.sqrt, "sin": math.sin, "cos": math.cos, "pi": math.pi, "e": math.e}
try:
return str(eval(expression, {"__builtins__": {}}, allowed))
except Exception as exc:
return f"Error: {exc}"
# ββ Shared helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _setup_tools() -> None:
"""Register built-in tools once."""
registry = get_registry()
registry.register(ShellTool(timeout=10))
registry.register(CodeInterpreterTool(timeout=10, safe_mode=True))
registry.register(FileSearchTool(base_directory=".", max_results=10))
def _create_llm():
return create_openai_caller(
base_url=os.getenv("LLM_BASE_URL", "http://localhost:8000/v1"),
api_key=os.getenv("LLM_API_KEY", "your-api-key"),
model=os.getenv("LLM_MODEL", "gpt-4o-mini"),
temperature=0.1,
)
def _header(title: str) -> None:
print(f"\n{'β' * 60}\n {title}\n{'β' * 60}")
# ββ Example 1: Custom math tools ββββββββββββββββββββββββββββββββββββββββββββ
def example_custom_math_tools():
"""Agent uses fibonacci, is_prime, and calculate tools."""
_header("1 Β· Custom Math Tools")
builder = GraphBuilder()
builder.add_agent(
agent_id="math_agent",
display_name="Math Agent",
persona="a helpful math assistant",
description="Solves math problems using available tools.",
tools=["fibonacci", "is_prime", "calculate"],
)
builder.add_task(query="Calculate fibonacci(10), check if 17 is prime, and compute 2**10")
builder.connect_task_to_agents(agent_ids=["math_agent"])
graph = builder.build()
result = MACPRunner(llm_caller=_create_llm()).run_round(graph)
print(f" Task : {graph.query}")
print(f" Answer : {result.final_answer}")
# ββ Example 2: Code interpreter βββββββββββββββββββββββββββββββββββββββββββββ
def example_code_interpreter():
"""Agent runs Python code via the code_interpreter tool."""
_header("2 Β· Code Interpreter")
builder = GraphBuilder()
builder.add_agent(
agent_id="coder",
display_name="Python Coder",
persona="a Python programmer",
description="Executes Python code to solve problems.",
tools=["code_interpreter"],
)
builder.add_task(query="Use code_interpreter to calculate 2**100")
builder.connect_task_to_agents(agent_ids=["coder"])
graph = builder.build()
result = MACPRunner(llm_caller=_create_llm()).run_round(graph)
print(f" Task : {graph.query}")
print(f" Answer : {result.final_answer}")
# ββ Example 3: Shell tool βββββββββββββββββββββββββββββββββββββββββββββββββββ
def example_shell_tool():
"""Agent executes a shell command."""
_header("3 Β· Shell Tool")
builder = GraphBuilder()
builder.add_agent(
agent_id="sysadmin",
display_name="System Admin",
persona="a system administrator",
description="Executes shell commands.",
tools=["shell"],
)
builder.add_task(query="Use shell to run: echo 'Hello from shell'")
builder.connect_task_to_agents(agent_ids=["sysadmin"])
graph = builder.build()
result = MACPRunner(llm_caller=_create_llm()).run_round(graph)
print(f" Task : {graph.query}")
print(f" Answer : {result.final_answer}")
# ββ Example 4: File search ββββββββββββββββββββββββββββββββββββββββββββββββββ
def example_file_search():
"""Agent searches for files matching a pattern."""
_header("4 Β· File Search")
builder = GraphBuilder()
builder.add_agent(
agent_id="searcher",
display_name="File Searcher",
persona="a file search specialist",
description="Searches for files by pattern.",
tools=["file_search"],
)
builder.add_task(query="Find Python files (pattern='*.py')")
builder.connect_task_to_agents(agent_ids=["searcher"])
graph = builder.build()
result = MACPRunner(llm_caller=_create_llm()).run_round(graph)
print(f" Task : {graph.query}")
print(f" Answer : {result.final_answer[:200]}β¦")
# ββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def main():
_setup_tools()
example_custom_math_tools()
example_code_interpreter()
example_shell_tool()
example_file_search()
print(f"\n{'=' * 60}")
print("All tool examples completed β
")
if __name__ == "__main__":
main()
|