AC-Angelo93 commited on
Commit
88f109e
·
verified ·
1 Parent(s): f0b4404

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +26 -56
agent.py CHANGED
@@ -1,85 +1,55 @@
1
- # agent.py
2
-
3
  import os
4
  from langchain.tools import tool
5
- # new, works with langchain-community>=0.2.17
6
- from langchain_community.llms.huggingface_hub import HuggingFaceHub
7
-
8
  from langchain.agents import initialize_agent, AgentType
9
- from retrieval import retrieve_examples, wiki_context
10
-
11
- # Load the system prompt
12
- SYSTEM_PROMPT = open("system_prompt.txt", "r").read().strip()
13
-
14
- # --- 1) Define your tools with @tool ---
15
 
16
- @tool
17
- def few_shot_retriever(query: str) -> str:
18
- """
19
- Returns a few-shot snippet (top-k examples) for this question.
20
- """
21
- return retrieve_examples(query, k=3)
22
 
23
  @tool
24
- def wiki_search(query: str) -> str:
25
- """
26
- Returns concatenated Wikipedia pages for factual lookup.
27
- """
28
- return wiki_context(query, max_docs=1)
29
-
30
- @tool
31
- def calculator(expression: str) -> str:
32
  """
33
  Safely evaluates a math expression and returns the result.
34
  """
35
  try:
36
- # VERY simple eval: you can sandbox this further
37
- result = eval(expression, {"__builtins__": {}})
38
  return str(result)
39
  except Exception as e:
40
  return f"Error: {e}"
41
 
42
- # --- 2) Build your agent class ---
 
 
 
 
 
 
 
 
 
43
 
44
  class BasicAgent:
45
  def __init__(self):
46
- print("🔧 Initializing tool-using agent…")
47
- # Read your HF_TOKEN from Secrets
48
- self.hf_token = os.environ.get("HF_TOKEN")
49
- assert self.hf_token, "HF_TOKEN environment variable not set!"
50
-
51
- # 2a) LLM binding via HuggingFaceHub
52
  self.llm = HuggingFaceHub(
53
  repo_id="HuggingFaceH4/zephyr-7b-beta",
 
54
  model_kwargs={"temperature": 0.2, "max_new_tokens": 250},
55
- huggingfacehub_api_token=self.hf_token
56
  )
57
-
58
- # 2b) Collect the decorated tools
59
- self.tools = [few_shot_retriever, wiki_search, calculator]
60
-
61
- # 2c) Initialize a React-style agent
62
  self.agent = initialize_agent(
63
- self.tools,
64
  self.llm,
65
  agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
66
  verbose=False,
67
  max_iterations=3,
68
- early_stopping_method="generate"
69
  )
70
 
71
  def __call__(self, question: str) -> str:
72
- # Prepend your system_prompt for clean FINAL ANSWER formatting
73
- prompt = f"{SYSTEM_PROMPT}\n\nQUESTION: {question}"
74
- try:
75
- answer = self.agent.run(prompt)
76
- except Exception as e:
77
- print(f"❌ Agent.run() error: {e}")
78
- return f"Error: {e}"
79
-
80
- # The agent should already obey your "FINAL ANSWER:" rule,
81
- # but just in case, strip out everything before it:
82
- if "FINAL ANSWER:" in answer:
83
- return answer.split("FINAL ANSWER:")[-1].strip()
84
- # fallback to last line
85
- return answer.splitlines()[-1].strip()
 
 
 
1
  import os
2
  from langchain.tools import tool
 
 
 
3
  from langchain.agents import initialize_agent, AgentType
4
+ # HF-hub integration lives in langchain_community now:
5
+ from langchain_community.llms.huggingface_hub import HuggingFaceHub
6
+ from langchain_community.document_loaders import WikipediaLoader
 
 
 
7
 
8
+ # 1) Define Tools
 
 
 
 
 
9
 
10
  @tool
11
+ def calculator(expr: str) -> str:
 
 
 
 
 
 
 
12
  """
13
  Safely evaluates a math expression and returns the result.
14
  """
15
  try:
16
+ # sandbox a bit
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
+ Loads 1–2 Wikipedia pages for the query and concatenates their text.
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 the Agent
32
 
33
  class BasicAgent:
34
  def __init__(self):
35
+ hf_token = os.environ.get("HF_TOKEN")
36
+ assert hf_token, "HF_TOKEN secret is missing!"
37
+ # Bind to a free-tier HF model
 
 
 
38
  self.llm = HuggingFaceHub(
39
  repo_id="HuggingFaceH4/zephyr-7b-beta",
40
+ huggingfacehub_api_token=hf_token,
41
  model_kwargs={"temperature": 0.2, "max_new_tokens": 250},
 
42
  )
43
+ # Register your tools
 
 
 
 
44
  self.agent = initialize_agent(
45
+ [calculator, wiki_search],
46
  self.llm,
47
  agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
48
  verbose=False,
49
  max_iterations=3,
50
+ early_stopping_method="generate",
51
  )
52
 
53
  def __call__(self, question: str) -> str:
54
+ # Run the agent; it will decide when (and how) to call tools
55
+ return self.agent.run(question)