File size: 2,813 Bytes
496166b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from smolagents import DuckDuckGoSearchTool, HfApiModel, load_tool, CodeAgent, PythonInterpreterTool, VisitWebpageTool, \
    Tool
import hashlib
import json
from transformers import AutoTokenizer, AutoModelForCausalLM
import os


class ModelMathTool(Tool):
    name = "math_model"
    description = "Answers advanced math questions using a pretrained math model."

    inputs = {
        "problem": {
            "type": "string",
            "description": "Math problem to solve.",
        }
    }

    output_type = "string"

    def __init__(self, model_id="Qwen/Qwen2.5-Math-7B"):
        print(f"Loading math model: {model_id}")
        self.tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
        self.model = HfApiModel(model_id=model_id, max_tokens=512)

    def forward(self, problem: str) -> str:
        print(f"[MathModelTool] Question: {problem}")
        response = self.model.__call__(problem)
        return response


# (Keep Constants as is)
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"

web_search = DuckDuckGoSearchTool()
python_interpreter = PythonInterpreterTool()
visit_webpage_tool = VisitWebpageTool()
model_math_tool = ModelMathTool()

# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'

model = HfApiModel(model_id="HuggingFaceH4/zephyr-7b-beta", max_tokens=512, token=tok)


def get_cache_key(question: str) -> str:
    return hashlib.sha256(question.encode()).hexdigest()


def load_cached_answer(question: str) -> str | None:
    key = get_cache_key(question)
    path = f"cache/{key}.json"
    if os.path.exists(path):
        with open(path, "r") as f:
            data = json.load(f)
            return data.get("answer")
    return None


def cache_answer(question: str, answer: str):
    key = get_cache_key(question)
    path = f"cache/{key}.json"
    with open(path, "w") as f:
        json.dump({"question": question, "answer": answer}, f)


class BasicAgent:
    def __init__(self):
        print("BasicAgent initialized.")
        self.agent = CodeAgent(
            model=model,
            tools=[model_math_tool],
            max_steps=1,
            verbosity_level=0,
            grammar=None,
            planning_interval=3,

        )

    def __call__(self, question: str) -> str:
        print(f"Agent received question (first 50 chars): {question[:50]}...")
        answer = self.agent.run(question)
        return answer



agent = BasicAgent()

response = agent.__call__(question="How much is 2*2?")
print(response)