feat: solution for '8. Самописный поисковый агент на основе deep agents from scratch'
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
.env
|
||||
dist/
|
||||
build/
|
||||
*.log
|
||||
@@ -0,0 +1,31 @@
|
||||
# 8. Самописный поисковый агент на основе deep agents from scratch
|
||||
|
||||
Главная
|
||||
Мои задания
|
||||
8. Самописный поисковый агент на основе deep agents from scratch
|
||||
5Д
|
||||
EN
|
||||
8. Самописный поисковый агент на основе deep agents from scratch
|
||||
Зачёт
|
||||
Версия 1
|
||||
Дедлайн сдачи: 31.08.2026
|
||||
|
||||
В работе
|
||||
|
||||
Редактирование ответа
|
||||
|
||||
Заполните ответ и отправьте работу на проверку преподавателю.
|
||||
|
||||
Тип ответа
|
||||
Текст
|
||||
Ссылка
|
||||
Файлы
|
||||
Текст ответа
|
||||
Прикреплённые файлы
|
||||
Загрузить файл
|
||||
Отправить на проверку
|
||||
Отменить
|
||||
|
||||
Задание
|
||||
|
||||
Необходимо написать deepagent на основе курса deep agents from scratch пример такого аг
|
||||
@@ -0,0 +1,3 @@
|
||||
langchain
|
||||
openai
|
||||
duckduckgo-search
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure the virtual_files package is importable
|
||||
sys.path.append(str(Path(__file__).resolve().parent))
|
||||
|
||||
from langchain import OpenAI
|
||||
from langchain.agents import initialize_agent
|
||||
from langchain.tools import DuckDuckGoSearchRun, Tool
|
||||
from src.virtual_files import VirtualFileSystem
|
||||
|
||||
def main():
|
||||
# Initialize the virtual file system
|
||||
vfs = VirtualFileSystem()
|
||||
|
||||
# Define a custom tool to write to the virtual file system
|
||||
def write_file_tool(input_str: str) -> str:
|
||||
"""
|
||||
Expected input format: filename|content
|
||||
Example: python_history.txt|Python was created by Guido van Rossum...
|
||||
"""
|
||||
if "|" not in input_str:
|
||||
return "Error: Input must be in the format 'filename|content'."
|
||||
filename, content = input_str.split("|", 1)
|
||||
filename = filename.strip()
|
||||
content = content.strip()
|
||||
if not filename:
|
||||
return "Error: Filename cannot be empty."
|
||||
vfs.write_file(filename, content)
|
||||
return f"File '{filename}' written successfully."
|
||||
|
||||
write_tool = Tool(
|
||||
name="WriteFile",
|
||||
func=write_file_tool,
|
||||
description=(
|
||||
"Writes content to a virtual file. "
|
||||
"Use the format: filename|content. "
|
||||
"The file will be stored in the virtual file system and exported at the end."
|
||||
),
|
||||
)
|
||||
|
||||
# Search tool
|
||||
search_tool = DuckDuckGoSearchRun()
|
||||
|
||||
# LLM configuration
|
||||
llm = OpenAI(temperature=0)
|
||||
|
||||
# Initialize the agent with the tools
|
||||
agent_executor = initialize_agent(
|
||||
tools=[search_tool, write_tool],
|
||||
llm=llm,
|
||||
agent="zero-shot-react-description",
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
# Example task: gather information about Python programming language
|
||||
task = """
|
||||
You are a research assistant. Your task is to gather information about the Python programming language, including its history, key features, and popular libraries.
|
||||
Create a virtual file named 'python_history.txt' containing the history, a file named 'python_features.txt' containing key features, and a file named 'python_libraries.txt' containing a list of popular libraries.
|
||||
Use the web search tool to find reliable information. After gathering the data, write each section to the corresponding virtual file using the WriteFile tool.
|
||||
Finally, return a summary of what you have done.
|
||||
"""
|
||||
|
||||
# Run the agent
|
||||
result = agent_executor.run(task)
|
||||
print("\nAgent finished. Result:")
|
||||
print(result)
|
||||
|
||||
# Export virtual files to disk
|
||||
output_dir = Path(__file__).resolve().parent / "output_files"
|
||||
vfs.export_to_disk(str(output_dir))
|
||||
print(f"\nVirtual files exported to {output_dir}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,40 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
class VirtualFileSystem:
|
||||
"""
|
||||
A simple in-memory virtual file system that stores files as a dictionary.
|
||||
Provides methods to write, read, list, and export files to the real filesystem.
|
||||
"""
|
||||
def __init__(self):
|
||||
self.files = {} # dict of filename -> content
|
||||
|
||||
def write_file(self, name: str, content: str):
|
||||
"""
|
||||
Write content to a virtual file. Overwrites if the file already exists.
|
||||
"""
|
||||
self.files[name] = content
|
||||
|
||||
def read_file(self, name: str) -> str:
|
||||
"""
|
||||
Read content from a virtual file. Returns empty string if file does not exist.
|
||||
"""
|
||||
return self.files.get(name, "")
|
||||
|
||||
def list_files(self):
|
||||
"""
|
||||
Return a list of all virtual file names.
|
||||
"""
|
||||
return list(self.files.keys())
|
||||
|
||||
def export_to_disk(self, base_path: str):
|
||||
"""
|
||||
Export all virtual files to the real filesystem under the given base_path.
|
||||
Creates directories as needed.
|
||||
"""
|
||||
os.makedirs(base_path, exist_ok=True)
|
||||
for name, content in self.files.items():
|
||||
file_path = os.path.join(base_path, name)
|
||||
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
Reference in New Issue
Block a user