Update agent.py
Browse files
agent.py
CHANGED
@@ -1,14 +1,15 @@
|
|
1 |
-
# agent.py
|
2 |
|
|
|
3 |
from llama_index.llms.openai import OpenAI
|
4 |
-
from llama_index.core.agent.
|
5 |
from llama_index.core.tools import FunctionTool
|
6 |
|
7 |
from langchain_community.tools import DuckDuckGoSearchRun, WikipediaQueryRun
|
8 |
from langchain_experimental.tools.python.tool import PythonREPLTool
|
9 |
from langchain_community.document_loaders import YoutubeLoader
|
10 |
|
11 |
-
# --- Tool
|
12 |
def search_duckduckgo(query: str) -> str:
|
13 |
return DuckDuckGoSearchRun().run(query)
|
14 |
|
@@ -23,7 +24,7 @@ def get_youtube_transcript(url: str) -> str:
|
|
23 |
docs = loader.load()
|
24 |
return " ".join(doc.page_content for doc in docs)
|
25 |
|
26 |
-
# ---
|
27 |
TOOLS = [
|
28 |
FunctionTool.from_defaults(search_duckduckgo),
|
29 |
FunctionTool.from_defaults(search_wikipedia),
|
@@ -31,17 +32,22 @@ TOOLS = [
|
|
31 |
FunctionTool.from_defaults(get_youtube_transcript),
|
32 |
]
|
33 |
|
34 |
-
# ---
|
35 |
llm = OpenAI(model="gpt-4")
|
36 |
|
37 |
-
# ---
|
38 |
-
agent =
|
39 |
-
TOOLS,
|
40 |
llm=llm,
|
41 |
-
system_prompt="You are a helpful
|
42 |
)
|
43 |
|
44 |
-
# ---
|
45 |
async def answer_question(question: str) -> str:
|
46 |
-
|
47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agent.py – ReActAgent version with timeouts
|
2 |
|
3 |
+
import asyncio
|
4 |
from llama_index.llms.openai import OpenAI
|
5 |
+
from llama_index.core.agent.react import ReActAgent
|
6 |
from llama_index.core.tools import FunctionTool
|
7 |
|
8 |
from langchain_community.tools import DuckDuckGoSearchRun, WikipediaQueryRun
|
9 |
from langchain_experimental.tools.python.tool import PythonREPLTool
|
10 |
from langchain_community.document_loaders import YoutubeLoader
|
11 |
|
12 |
+
# --- Tool Wrappers ---
|
13 |
def search_duckduckgo(query: str) -> str:
|
14 |
return DuckDuckGoSearchRun().run(query)
|
15 |
|
|
|
24 |
docs = loader.load()
|
25 |
return " ".join(doc.page_content for doc in docs)
|
26 |
|
27 |
+
# --- Tools ---
|
28 |
TOOLS = [
|
29 |
FunctionTool.from_defaults(search_duckduckgo),
|
30 |
FunctionTool.from_defaults(search_wikipedia),
|
|
|
32 |
FunctionTool.from_defaults(get_youtube_transcript),
|
33 |
]
|
34 |
|
35 |
+
# --- LLM ---
|
36 |
llm = OpenAI(model="gpt-4")
|
37 |
|
38 |
+
# --- ReActAgent ---
|
39 |
+
agent = ReActAgent(
|
40 |
+
tools=TOOLS,
|
41 |
llm=llm,
|
42 |
+
system_prompt="You are a helpful assistant that uses tools to answer questions accurately and efficiently."
|
43 |
)
|
44 |
|
45 |
+
# --- Runner with timeout ---
|
46 |
async def answer_question(question: str) -> str:
|
47 |
+
try:
|
48 |
+
result = await asyncio.wait_for(agent.run(question), timeout=60)
|
49 |
+
return str(result)
|
50 |
+
except asyncio.TimeoutError:
|
51 |
+
return "[TIMEOUT]"
|
52 |
+
except Exception as e:
|
53 |
+
return f"[ERROR] {e}"
|