add main.py

This commit is contained in:
2026-05-26 12:03:21 +00:00
parent b32806464c
commit d44ecc349f
+35 -17
View File
@@ -1,12 +1,11 @@
import os import os, asyncio
import asyncio
from langchain_openai import ChatOpenAI from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage from langchain_core.messages import HumanMessage
from langchain.tools import tool from langchain.tools import tool
from deepagents import create_deep_agent from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend, CompositeBackend from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
# LLM configuration using OpenRouter # LLM configuration
llm = ChatOpenAI( llm = ChatOpenAI(
model="openai/gpt-oss-20b:free", model="openai/gpt-oss-20b:free",
base_url="https://openrouter.ai/api/v1", base_url="https://openrouter.ai/api/v1",
@@ -14,14 +13,16 @@ llm = ChatOpenAI(
temperature=0.0, temperature=0.0,
) )
# Backend: real filesystem in current directory # Backend: virtual FS + real shell
backend = CompositeBackend([ backend = CompositeBackend([
LocalShellBackend(workspace_dir="./workspace"),
FilesystemBackend(), FilesystemBackend(),
]) ])
# Tool: web search using duckduckgo-search
@tool @tool
async def web_search(query: str) -> str: def web_search(query: str) -> str:
"""Search the web for information using DuckDuckGo.""" """Search the web for information."""
try: try:
from duckduckgo_search import DDGS from duckduckgo_search import DDGS
with DDGS() as ddgs: with DDGS() as ddgs:
@@ -30,27 +31,44 @@ async def web_search(query: str) -> str:
except Exception as e: except Exception as e:
return f"Search error: {e}" return f"Search error: {e}"
# Tool: create virtual file in the virtual FS
@tool @tool
def write_file(path: str, content: str) -> str: def create_virtual_file(path: str, content: str) -> str:
"""Write a file to the local filesystem.""" """Create a file in the virtual filesystem."""
try: try:
with open(path, 'w', encoding='utf-8') as f: backend.write_file(path, content)
f.write(content) return f"Virtual file {path} created."
return f"File written to {path}"
except Exception as e: except Exception as e:
return f"Error writing file: {e}" return f"Error creating virtual file: {e}"
# Tool: write virtual files to real filesystem
@tool
def write_to_real_fs() -> str:
"""Copy all files from virtual FS to the real workspace."""
try:
for root, dirs, files in os.walk("./workspace"):
for file in files:
src = os.path.join(root, file)
dst = os.path.join("./real_files", file)
os.makedirs(os.path.dirname(dst), exist_ok=True)
with open(src, "r", encoding="utf-8") as fsrc, open(dst, "w", encoding="utf-8") as fdst:
fdst.write(fsrc.read())
return "All virtual files written to real filesystem."
except Exception as e:
return f"Error writing to real FS: {e}"
# Create the deep agent
agent = create_deep_agent( agent = create_deep_agent(
llm=llm, llm=llm,
tools=[web_search, write_file], tools=[web_search, create_virtual_file, write_to_real_fs],
backend=backend, backend=backend,
system_prompt="You are a helpful research assistant. Your task is to search the web for information on a given topic and then create virtual files with the results. At the end of the conversation, ensure all generated files are written to disk.", system_prompt="You are a deep agent that can search the web, create virtual files, and finally write them to the real filesystem.",
) )
async def main(): async def main():
# Example interaction: ask about Python best practices # Example interaction: search, create file, write to real FS
result = await agent.ainvoke( result = await agent.ainvoke(
{"messages": [HumanMessage(content="Search for Python best practices and save to results.txt")]}, {"messages": [HumanMessage(content="Search for Python async programming examples and store results in a file called async_examples.txt")]},
{"configurable": {"thread_id": "session-1"}}, {"configurable": {"thread_id": "session-1"}},
) )
print(result["messages"][-1].content) print(result["messages"][-1].content)