agent_course_open / agent.py
chezhian's picture
optimised the answer_question function
b4936e8 verified
raw
history blame
1.65 kB
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel
from smolagents import tool
import os
# Initialize model
model = InferenceClientModel(model_id="Qwen/Qwen2.5-72B-Instruct", token = os.environ.get("HF_TOKEN"))
# Custom tools with corrected docstrings
@tool
def add(a: int, b: int) -> int:
"""Add two numbers.
Args:
a: The first number to add
b: The second number to add
"""
return a + b
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two numbers.
Args:
a: The first number to multiply
b: The second number to multiply
"""
return a * b
@tool
def subtract(a: int, b: int) -> int:
"""Subtract two numbers.
Args:
a: The number to subtract from
b: The number to subtract
"""
return a - b
@tool
def divide(a: int, b: int) -> int:
"""Divide two numbers.
Args:
a: The number to divide
b: The divisor
"""
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
@tool
def modulus(a: int, b: int) -> int:
"""Get the modulus of two numbers.
Args:
a: The number to get modulus of
b: The modulus divisor
"""
return a % b
# Create agent with tools
agent = CodeAgent(
tools=[DuckDuckGoSearchTool(), add, multiply, subtract, divide, modulus],
model=model,
)
def answer_question(question: str) -> str:
result = agent.run(question)
# Ensure output starts with "FINAL ANSWER:"
if not result.strip().startswith("FINAL ANSWER:"):
result = f"FINAL ANSWER: {result.strip()}"
return result