update agent.py
This commit is contained in:
@@ -1,11 +1,9 @@
|
|||||||
import os
|
import os
|
||||||
from typing import Dict, Any
|
import json
|
||||||
import requests
|
import requests
|
||||||
from langchain.llms.openai import OpenAI
|
from typing import Dict, Any
|
||||||
from langchain.prompts import PromptTemplate
|
|
||||||
from langchain.chains import LLMChain
|
|
||||||
|
|
||||||
# Simple web search tool using DuckDuckGo instant answer API
|
# Simple web search using DuckDuckGo instant answer API
|
||||||
class WebSearch:
|
class WebSearch:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.base = "https://api.duckduckgo.com/"
|
self.base = "https://api.duckduckgo.com/"
|
||||||
@@ -20,32 +18,47 @@ class WebSearch:
|
|||||||
}
|
}
|
||||||
r = requests.get(self.base, params=params)
|
r = requests.get(self.base, params=params)
|
||||||
data = r.json()
|
data = r.json()
|
||||||
# Return the abstract text if available
|
return data.get("AbstractText") or (data.get("RelatedTopics", [])[0].get("Text") if data.get("RelatedTopics") else "")
|
||||||
return data.get("AbstractText", "") or data.get("RelatedTopics", [])[0].get("Text", "")
|
|
||||||
|
|
||||||
# Agent that searches and writes a virtual file
|
# DeepAgent without external libraries
|
||||||
class DeepAgent:
|
class DeepAgent:
|
||||||
def __init__(self, llm: Any):
|
def __init__(self, api_key: str):
|
||||||
self.llm = llm
|
self.api_key = api_key
|
||||||
self.search = WebSearch()
|
self.search = WebSearch()
|
||||||
self.virtual_fs: Dict[str, str] = {}
|
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:
|
def run(self, task_description: str) -> None:
|
||||||
# Step 1: Search the web for relevant info
|
# 1. Search web for context
|
||||||
search_query = f"{task_description} example"
|
query = f"{task_description} example"
|
||||||
context = self.search.run(search_query)
|
context = self.search.run(query)
|
||||||
if not context:
|
if not context:
|
||||||
context = "No context found."
|
context = "No relevant information found."
|
||||||
|
|
||||||
# Step 2: Ask LLM to generate file content based on context
|
# 2. Ask LLM to generate file content
|
||||||
prompt = PromptTemplate(
|
system_prompt = (
|
||||||
input_variables=["context", "task_description"],
|
"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."
|
||||||
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"
|
|
||||||
)
|
)
|
||||||
chain = LLMChain(llm=self.llm, prompt=prompt)
|
user_prompt = f"Task: {task_description}\nContext: {context}\nProvide only the code for output.py."
|
||||||
result = chain.run(context=context, task_description=task_description)
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt},
|
||||||
# Step 3: Store in virtual FS
|
{"role": "user", "content": user_prompt},
|
||||||
|
]
|
||||||
|
result = self._chat(messages)
|
||||||
self.virtual_fs["output.py"] = result.strip()
|
self.virtual_fs["output.py"] = result.strip()
|
||||||
|
|
||||||
def export_to_real_fs(self, repo_path: str) -> None:
|
def export_to_real_fs(self, repo_path: str) -> None:
|
||||||
@@ -56,11 +69,12 @@ class DeepAgent:
|
|||||||
|
|
||||||
# Example usage
|
# Example usage
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
llm = OpenAI(temperature=0.2, model_name="gpt-4o-mini")
|
api_key = os.getenv("OPENAI_API_KEY")
|
||||||
agent = DeepAgent(llm)
|
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'"
|
task_desc = "Create a simple Python script that prints 'Hello World'"
|
||||||
agent.run(task_desc)
|
agent.run(task_desc)
|
||||||
# Export to repository directory
|
|
||||||
repo_dir = os.path.abspath(".")
|
repo_dir = os.path.abspath(".")
|
||||||
agent.export_to_real_fs(repo_dir)
|
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