add main.py
This commit is contained in:
@@ -1,64 +1,53 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Deep agent that searches the web using Perplexity and writes results to a file.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
python main.py "search query"
|
|
||||||
|
|
||||||
The agent will:
|
|
||||||
1. Query Perplexity via LangChain's Perplexity wrapper.
|
|
||||||
2. Store the answer in a virtual file `output.txt`.
|
|
||||||
3. Write the virtual file to the real filesystem.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
import asyncio
|
||||||
|
from langchain_openai import ChatOpenAI
|
||||||
|
from langchain_core.messages import HumanMessage
|
||||||
|
from langchain.tools import tool
|
||||||
|
from deepagents import create_deep_agent
|
||||||
|
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
|
||||||
|
|
||||||
from langchain_community.utilities import Perplexity
|
# LLM setup
|
||||||
from langchain_core.prompts import ChatPromptTemplate
|
llm = ChatOpenAI(
|
||||||
from langchain_core.output_parsers import StrOutputParser
|
model="openai/gpt-oss-20b:free",
|
||||||
|
base_url="https://openrouter.ai/api/v1",
|
||||||
|
api_key=os.getenv("OPENAI_API_KEY"),
|
||||||
|
temperature=0.0,
|
||||||
|
)
|
||||||
|
|
||||||
# Configure Perplexity API key via environment variable
|
# Backend: virtual FS + real shell
|
||||||
# Users should set PERPLEXITY_API_KEY in their environment
|
backend = CompositeBackend([
|
||||||
|
LocalShellBackend(workspace_dir="./workspace"),
|
||||||
PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY")
|
FilesystemBackend(),
|
||||||
if not PERPLEXITY_API_KEY:
|
|
||||||
raise RuntimeError("PERPLEXITY_API_KEY environment variable not set")
|
|
||||||
|
|
||||||
# Create a simple chain: prompt -> Perplexity -> output parser
|
|
||||||
prompt = ChatPromptTemplate.from_messages([
|
|
||||||
("system", "You are a helpful assistant that answers questions based on web search."),
|
|
||||||
("human", "{question}")
|
|
||||||
])
|
])
|
||||||
|
|
||||||
llm = Perplexity(api_key=PERPLEXITY_API_KEY, temperature=0.7)
|
# Web search tool using duckduckgo-search
|
||||||
chain = prompt | llm | StrOutputParser()
|
@tool
|
||||||
|
def web_search(query: str) -> str:
|
||||||
|
"""Search the web for information."""
|
||||||
|
try:
|
||||||
|
from duckduckgo_search import DDGS
|
||||||
|
with DDGS() as ddgs:
|
||||||
|
results = list(ddgs.text(query, max_results=5))
|
||||||
|
return "\n".join(f"{r['title']}: {r['body']}" for r in results)
|
||||||
|
except Exception as e:
|
||||||
|
return f"Search error: {e}"
|
||||||
|
|
||||||
|
# Create deep agent
|
||||||
|
agent = create_deep_agent(
|
||||||
|
llm=llm,
|
||||||
|
tools=[web_search],
|
||||||
|
backend=backend,
|
||||||
|
system_prompt="You are a helpful research agent.",
|
||||||
|
)
|
||||||
|
|
||||||
def search_and_write(query: str, output_path: Path) -> None:
|
async def main():
|
||||||
"""Search the web for *query* and write the answer to *output_path*.
|
# Example query
|
||||||
|
query = "Python async programming"
|
||||||
The function creates a virtual file in memory and then writes it to disk.
|
result = await agent.ainvoke(
|
||||||
"""
|
{"messages": [HumanMessage(content=f"Search for {query}")]},
|
||||||
print(f"Searching for: {query}")
|
{"configurable": {"thread_id": "session-1"}},
|
||||||
answer = chain.invoke({"question": query})
|
)
|
||||||
# Virtual file content
|
print(result["messages"][-1].content)
|
||||||
virtual_file_content = f"Query: {query}\n\nAnswer:\n{answer}\n"
|
|
||||||
# Write to real filesystem
|
|
||||||
output_path.write_text(virtual_file_content, encoding="utf-8")
|
|
||||||
print(f"Result written to {output_path.resolve()}")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = argparse.ArgumentParser(description="Deep agent search tool")
|
asyncio.run(main())
|
||||||
parser.add_argument("query", type=str, help="Search query")
|
|
||||||
parser.add_argument(
|
|
||||||
"--output",
|
|
||||||
type=str,
|
|
||||||
default="output.txt",
|
|
||||||
help="Path to write the result file (default: output.txt)",
|
|
||||||
)
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
output_path = Path(args.output)
|
|
||||||
search_and_write(args.query, output_path)
|
|
||||||
|
|||||||
Reference in New Issue
Block a user