Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_openai import ChatOpenAI
|
| 2 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
| 3 |
+
|
| 4 |
+
class BasicAgent:
|
| 5 |
+
def __init__(self):
|
| 6 |
+
print("SmartAgent initialized.")
|
| 7 |
+
self.llm = ChatOpenAI(model="gpt-4", temperature=0)
|
| 8 |
+
self.search_tool = DuckDuckGoSearchRun()
|
| 9 |
+
|
| 10 |
+
def __call__(self, question: str) -> str:
|
| 11 |
+
print(f"Agent received question: {question[:50]}...")
|
| 12 |
+
|
| 13 |
+
# Step 1: Ask LLM if it can confidently answer or needs to search
|
| 14 |
+
prompt = f"""
|
| 15 |
+
You are a helpful assistant. Given the question below, decide if you know the answer with high confidence.
|
| 16 |
+
If yes, answer concisely.
|
| 17 |
+
If you need more information, respond with SEARCH: followed by the search query.
|
| 18 |
+
Question: {question}
|
| 19 |
+
Answer or SEARCH:
|
| 20 |
+
"""
|
| 21 |
+
response = self.llm.invoke(prompt).content.strip()
|
| 22 |
+
|
| 23 |
+
if response.upper().startswith("SEARCH:"):
|
| 24 |
+
# Extract search query
|
| 25 |
+
query = response[len("SEARCH:"):].strip()
|
| 26 |
+
print(f"Performing search with query: {query}")
|
| 27 |
+
|
| 28 |
+
# Use DuckDuckGo search to get info
|
| 29 |
+
search_result = self.search_tool.run(query)
|
| 30 |
+
|
| 31 |
+
# Step 2: Now use LLM again with search results to answer
|
| 32 |
+
prompt2 = f"""
|
| 33 |
+
You are a helpful assistant. Use the following search results to answer the question concisely.
|
| 34 |
+
Question: {question}
|
| 35 |
+
Search Results: {search_result}
|
| 36 |
+
Answer:
|
| 37 |
+
"""
|
| 38 |
+
final_answer = self.llm.invoke(prompt2).content.strip()
|
| 39 |
+
print(f"Agent final answer: {final_answer}")
|
| 40 |
+
return final_answer
|
| 41 |
+
|
| 42 |
+
else:
|
| 43 |
+
# LLM confident answer directly
|
| 44 |
+
print(f"Agent direct answer: {response}")
|
| 45 |
+
return response
|