George Sergia commited on
Commit
bbfc23a
·
1 Parent(s): 7626150

Use llama_index as agent framework

Browse files
Files changed (4) hide show
  1. .gitignore +2 -0
  2. agent.py +25 -22
  3. app.py +14 -12
  4. requirements.txt +5 -1
.gitignore CHANGED
@@ -172,3 +172,5 @@ cython_debug/
172
 
173
  # PyPI configuration file
174
  .pypirc
 
 
 
172
 
173
  # PyPI configuration file
174
  .pypirc
175
+
176
+ *.old
agent.py CHANGED
@@ -1,27 +1,30 @@
1
- from smolagents import DuckDuckGoSearchTool, CodeAgent, HfApiModel
 
 
 
 
2
  import os
3
  import yaml
4
 
5
- class BasicAgent:
6
- def __init__(self):
7
- print("BasicAgent initialized.")
 
 
8
 
9
- def __call__(self, question: str) -> str:
10
- print(f"Agent received question (first 50 chars): {question[:50]}...")
11
-
12
- with open("prompts.yaml", 'r') as stream:
13
- prompt_templates = yaml.safe_load(stream)
 
 
 
 
 
 
 
14
 
15
- model = HfApiModel(model_id="Qwen/Qwen3-235B-A22B")
16
- search_tool = DuckDuckGoSearchTool()
17
-
18
- agent = CodeAgent(
19
- tools=[search_tool],
20
- model=model,
21
- add_base_tools = True,
22
- prompt_templates=prompt_templates
23
- )
24
-
25
- fixed_answer = agent.run(question)
26
- print(f"Agent returning fixed answer: {fixed_answer}")
27
- return fixed_answer
 
1
+ from llama_index.core.agent.workflow import AgentWorkflow
2
+ from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
3
+ from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec
4
+ from llama_index.core.tools import FunctionTool
5
+ from llama_index.core.workflow import Context
6
  import os
7
  import yaml
8
 
9
+ async def main(query: str, hf_token: str) -> str:
10
+ hugging_face_llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct", token=hf_token)
11
+
12
+ ddg = DuckDuckGoSearchToolSpec()
13
+ search_tool = FunctionTool.from_defaults(ddg.duckduckgo_full_search)
14
 
15
+ agent = AgentWorkflow.from_tools_or_functions(
16
+ [search_tool],
17
+ llm=hugging_face_llm,
18
+ system_prompt="""
19
+ You are a general AI assistant. I will ask you a question.
20
+ Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
21
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
22
+ If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
23
+ If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
24
+ If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
25
+ """
26
+ )
27
 
28
+ ctx = Context(agent)
29
+ response = await agent.run(query, ctx=ctx)
30
+ return response
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -3,12 +3,9 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
6
- from agent import BasicAgent
7
  from dotenv.main import load_dotenv
8
-
9
- load_dotenv()
10
-
11
- HF_TOKEN = os.getenv("HF_TOKEN")
12
 
13
  # (Keep Constants as is)
14
  # --- Constants ---
@@ -22,6 +19,11 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
22
  Fetches all questions, runs the BasicAgent on them, submits all answers,
23
  and displays the results.
24
  """
 
 
 
 
 
25
  # --- Determine HF Space Runtime URL and Repo URL ---
26
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
27
 
@@ -35,13 +37,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
35
  api_url = DEFAULT_API_URL
36
  questions_url = f"{api_url}/questions"
37
  submit_url = f"{api_url}/submit"
38
-
39
  # 1. Instantiate Agent ( modify this part to create your agent)
40
- try:
41
- agent = BasicAgent()
42
- except Exception as e:
43
- print(f"Error instantiating agent: {e}")
44
- return f"Error initializing agent: {e}", None
45
  # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
46
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
47
  print(agent_code)
@@ -78,7 +80,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
78
  print(f"Skipping item with missing task_id or question: {item}")
79
  continue
80
  try:
81
- submitted_answer = agent(question_text)
82
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
83
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
84
  except Exception as e:
 
3
  import requests
4
  import inspect
5
  import pandas as pd
 
6
  from dotenv.main import load_dotenv
7
+ import agent
8
+ import asyncio
 
 
9
 
10
  # (Keep Constants as is)
11
  # --- Constants ---
 
19
  Fetches all questions, runs the BasicAgent on them, submits all answers,
20
  and displays the results.
21
  """
22
+
23
+ load_dotenv()
24
+
25
+ HF_TOKEN = os.getenv("HF_TOKEN")
26
+
27
  # --- Determine HF Space Runtime URL and Repo URL ---
28
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
 
 
37
  api_url = DEFAULT_API_URL
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
+
41
  # 1. Instantiate Agent ( modify this part to create your agent)
42
+ #try:
43
+ # agent = BasicAgent()
44
+ #except Exception as e:
45
+ # print(f"Error instantiating agent: {e}")
46
+ # return f"Error initializing agent: {e}", None
47
  # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
48
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
  print(agent_code)
 
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
  try:
83
+ submitted_answer = asyncio.run(agent.main(question_text, HF_TOKEN))
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
requirements.txt CHANGED
@@ -2,4 +2,8 @@ gradio
2
  requests
3
  smolagents
4
  pyyaml
5
- dotenv
 
 
 
 
 
2
  requests
3
  smolagents
4
  pyyaml
5
+ dotenv
6
+ llama-index
7
+ llama_index.llms.huggingface_api
8
+ llama_index.tools.duckduckgo
9
+ asyncio