Create base_agent.py
Browse files- base_agent.py +52 -0
base_agent.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, Any, Optional
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
import json
|
| 5 |
+
import openai
|
| 6 |
+
|
| 7 |
+
class BaseAgent:
|
| 8 |
+
"""Base class for all agents with common functionality."""
|
| 9 |
+
|
| 10 |
+
def __init__(self, model: str = DEFAULT_LLM_MODEL):
|
| 11 |
+
"""Initialize the base agent with the specified model."""
|
| 12 |
+
if model in None:
|
| 13 |
+
model = os.getenv("DEFAULT_LLM_MODEL")
|
| 14 |
+
|
| 15 |
+
openai_key = os.getenv("OPENAI_API_KEY")
|
| 16 |
+
self.model = model
|
| 17 |
+
self.client = openai.OpenAI(api_key=openai_key)
|
| 18 |
+
|
| 19 |
+
def __call__(self, question: str, task_id: Optional[str] = None, **kwargs) -> str:
|
| 20 |
+
"""Process the question and return an answer."""
|
| 21 |
+
raise NotImplementedError("Subclasses must implement this method")
|
| 22 |
+
|
| 23 |
+
def llm_call(self, system_prompt: str, user_prompt: str,
|
| 24 |
+
temperature: float = 0.1, model: Optional[str] = None) -> str:
|
| 25 |
+
"""
|
| 26 |
+
Make a call to the LLM with the given prompts.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
system_prompt: The system prompt to guide the LLM behavior
|
| 30 |
+
user_prompt: The user prompt containing the question or task
|
| 31 |
+
temperature: Controls randomness (lower is more deterministic)
|
| 32 |
+
model: Optional override for the model to use
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
The LLM response content as a string
|
| 36 |
+
"""
|
| 37 |
+
if model is None:
|
| 38 |
+
model = self.model
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
response = self.client.chat.completions.create(
|
| 42 |
+
model=model,
|
| 43 |
+
messages=[
|
| 44 |
+
{"role": "system", "content": system_prompt},
|
| 45 |
+
{"role": "user", "content": user_prompt}
|
| 46 |
+
],
|
| 47 |
+
temperature=temperature
|
| 48 |
+
)
|
| 49 |
+
return response.choices[0].message.content
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print(f"Error calling LLM: {str(e)}")
|
| 52 |
+
return f"Error: {str(e)}"
|