Add DeepAgent implementation
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
DeepAgent that searches the web and creates virtual files.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
import os
|
||||
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
|
||||
|
||||
# Configuration
|
||||
BASE_DIR = Path("/tmp/deepagent")
|
||||
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())
|
||||
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}")
|
||||
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))
|
||||
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)
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
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.export()
|
||||
print("Exported files to", OUTPUT_DIR)
|
||||
Reference in New Issue
Block a user