Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
@@ -1,5 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
# ----------------------------------------------------------
|
2 |
-
# Section 0: Imports
|
3 |
# ----------------------------------------------------------
|
4 |
import json
|
5 |
import os
|
@@ -8,44 +16,34 @@ import re
|
|
8 |
import subprocess
|
9 |
import textwrap
|
10 |
import base64
|
11 |
-
import functools
|
12 |
from io import BytesIO
|
13 |
from pathlib import Path
|
14 |
|
15 |
-
# Third-party libraries
|
16 |
import requests
|
17 |
from cachetools import TTLCache
|
18 |
from PIL import Image
|
19 |
|
20 |
-
# LangChain and associated libraries
|
21 |
from langchain.schema import Document
|
22 |
from langchain.tools.retriever import create_retriever_tool
|
23 |
from langchain_community.vectorstores import FAISS
|
24 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
25 |
from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
|
26 |
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
|
27 |
-
from langchain_core.tools import Tool, tool
|
28 |
from langchain_google_genai import ChatGoogleGenerativeAI
|
29 |
from langchain_groq import ChatGroq
|
30 |
from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpoint, ChatHuggingFace
|
31 |
from langgraph.graph import START, StateGraph, MessagesState
|
32 |
from langgraph.prebuilt import ToolNode, tools_condition
|
33 |
|
34 |
-
# Environment variable loading
|
35 |
from dotenv import load_dotenv
|
36 |
load_dotenv()
|
37 |
|
38 |
-
#
|
39 |
-
|
40 |
-
|
41 |
-
JSONL_PATH = Path("metadata.jsonl")
|
42 |
-
FAISS_CACHE = Path("faiss_index.pkl")
|
43 |
-
EMBED_MODEL = "sentence-transformers/all-mpnet-base-v2"
|
44 |
-
RETRIEVER_K = 5
|
45 |
-
CACHE_TTL = 600
|
46 |
API_CACHE = TTLCache(maxsize=256, ttl=CACHE_TTL)
|
47 |
-
|
48 |
-
# Global helper for caching API calls
|
49 |
def cached_get(key: str, fetch_fn):
|
50 |
if key in API_CACHE: return API_CACHE[key]
|
51 |
val = fetch_fn()
|
@@ -53,9 +51,8 @@ def cached_get(key: str, fetch_fn):
|
|
53 |
return val
|
54 |
|
55 |
# ----------------------------------------------------------
|
56 |
-
# Section 2: Standalone Tool Functions (
|
57 |
# ----------------------------------------------------------
|
58 |
-
|
59 |
@tool
|
60 |
def python_repl(code: str) -> str:
|
61 |
"""Executes a string of Python code and returns the stdout/stderr."""
|
@@ -66,8 +63,6 @@ def python_repl(code: str) -> str:
|
|
66 |
else: return f"Execution failed.\nSTDOUT:\n```\n{result.stdout}\n```\nSTDERR:\n```\n{result.stderr}\n```"
|
67 |
except subprocess.TimeoutExpired: return "Execution timed out (>10s)."
|
68 |
|
69 |
-
# These functions now accept their dependencies (like an llm instance or a cache function) as arguments.
|
70 |
-
@tool
|
71 |
def describe_image_func(image_source: str, vision_llm_instance) -> str:
|
72 |
"""Describes an image from a local file path or a URL using a provided vision LLM."""
|
73 |
try:
|
@@ -79,19 +74,19 @@ def describe_image_func(image_source: str, vision_llm_instance) -> str:
|
|
79 |
msg = HumanMessage(content=[{"type": "text", "text": "Describe this image in detail."}, {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_string}"}}])
|
80 |
return vision_llm_instance.invoke([msg]).content
|
81 |
except Exception as e: return f"Error processing image: {e}"
|
82 |
-
|
83 |
def web_search_func(query: str, cache_func) -> str:
|
84 |
"""Performs a web search using Tavily and returns a compilation of results."""
|
85 |
key = f"web:{query}"
|
86 |
results = cache_func(key, lambda: TavilySearchResults(max_results=5).invoke(query))
|
87 |
return "\n\n---\n\n".join([f"Source: {res['url']}\nContent: {res['content']}" for res in results])
|
88 |
-
|
89 |
def wiki_search_func(query: str, cache_func) -> str:
|
90 |
"""Searches Wikipedia and returns the top 2 results."""
|
91 |
key = f"wiki:{query}"
|
92 |
docs = cache_func(key, lambda: WikipediaLoader(query=query, load_max_docs=2, doc_content_chars_max=2000).load())
|
93 |
return "\n\n---\n\n".join([f"Source: {d.metadata['source']}\n\n{d.page_content}" for d in docs])
|
94 |
-
|
95 |
def arxiv_search_func(query: str, cache_func) -> str:
|
96 |
"""Searches Arxiv for scientific papers and returns the top 2 results."""
|
97 |
key = f"arxiv:{query}"
|
@@ -99,46 +94,41 @@ def arxiv_search_func(query: str, cache_func) -> str:
|
|
99 |
return "\n\n---\n\n".join([f"Source: {d.metadata['source']}\nPublished: {d.metadata['Published']}\nTitle: {d.metadata['Title']}\n\nSummary:\n{d.page_content}" for d in docs])
|
100 |
|
101 |
# ----------------------------------------------------------
|
102 |
-
# Section 3:
|
103 |
# ----------------------------------------------------------
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
**
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
**Crucial Instructions:**
|
118 |
-
- If your tools **cannot possibly answer the question** (e.g., it requires watching a video or listening to audio), you MUST respond by stating the limitation.
|
119 |
-
- In case of a limitation, your response should be:
|
120 |
-
`FINAL ANSWER: I am unable to answer this question because it requires a capability I do not possess, such as [describe the missing capability].`
|
121 |
"""
|
122 |
)
|
123 |
|
124 |
# ----------------------------------------------------------
|
125 |
-
# Section 4: Factory Function for Agent Executor
|
126 |
# ----------------------------------------------------------
|
127 |
def create_agent_executor(provider: str = "groq"):
|
128 |
"""
|
129 |
Factory function to create and compile the LangGraph agent executor.
|
130 |
-
This version
|
131 |
"""
|
132 |
print(f"Initializing agent with provider: {provider}")
|
133 |
|
134 |
-
# Step 1: Build LLMs
|
135 |
if provider == "google": main_llm = ChatGoogleGenerativeAI(model="gemini-1.5-pro-latest", temperature=0)
|
136 |
elif provider == "groq": main_llm = ChatGroq(model_name="meta-llama/llama-4-maverick-17b-128e-instruct", temperature=0)
|
137 |
elif provider == "huggingface": main_llm = ChatHuggingFace(llm=HuggingFaceEndpoint(repo_id="mistralai/Mixtral-8x7B-Instruct-v0.1", temperature=0.1))
|
138 |
else: raise ValueError("Invalid provider selected")
|
139 |
vision_llm = ChatGroq(model_name="meta-llama/llama-4-maverick-17b-128e-instruct", temperature=0)
|
140 |
|
141 |
-
# Step 2: Build Retriever
|
142 |
embeddings = HuggingFaceEmbeddings(model_name=EMBED_MODEL)
|
143 |
if FAISS_CACHE.exists():
|
144 |
with open(FAISS_CACHE, "rb") as f: vector_store = pickle.load(f)
|
@@ -148,9 +138,7 @@ def create_agent_executor(provider: str = "groq"):
|
|
148 |
with open(FAISS_CACHE, "wb") as f: pickle.dump(vector_store, f)
|
149 |
retriever = vector_store.as_retriever(search_kwargs={"k": RETRIEVER_K})
|
150 |
|
151 |
-
# Step 3: Create the final list of tools
|
152 |
-
# We use functools.partial to "bake in" the dependencies (like the LLM or cache) into our standalone functions.
|
153 |
-
# This creates new functions with a simpler signature that the agent can easily call.
|
154 |
tools_list = [
|
155 |
python_repl,
|
156 |
Tool(name="describe_image", func=functools.partial(describe_image_func, vision_llm_instance=vision_llm), description="Describes an image from a local file path or a URL."),
|
@@ -160,13 +148,22 @@ def create_agent_executor(provider: str = "groq"):
|
|
160 |
create_retriever_tool(retriever=retriever, name="retrieve_examples", description="Retrieve solved questions similar to the user's query."),
|
161 |
]
|
162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
llm_with_tools = main_llm.bind_tools(tools_list)
|
164 |
|
165 |
-
# Step
|
166 |
def retriever_node(state: MessagesState):
|
167 |
user_query = state["messages"][-1].content
|
168 |
docs = retriever.invoke(user_query)
|
169 |
-
|
|
|
170 |
if docs:
|
171 |
example_text = "\n\n---\n\n".join(d.page_content for d in docs)
|
172 |
messages.append(AIMessage(content=f"I have found {len(docs)} similar solved examples:\n\n{example_text}", name="ExampleRetriever"))
|
@@ -177,7 +174,7 @@ def create_agent_executor(provider: str = "groq"):
|
|
177 |
result = llm_with_tools.invoke(state["messages"])
|
178 |
return {"messages": [result]}
|
179 |
|
180 |
-
# Step
|
181 |
builder = StateGraph(MessagesState)
|
182 |
builder.add_node("retriever", retriever_node)
|
183 |
builder.add_node("assistant", assistant_node)
|
@@ -192,35 +189,5 @@ def create_agent_executor(provider: str = "groq"):
|
|
192 |
print("Agent Executor created successfully.")
|
193 |
return agent_executor
|
194 |
|
195 |
-
#
|
196 |
-
#
|
197 |
-
# ----------------------------------------------------------
|
198 |
-
def test_llm_connection(provider: str = "google"):
|
199 |
-
"""Performs a quick test to see if the LLM provider is accessible."""
|
200 |
-
print(f"--- Performing pre-flight check for LLM provider: {provider} ---")
|
201 |
-
try:
|
202 |
-
if provider == "google": llm, name = ChatGoogleGenerativeAI(model="gemini-1.5-pro-latest"), "Google Gemini"
|
203 |
-
elif provider == "groq": llm, name = ChatGroq(model_name="llama3-70b-8192"), "Groq"
|
204 |
-
elif provider == "huggingface": llm, name = ChatHuggingFace(llm=HuggingFaceEndpoint(repo_id="mistralai/Mixtral-8x7B-Instruct-v0.1")), "Hugging Face"
|
205 |
-
else: return "❌ **LLM Status:** Invalid provider configured."
|
206 |
-
llm.invoke("hello")
|
207 |
-
success_message = f"✅ **LLM Status:** Connection to {name} is successful."
|
208 |
-
print(success_message)
|
209 |
-
return success_message
|
210 |
-
except Exception as e:
|
211 |
-
error_message = f"❌ **LLM Status:** FAILED to connect. Check API keys/credits. Details: {e}"
|
212 |
-
print(error_message)
|
213 |
-
return error_message
|
214 |
-
|
215 |
-
if __name__ == "__main__":
|
216 |
-
"""Allows for direct testing of the agent's logic."""
|
217 |
-
print("--- Running Agent in Test Mode ---")
|
218 |
-
agent = create_agent_executor(provider="google")
|
219 |
-
question = "According to wikipedia, what is the main difference between a lama and an alpaca?"
|
220 |
-
print(f"\nTest Question: {question}\n\n--- Agent Thinking... ---\n")
|
221 |
-
|
222 |
-
for chunk in agent.stream({"messages": [("user", question)]}):
|
223 |
-
for key, value in chunk.items():
|
224 |
-
if value['messages']:
|
225 |
-
message = value['messages'][-1]
|
226 |
-
if message.content: print(f"--- Node: {key} ---\n{message.content}\n")
|
|
|
1 |
+
"""
|
2 |
+
agent.py
|
3 |
+
|
4 |
+
This file defines the core logic for a sophisticated AI agent using LangGraph.
|
5 |
+
This version uses a dynamic system prompt to explicitly list the available tools
|
6 |
+
for the LLM on every run, designed to combat "tool refusal".
|
7 |
+
"""
|
8 |
+
|
9 |
# ----------------------------------------------------------
|
10 |
+
# Section 0: Imports and Configuration (Identical to before)
|
11 |
# ----------------------------------------------------------
|
12 |
import json
|
13 |
import os
|
|
|
16 |
import subprocess
|
17 |
import textwrap
|
18 |
import base64
|
19 |
+
import functools
|
20 |
from io import BytesIO
|
21 |
from pathlib import Path
|
22 |
|
|
|
23 |
import requests
|
24 |
from cachetools import TTLCache
|
25 |
from PIL import Image
|
26 |
|
|
|
27 |
from langchain.schema import Document
|
28 |
from langchain.tools.retriever import create_retriever_tool
|
29 |
from langchain_community.vectorstores import FAISS
|
30 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
31 |
from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
|
32 |
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
|
33 |
+
from langchain_core.tools import Tool, tool
|
34 |
from langchain_google_genai import ChatGoogleGenerativeAI
|
35 |
from langchain_groq import ChatGroq
|
36 |
from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpoint, ChatHuggingFace
|
37 |
from langgraph.graph import START, StateGraph, MessagesState
|
38 |
from langgraph.prebuilt import ToolNode, tools_condition
|
39 |
|
|
|
40 |
from dotenv import load_dotenv
|
41 |
load_dotenv()
|
42 |
|
43 |
+
# --- Configuration and Caching (Identical) ---
|
44 |
+
JSONL_PATH, FAISS_CACHE, EMBED_MODEL = Path("metadata.jsonl"), Path("faiss_index.pkl"), "sentence-transformers/all-mpnet-base-v2"
|
45 |
+
RETRIEVER_K, CACHE_TTL = 5, 600
|
|
|
|
|
|
|
|
|
|
|
46 |
API_CACHE = TTLCache(maxsize=256, ttl=CACHE_TTL)
|
|
|
|
|
47 |
def cached_get(key: str, fetch_fn):
|
48 |
if key in API_CACHE: return API_CACHE[key]
|
49 |
val = fetch_fn()
|
|
|
51 |
return val
|
52 |
|
53 |
# ----------------------------------------------------------
|
54 |
+
# Section 2: Standalone Tool Functions (Identical to before)
|
55 |
# ----------------------------------------------------------
|
|
|
56 |
@tool
|
57 |
def python_repl(code: str) -> str:
|
58 |
"""Executes a string of Python code and returns the stdout/stderr."""
|
|
|
63 |
else: return f"Execution failed.\nSTDOUT:\n```\n{result.stdout}\n```\nSTDERR:\n```\n{result.stderr}\n```"
|
64 |
except subprocess.TimeoutExpired: return "Execution timed out (>10s)."
|
65 |
|
|
|
|
|
66 |
def describe_image_func(image_source: str, vision_llm_instance) -> str:
|
67 |
"""Describes an image from a local file path or a URL using a provided vision LLM."""
|
68 |
try:
|
|
|
74 |
msg = HumanMessage(content=[{"type": "text", "text": "Describe this image in detail."}, {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_string}"}}])
|
75 |
return vision_llm_instance.invoke([msg]).content
|
76 |
except Exception as e: return f"Error processing image: {e}"
|
77 |
+
|
78 |
def web_search_func(query: str, cache_func) -> str:
|
79 |
"""Performs a web search using Tavily and returns a compilation of results."""
|
80 |
key = f"web:{query}"
|
81 |
results = cache_func(key, lambda: TavilySearchResults(max_results=5).invoke(query))
|
82 |
return "\n\n---\n\n".join([f"Source: {res['url']}\nContent: {res['content']}" for res in results])
|
83 |
+
|
84 |
def wiki_search_func(query: str, cache_func) -> str:
|
85 |
"""Searches Wikipedia and returns the top 2 results."""
|
86 |
key = f"wiki:{query}"
|
87 |
docs = cache_func(key, lambda: WikipediaLoader(query=query, load_max_docs=2, doc_content_chars_max=2000).load())
|
88 |
return "\n\n---\n\n".join([f"Source: {d.metadata['source']}\n\n{d.page_content}" for d in docs])
|
89 |
+
|
90 |
def arxiv_search_func(query: str, cache_func) -> str:
|
91 |
"""Searches Arxiv for scientific papers and returns the top 2 results."""
|
92 |
key = f"arxiv:{query}"
|
|
|
94 |
return "\n\n---\n\n".join([f"Source: {d.metadata['source']}\nPublished: {d.metadata['Published']}\nTitle: {d.metadata['Title']}\n\nSummary:\n{d.page_content}" for d in docs])
|
95 |
|
96 |
# ----------------------------------------------------------
|
97 |
+
# Section 3: NEW DYNAMIC SYSTEM PROMPT
|
98 |
# ----------------------------------------------------------
|
99 |
+
# This is now a template string. The {tools} section will be filled in dynamically.
|
100 |
+
SYSTEM_PROMPT_TEMPLATE = (
|
101 |
+
"""You are an expert-level research assistant. Your goal is to answer the user's question accurately.
|
102 |
+
|
103 |
+
**CRITICAL INSTRUCTIONS:**
|
104 |
+
1. **USE YOUR TOOLS:** You have been given a set of tools to find information. You MUST use them when the answer is not immediately known to you. Do not make up answers. Do not apologize or refuse to use a tool. You must try.
|
105 |
+
2. **AVAILABLE TOOLS:** Here is the exact list of tools you have access to:
|
106 |
+
{tools}
|
107 |
+
3. **REASONING:** Think step-by-step. First, analyze the user's question. Second, decide which tool is appropriate. Third, call the tool with the correct parameters. Finally, analyze the tool's output to formulate your answer.
|
108 |
+
4. **LIMITATIONS:** If a question requires a capability you absolutely do not have (e.g., watching a video, listening to audio), you must state that limitation clearly.
|
109 |
+
5. **FINAL ANSWER FORMAT:** Your final response MUST strictly follow this format and nothing else:
|
110 |
+
`FINAL ANSWER: [Your concise and accurate answer here]`
|
|
|
|
|
|
|
|
|
|
|
111 |
"""
|
112 |
)
|
113 |
|
114 |
# ----------------------------------------------------------
|
115 |
+
# Section 4: Factory Function for Agent Executor (MODIFIED)
|
116 |
# ----------------------------------------------------------
|
117 |
def create_agent_executor(provider: str = "groq"):
|
118 |
"""
|
119 |
Factory function to create and compile the LangGraph agent executor.
|
120 |
+
This version dynamically builds the system prompt with the list of tools.
|
121 |
"""
|
122 |
print(f"Initializing agent with provider: {provider}")
|
123 |
|
124 |
+
# Step 1: Build LLMs (Identical)
|
125 |
if provider == "google": main_llm = ChatGoogleGenerativeAI(model="gemini-1.5-pro-latest", temperature=0)
|
126 |
elif provider == "groq": main_llm = ChatGroq(model_name="meta-llama/llama-4-maverick-17b-128e-instruct", temperature=0)
|
127 |
elif provider == "huggingface": main_llm = ChatHuggingFace(llm=HuggingFaceEndpoint(repo_id="mistralai/Mixtral-8x7B-Instruct-v0.1", temperature=0.1))
|
128 |
else: raise ValueError("Invalid provider selected")
|
129 |
vision_llm = ChatGroq(model_name="meta-llama/llama-4-maverick-17b-128e-instruct", temperature=0)
|
130 |
|
131 |
+
# Step 2: Build Retriever (Identical)
|
132 |
embeddings = HuggingFaceEmbeddings(model_name=EMBED_MODEL)
|
133 |
if FAISS_CACHE.exists():
|
134 |
with open(FAISS_CACHE, "rb") as f: vector_store = pickle.load(f)
|
|
|
138 |
with open(FAISS_CACHE, "wb") as f: pickle.dump(vector_store, f)
|
139 |
retriever = vector_store.as_retriever(search_kwargs={"k": RETRIEVER_K})
|
140 |
|
141 |
+
# Step 3: Create the final list of tools (Identical)
|
|
|
|
|
142 |
tools_list = [
|
143 |
python_repl,
|
144 |
Tool(name="describe_image", func=functools.partial(describe_image_func, vision_llm_instance=vision_llm), description="Describes an image from a local file path or a URL."),
|
|
|
148 |
create_retriever_tool(retriever=retriever, name="retrieve_examples", description="Retrieve solved questions similar to the user's query."),
|
149 |
]
|
150 |
|
151 |
+
# --- THIS PART IS NEW ---
|
152 |
+
# 4a. Format the tool list into a string for the prompt
|
153 |
+
tool_definitions = "\n".join([f"- `{tool.name}`: {tool.description}" for tool in tools_list])
|
154 |
+
|
155 |
+
# 4b. Create the final, dynamic system prompt
|
156 |
+
final_system_prompt = SYSTEM_PROMPT_TEMPLATE.format(tools=tool_definitions)
|
157 |
+
# --- END NEW PART ---
|
158 |
+
|
159 |
llm_with_tools = main_llm.bind_tools(tools_list)
|
160 |
|
161 |
+
# Step 5: Define Graph Nodes (Modified to use the new prompt)
|
162 |
def retriever_node(state: MessagesState):
|
163 |
user_query = state["messages"][-1].content
|
164 |
docs = retriever.invoke(user_query)
|
165 |
+
# Use the new, dynamic prompt here
|
166 |
+
messages = [SystemMessage(content=final_system_prompt)]
|
167 |
if docs:
|
168 |
example_text = "\n\n---\n\n".join(d.page_content for d in docs)
|
169 |
messages.append(AIMessage(content=f"I have found {len(docs)} similar solved examples:\n\n{example_text}", name="ExampleRetriever"))
|
|
|
174 |
result = llm_with_tools.invoke(state["messages"])
|
175 |
return {"messages": [result]}
|
176 |
|
177 |
+
# Step 6: Build Graph (Identical)
|
178 |
builder = StateGraph(MessagesState)
|
179 |
builder.add_node("retriever", retriever_node)
|
180 |
builder.add_node("assistant", assistant_node)
|
|
|
189 |
print("Agent Executor created successfully.")
|
190 |
return agent_executor
|
191 |
|
192 |
+
# --- Section 5 (Testing functions) remains the same ---
|
193 |
+
# ... (test_llm_connection and __main__ block)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|