Update DeepAgent with deepagents

This commit is contained in:
2026-05-28 13:20:00 +00:00
parent c16e76fb93
commit 2c2d72bc24
+17 -32
View File
@@ -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. The agent searches the web via Perplexity API and writes results to virtual files,
It writes results into a temporary directory and finally copies them then exports them to real filesystem.
to the real filesystem when finished.
""" """
import os import os
@@ -11,9 +10,8 @@ import shutil
from pathlib import Path from pathlib import Path
from typing import List, Dict from typing import List, Dict
from langchain_community.utilities.perplexity import PerplexityAPIWrapper from deepagents import AgentBuilder, Tool, LLMWrapper
from langchain_core.prompts import PromptTemplate from deepagents.tools.perplexity import PerplexityTool
from langchain.chains import LLMChain
# Configuration # Configuration
BASE_DIR = Path("/tmp/deepagent") BASE_DIR = Path("/tmp/deepagent")
@@ -22,39 +20,27 @@ OUTPUT_DIR = Path("./output_files")
class DeepAgent: class DeepAgent:
def __init__(self, api_key: str): def __init__(self, api_key: str):
self.api_key = api_key self.api_key = api_key
self.llm = PerplexityAPIWrapper(api_key=api_key) # Build agent with Perplexity tool
self.chain = LLMChain(llm=self.llm, prompt=self._build_prompt()) 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) BASE_DIR.mkdir(parents=True, exist_ok=True)
OUTPUT_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): def search_and_save(self, query: str, filename: str):
result = self.chain.run({"query": query}) # Run agent to get result
# Parse JSON safely result = self.agent.run(query)
try:
import json
data = json.loads(result)
except Exception as e:
raise ValueError(f"Failed to parse LLM output: {e}\n{result}")
file_path = BASE_DIR / filename file_path = BASE_DIR / filename
with open(file_path, "w", encoding="utf-8") as f: 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 return file_path
def export(self): def export(self):
"""Copy all virtual files to OUTPUT_DIR."""
for src in BASE_DIR.iterdir(): for src in BASE_DIR.iterdir():
dst = OUTPUT_DIR / src.name shutil.copy(src, OUTPUT_DIR / src.name)
shutil.copy(src, dst)
if __name__ == "__main__": if __name__ == "__main__":
import argparse import argparse
@@ -62,9 +48,8 @@ if __name__ == "__main__":
parser.add_argument("--api-key", required=True) parser.add_argument("--api-key", required=True)
args = parser.parse_args() args = parser.parse_args()
agent = DeepAgent(api_key=args.api_key) agent = DeepAgent(api_key=args.api_key)
# Example queries
queries = ["Python async programming", "LangChain deep agents"] queries = ["Python async programming", "LangChain deep agents"]
for i, q in enumerate(queries, 1): 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() agent.export()
print("Exported files to", OUTPUT_DIR) print("Exported files to", OUTPUT_DIR)