From b217425478f6e9da9d55e2c1e7ca3aba343cdeaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=B8=D1=80=D0=B8=D0=BB=D0=BB=20=D0=9A=D1=83=D1=82?= =?UTF-8?q?=D0=BB=D0=B0=D1=85=D0=BC=D0=B5=D1=82=D0=BE=D0=B2?= Date: Tue, 26 May 2026 13:00:53 +0000 Subject: [PATCH] add main.py --- main.py | 134 +++++++++++++++++++++++--------------------------------- 1 file changed, 54 insertions(+), 80 deletions(-) diff --git a/main.py b/main.py index 1bb8c0a..73af17d 100644 --- a/main.py +++ b/main.py @@ -1,94 +1,68 @@ import os import json +from dotenv import load_dotenv from langchain_openai import ChatOpenAI -from langchain.tools import tool -from duckduckgo_search import DDGS +from agent_core import DeepAgent +from tools import web_search, create_virtual_file, list_virtual_files, export_files -# LLM configuration +# Load environment variables +load_dotenv() + +# LLM initialization llm = ChatOpenAI( model="openai/gpt-oss-20b:free", base_url="https://platform.brojs.ru/jrnl-bh/api/inference/v1", api_key=os.getenv("JOURNAL_MCP_PAT"), - temperature=0.5, + temperature=0.3, ) -# Simple virtual file system -class VirtualFileSystem: - def __init__(self): - self.files = {} - - def write(self, path: str, content: str): - self.files[path] = content - - def list(self): - return list(self.files.keys()) - - def dump_to_real_fs(self, base_dir: str = "."): - for path, content in self.files.items(): - full_path = os.path.join(base_dir, path) - os.makedirs(os.path.dirname(full_path), exist_ok=True) - with open(full_path, "w", encoding="utf-8") as f: - f.write(content) - -# Tool for web search using duckduckgo -@tool -def web_search(query: str) -> str: - """Search the web for a query and return top 3 results as a formatted string.""" - try: - with DDGS() as ddgs: - results = list(ddgs.text(query, max_results=3)) - if not results: - return "No results found." - formatted = [] - for i, r in enumerate(results, 1): - formatted.append(f"{i}. {r['title']}\n{r['body']}\nURL: {r['href']}") - return "\n\n".join(formatted) - except Exception as e: - return f"Search error: {e}" - -# Deep agent implementation -class DeepAgent: - def __init__(self, llm, tools): +# Helper to wrap the LLM callable expected by DeepAgent +class LLMWrapper: + def __init__(self, llm): self.llm = llm - self.tools = {t.__name__: t for t in tools} - self.vfs = VirtualFileSystem() + def __call__(self, messages): + # langchain returns a list of Message objects; convert to dict + # For simplicity, we use the first assistant message content + response = self.llm(messages) + # The wrapper expects a dict with 'content' + return {"content": response["content"]} - def run(self, prompt: str): - # Initial system message - system_msg = "You are a helpful assistant that can search the web and create virtual files." - # Build conversation - messages = [system_msg, prompt] - # Simple loop: ask for tool usage - while True: - # Ask LLM for next action - response = self.llm.invoke(messages) - text = response.content.strip() - if text.lower().startswith("search:"): - query = text[7:].strip() - result = web_search(query) - self.vfs.write(f"search_{query.replace(' ', '_')}.txt", result) - messages.append(f"Search result for '{query}' written to virtual file.") - elif text.lower().startswith("create file:"): - parts = text[12:].strip().split("::", 1) - if len(parts) == 2: - path, content = parts - self.vfs.write(path.strip(), content.strip()) - messages.append(f"File '{path.strip()}' created.") - else: - messages.append("Invalid create file syntax. Use 'create file: path::content'.") - elif text.lower() == "done": - break - else: - messages.append(text) - # Dump virtual files to real filesystem - self.vfs.dump_to_real_fs() - return "Agent finished. Files written to disk." +llm_wrapper = LLMWrapper(llm) + +# Instantiate agent with tools +agent = DeepAgent(llm_wrapper, [web_search, create_virtual_file, list_virtual_files, export_files]) + +# Example tasks +TASKS = [ + { + "description": "Найди информацию о LangGraph и создай файл summary.md", + "query": "LangGraph python framework", + "filename": "summary.md", + }, + { + "description": "Найди топ-5 Python библиотек для работы с LLM и создай файл llm_libs.md", + "query": "top python libraries for llm", + "filename": "llm_libs.md", + }, + { + "description": "Найди что такое ReAct агент и создай файл react_agent.md", + "query": "ReAct agent definition", + "filename": "react_agent.md", + }, +] + +for task in TASKS: + print(f"\n=== {task['description']} ===") + # Step 1: search + search_result = agent.run(task["query"]) + # Step 2: create file with search result + create_msg = agent.run(f"create_virtual_file {task['filename']} | {search_result}") + print(create_msg) + +# Export all virtual files to disk +export_msg = agent.run("export_files output") +print(export_msg) if __name__ == "__main__": - agent = DeepAgent(llm, tools=[web_search]) - # Example usage: search for LangChain and create a file - user_prompt = ( - "Search for 'LangChain deep agent' and create a file named 'summary.txt' with the first search result." - ) - result = agent.run(user_prompt) - print(result) + # The script already executed tasks above; nothing else needed. + pass