update agent.py
This commit is contained in:
@@ -1,11 +1,9 @@
|
||||
import os
|
||||
from typing import Dict, Any
|
||||
import json
|
||||
import requests
|
||||
from langchain.llms.openai import OpenAI
|
||||
from langchain.prompts import PromptTemplate
|
||||
from langchain.chains import LLMChain
|
||||
from typing import Dict, Any
|
||||
|
||||
# Simple web search tool using DuckDuckGo instant answer API
|
||||
# Simple web search using DuckDuckGo instant answer API
|
||||
class WebSearch:
|
||||
def __init__(self):
|
||||
self.base = "https://api.duckduckgo.com/"
|
||||
@@ -20,32 +18,47 @@ class WebSearch:
|
||||
}
|
||||
r = requests.get(self.base, params=params)
|
||||
data = r.json()
|
||||
# Return the abstract text if available
|
||||
return data.get("AbstractText", "") or data.get("RelatedTopics", [])[0].get("Text", "")
|
||||
return data.get("AbstractText") or (data.get("RelatedTopics", [])[0].get("Text") if data.get("RelatedTopics") else "")
|
||||
|
||||
# Agent that searches and writes a virtual file
|
||||
# DeepAgent without external libraries
|
||||
class DeepAgent:
|
||||
def __init__(self, llm: Any):
|
||||
self.llm = llm
|
||||
def __init__(self, api_key: str):
|
||||
self.api_key = api_key
|
||||
self.search = WebSearch()
|
||||
self.virtual_fs: Dict[str, str] = {}
|
||||
|
||||
def _chat(self, messages: list[dict]) -> str:
|
||||
url = "https://api.openai.com/v1/chat/completions"
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
payload = {
|
||||
"model": "gpt-4o-mini",
|
||||
"messages": messages,
|
||||
"temperature": 0.2,
|
||||
}
|
||||
r = requests.post(url, headers=headers, json=payload)
|
||||
r.raise_for_status()
|
||||
return r.json()["choices"][0]["message"]["content"]
|
||||
|
||||
def run(self, task_description: str) -> None:
|
||||
# Step 1: Search the web for relevant info
|
||||
search_query = f"{task_description} example"
|
||||
context = self.search.run(search_query)
|
||||
# 1. Search web for context
|
||||
query = f"{task_description} example"
|
||||
context = self.search.run(query)
|
||||
if not context:
|
||||
context = "No context found."
|
||||
context = "No relevant information found."
|
||||
|
||||
# Step 2: Ask LLM to generate file content based on context
|
||||
prompt = PromptTemplate(
|
||||
input_variables=["context", "task_description"],
|
||||
template="You are a developer. Based on the following context, write a Python file named output.py that demonstrates the concept described in the task: {task_description}\nContext: {context}\nOutput:\n"
|
||||
# 2. Ask LLM to generate file content
|
||||
system_prompt = (
|
||||
"You are a developer assistant. Based on the provided context and task description, produce the content of a Python file named output.py that demonstrates the requested functionality."
|
||||
)
|
||||
chain = LLMChain(llm=self.llm, prompt=prompt)
|
||||
result = chain.run(context=context, task_description=task_description)
|
||||
|
||||
# Step 3: Store in virtual FS
|
||||
user_prompt = f"Task: {task_description}\nContext: {context}\nProvide only the code for output.py."
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
]
|
||||
result = self._chat(messages)
|
||||
self.virtual_fs["output.py"] = result.strip()
|
||||
|
||||
def export_to_real_fs(self, repo_path: str) -> None:
|
||||
@@ -56,11 +69,12 @@ class DeepAgent:
|
||||
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
llm = OpenAI(temperature=0.2, model_name="gpt-4o-mini")
|
||||
agent = DeepAgent(llm)
|
||||
api_key = os.getenv("OPENAI_API_KEY")
|
||||
if not api_key:
|
||||
raise RuntimeError("Please set OPENAI_API_KEY environment variable.")
|
||||
agent = DeepAgent(api_key)
|
||||
task_desc = "Create a simple Python script that prints 'Hello World'"
|
||||
agent.run(task_desc)
|
||||
# Export to repository directory
|
||||
repo_dir = os.path.abspath(".")
|
||||
agent.export_to_real_fs(repo_dir)
|
||||
print("Files written:", list(agent.virtual_fs.keys()))
|
||||
print("Generated files:", list(agent.virtual_fs.keys()))
|
||||
|
||||
Reference in New Issue
Block a user