Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
@@ -1,55 +1,79 @@
|
|
1 |
-
|
|
|
|
|
2 |
from langchain.tools import tool
|
3 |
from langchain.agents import initialize_agent, AgentType
|
4 |
-
|
5 |
-
from langchain_community.llms.huggingface_hub import HuggingFaceHub
|
6 |
from langchain_community.document_loaders import WikipediaLoader
|
7 |
|
8 |
-
# 1) Define
|
9 |
|
10 |
@tool
|
11 |
def calculator(expr: str) -> str:
|
12 |
-
"""
|
13 |
-
Safely evaluates a math expression and returns the result.
|
14 |
-
"""
|
15 |
try:
|
16 |
-
|
17 |
-
result = eval(expr, {"__builtins__": {}})
|
18 |
-
return str(result)
|
19 |
except Exception as e:
|
20 |
return f"Error: {e}"
|
21 |
|
22 |
@tool
|
23 |
def wiki_search(query: str) -> str:
|
24 |
-
"""
|
25 |
-
|
26 |
-
"""
|
27 |
-
loader = WikipediaLoader(query=query, load_max_docs=2)
|
28 |
-
docs = loader.load()
|
29 |
return "\n\n".join(d.page_content for d in docs)
|
30 |
|
31 |
-
# 2) Build
|
32 |
|
33 |
class BasicAgent:
|
34 |
def __init__(self):
|
35 |
-
|
36 |
-
assert
|
37 |
-
#
|
38 |
-
self.
|
39 |
-
|
40 |
-
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
42 |
)
|
43 |
-
|
|
|
44 |
self.agent = initialize_agent(
|
45 |
[calculator, wiki_search],
|
46 |
self.llm,
|
47 |
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
|
48 |
-
verbose=
|
49 |
-
max_iterations=
|
50 |
-
early_stopping_method="generate"
|
51 |
)
|
52 |
|
53 |
def __call__(self, question: str) -> str:
|
54 |
-
#
|
55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agent.py
|
2 |
+
|
3 |
+
import os, requests
|
4 |
from langchain.tools import tool
|
5 |
from langchain.agents import initialize_agent, AgentType
|
6 |
+
|
|
|
7 |
from langchain_community.document_loaders import WikipediaLoader
|
8 |
|
9 |
+
# 1) Define your tools
|
10 |
|
11 |
@tool
|
12 |
def calculator(expr: str) -> str:
|
13 |
+
"""Safely evaluate a math expression."""
|
|
|
|
|
14 |
try:
|
15 |
+
return str(eval(expr, {"__builtins__": {}}))
|
|
|
|
|
16 |
except Exception as e:
|
17 |
return f"Error: {e}"
|
18 |
|
19 |
@tool
|
20 |
def wiki_search(query: str) -> str:
|
21 |
+
"""Fetch up to 2 Wikipedia pages for the query."""
|
22 |
+
docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
|
|
|
|
|
|
23 |
return "\n\n".join(d.page_content for d in docs)
|
24 |
|
25 |
+
# 2) Build your Agent
|
26 |
|
27 |
class BasicAgent:
|
28 |
def __init__(self):
|
29 |
+
token = os.environ.get("HF_TOKEN")
|
30 |
+
assert token, "HF_TOKEN secret is missing!"
|
31 |
+
# We call the free inference endpoint directly
|
32 |
+
self.api_url = "https://api-inference.huggingface.co/models/google/flan-t5-large"
|
33 |
+
self.headers = {"Authorization": f"Bearer {token}"}
|
34 |
+
|
35 |
+
# LangChain’s HF wrapper
|
36 |
+
from langchain.llms import HuggingFaceEndpoint
|
37 |
+
self.llm = HuggingFaceEndpoint(
|
38 |
+
endpoint_url=self.api_url,
|
39 |
+
headers=self.headers,
|
40 |
+
model_kwargs={"temperature": 0.0, "max_new_tokens": 200},
|
41 |
)
|
42 |
+
|
43 |
+
# Register tools and initialize a React agent
|
44 |
self.agent = initialize_agent(
|
45 |
[calculator, wiki_search],
|
46 |
self.llm,
|
47 |
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
|
48 |
+
verbose=True, # see what it’s doing in the logs
|
49 |
+
max_iterations=5, # let it call up to 5 tools
|
50 |
+
early_stopping_method="generate"
|
51 |
)
|
52 |
|
53 |
def __call__(self, question: str) -> str:
|
54 |
+
# (Optional) Inject 3 hard-coded examples to guide format
|
55 |
+
EXAMPLES = """
|
56 |
+
Q: What is 2+2?
|
57 |
+
A: 4
|
58 |
+
|
59 |
+
Q: If a car goes 60 km/h for 2 hours, how far?
|
60 |
+
A: 120
|
61 |
+
|
62 |
+
Q: What is the capital of France?
|
63 |
+
A: Paris
|
64 |
+
"""
|
65 |
+
prompt = (
|
66 |
+
f"Answer the following question using the tools below. "
|
67 |
+
f"First think (internally), then output **only** the final answer—no chain-of-thought.\n\n"
|
68 |
+
f"Tools:\n"
|
69 |
+
f" • calculator(expr: str) -> str\n"
|
70 |
+
f" • wiki_search(query: str) -> str\n\n"
|
71 |
+
f"### Examples ###{EXAMPLES}\n"
|
72 |
+
f"### New Question ###\n{question}"
|
73 |
+
)
|
74 |
+
|
75 |
+
# Run the agent
|
76 |
+
raw = self.agent.run(prompt)
|
77 |
+
|
78 |
+
# Extract the last line as the answer
|
79 |
+
return raw.splitlines()[-1].strip()
|