Update DeepAgent with deepagents
This commit is contained in:
+17
-32
@@ -1,9 +1,8 @@
|
||||
"""
|
||||
DeepAgent that searches the web and creates virtual files.
|
||||
DeepAgent implementation using deepagents from scratch.
|
||||
|
||||
The agent uses langchain's Perplexity wrapper to query the internet.
|
||||
It writes results into a temporary directory and finally copies them
|
||||
to the real filesystem when finished.
|
||||
The agent searches the web via Perplexity API and writes results to virtual files,
|
||||
then exports them to real filesystem.
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -11,9 +10,8 @@ import shutil
|
||||
from pathlib import Path
|
||||
from typing import List, Dict
|
||||
|
||||
from langchain_community.utilities.perplexity import PerplexityAPIWrapper
|
||||
from langchain_core.prompts import PromptTemplate
|
||||
from langchain.chains import LLMChain
|
||||
from deepagents import AgentBuilder, Tool, LLMWrapper
|
||||
from deepagents.tools.perplexity import PerplexityTool
|
||||
|
||||
# Configuration
|
||||
BASE_DIR = Path("/tmp/deepagent")
|
||||
@@ -22,39 +20,27 @@ OUTPUT_DIR = Path("./output_files")
|
||||
class DeepAgent:
|
||||
def __init__(self, api_key: str):
|
||||
self.api_key = api_key
|
||||
self.llm = PerplexityAPIWrapper(api_key=api_key)
|
||||
self.chain = LLMChain(llm=self.llm, prompt=self._build_prompt())
|
||||
# Build agent with Perplexity tool
|
||||
perplexity_tool = Tool(
|
||||
name="perplexity",
|
||||
description="Search the web using Perplexity API.",
|
||||
func=lambda query: PerplexityTool(api_key=api_key).search(query),
|
||||
)
|
||||
self.agent = AgentBuilder().with_tools([perplexity_tool]).build()
|
||||
BASE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _build_prompt(self) -> PromptTemplate:
|
||||
template = (
|
||||
"You are a web search assistant. Given the query: {query}\n"
|
||||
"Return a JSON object with keys:\n"
|
||||
"- title: short title\n"
|
||||
"- content: full text of the page (max 500 words)\n"
|
||||
"- url: source URL\n"
|
||||
)
|
||||
return PromptTemplate(template=template, input_variables=["query"])
|
||||
|
||||
def search_and_save(self, query: str, filename: str):
|
||||
result = self.chain.run({"query": query})
|
||||
# Parse JSON safely
|
||||
try:
|
||||
import json
|
||||
data = json.loads(result)
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to parse LLM output: {e}\n{result}")
|
||||
# Run agent to get result
|
||||
result = self.agent.run(query)
|
||||
file_path = BASE_DIR / filename
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
f.write(json.dumps(data, ensure_ascii=False, indent=2))
|
||||
f.write(result)
|
||||
return file_path
|
||||
|
||||
def export(self):
|
||||
"""Copy all virtual files to OUTPUT_DIR."""
|
||||
for src in BASE_DIR.iterdir():
|
||||
dst = OUTPUT_DIR / src.name
|
||||
shutil.copy(src, dst)
|
||||
shutil.copy(src, OUTPUT_DIR / src.name)
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
@@ -62,9 +48,8 @@ if __name__ == "__main__":
|
||||
parser.add_argument("--api-key", required=True)
|
||||
args = parser.parse_args()
|
||||
agent = DeepAgent(api_key=args.api_key)
|
||||
# Example queries
|
||||
queries = ["Python async programming", "LangChain deep agents"]
|
||||
for i, q in enumerate(queries, 1):
|
||||
agent.search_and_save(q, f"result_{i}.json")
|
||||
agent.search_and_save(q, f"result_{i}.txt")
|
||||
agent.export()
|
||||
print("Exported files to", OUTPUT_DIR)
|
||||
|
||||
Reference in New Issue
Block a user