import uuid from typing import Any, Dict, List, Optional, Callable, Literal from openai import AsyncOpenAI from pydantic import BaseModel import os import urllib.parse import time import inspect import json # Initialize OpenAI client client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY")) class ModelSettings(BaseModel): """Settings for the model.""" model: str = "gpt-4" temperature: float = 0.7 max_tokens: int = 500 tool_choice: Optional[str] = None class WebSearchTool: """Tool for performing web searches.""" def __init__( self, api_key: Optional[str] = None, search_context_size: Literal["low", "medium", "high"] = "medium" ): self.api_key = api_key or os.getenv("OPENAI_API_KEY") self.search_context_size = search_context_size # Adjust max_tokens based on context size self.max_tokens = { "low": 500, "medium": 1000, "high": 2000 }.get(search_context_size, 1000) def _generate_placeholder_url(self, title: str) -> str: """Generate a placeholder URL based on the search result title.""" # Convert title to URL-friendly format slug = urllib.parse.quote(title.lower().replace(' ', '-')) # Use a realistic-looking domain return f"https://research-results.org/{slug}" async def search(self, query: str) -> List[Dict[str, Any]]: """Perform a web search.""" try: if not self.api_key: print("Warning: OpenAI API key not found. Using mock search results.") # Return mock results when API key is not available return [ { "title": f"Mock result for: {query}", "snippet": f"This is a mock search result for the query: {query}", "url": self._generate_placeholder_url(f"mock-{query}") } ] # Use OpenAI's API to perform the search response = await client.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": f"You are a web search assistant. Provide {self.search_context_size} context level results."}, {"role": "user", "content": f"Search for: {query}"} ], temperature=0.7, max_tokens=self.max_tokens ) # Parse and return the results results = [] if response.choices: content = response.choices[0].message.content # Split content into results (this is a simplified version) for line in content.split('\n'): if line.strip(): title = line.split(' - ')[0] if ' - ' in line else line results.append({ "title": title, "snippet": line, "url": self._generate_placeholder_url(title) }) return results except Exception as e: print(f"Error performing web search: {str(e)}") # Return mock results on error return [ { "title": f"Error result for: {query}", "snippet": f"An error occurred while searching: {str(e)}", "url": self._generate_placeholder_url(f"error-{query}") } ] def gen_trace_id() -> str: """Generate a unique trace ID.""" return str(uuid.uuid4()) class Trace(BaseModel): """Trace model for tracking agent execution.""" trace_id: str agent_name: str input: Dict[str, Any] output: Dict[str, Any] metadata: Optional[Dict[str, Any]] = None class TraceContext: """Context manager for tracing.""" def __init__(self, agent_name: str, trace_id: Optional[str] = None): self.agent_name = agent_name self.trace_id = trace_id or gen_trace_id() self.start_time = None self.end_time = None async def __aenter__(self): self.start_time = time.time() return self async def __aexit__(self, exc_type, exc_val, exc_tb): self.end_time = time.time() duration = self.end_time - self.start_time print(f"Trace {self.trace_id} completed in {duration:.2f} seconds") def trace(agent_name: str, trace_id: Optional[str] = None) -> TraceContext: """Create a trace context for agent execution.""" return TraceContext(agent_name, trace_id) def create_trace(agent_name: str, input_data: Dict[str, Any], output_data: Dict[str, Any], metadata: Optional[Dict[str, Any]] = None) -> Trace: """Create a trace object for agent execution.""" return Trace( trace_id=gen_trace_id(), agent_name=agent_name, input=input_data, output=output_data, metadata=metadata ) def function_tool(name: str, description: str) -> Callable: """Decorator for creating function tools.""" def decorator(func: Callable) -> Callable: func.tool_name = name func.tool_description = description return func return decorator class Agent: """Base Agent class.""" def __init__( self, name: str, description: str, tools: Optional[List[Callable]] = None, instructions: Optional[str] = None, model: Optional[str] = None, model_settings: Optional[ModelSettings] = None, output_type: Optional[type] = None ): self.name = name self.description = description self.tools = tools or [] self.instructions = instructions self.model = model or "gpt-4" self.model_settings = model_settings or ModelSettings() self.output_type = output_type class Runner: """Runner class for executing agents.""" @staticmethod async def run(agent: Agent, input_data: Dict[str, Any]) -> Dict[str, Any]: """Run an agent with the given input.""" try: print(f"\n[DEBUG] Starting Runner.run for agent: {agent.name}") print(f"[DEBUG] Input data: {input_data}") # Create a trace for the execution trace_id = gen_trace_id() print(f"[DEBUG] Generated trace_id: {trace_id}") # If the agent has tools, execute them if agent.tools: print(f"[DEBUG] Agent has {len(agent.tools)} tools") result = {} final_output = None # First, try to get a response from the agent response = await client.chat.completions.create( model=agent.model, messages=[ {"role": "system", "content": agent.description}, {"role": "user", "content": str(input_data)} ], temperature=agent.model_settings.temperature, max_tokens=agent.model_settings.max_tokens ) if response.choices: final_output = response.choices[0].message.content print(f"[DEBUG] Agent response: {final_output}") # If output_type is specified, try to parse the response as JSON if agent.output_type: try: # Try to parse the response as JSON json_data = json.loads(final_output) # Validate against the output type if it's a Pydantic model if hasattr(agent.output_type, 'model_validate'): final_output = agent.output_type.model_validate(json_data) else: final_output = json_data except json.JSONDecodeError: print(f"[DEBUG] Response is not valid JSON, using raw output") # Then execute any tools for tool in agent.tools: if hasattr(tool, 'tool_name'): print(f"[DEBUG] Executing tool: {tool.tool_name}") # Handle function parameters properly if isinstance(input_data, dict): # Get the function's parameter names sig = inspect.signature(tool) param_names = list(sig.parameters.keys()) # Create kwargs dictionary with only the parameters the function expects kwargs = {k: input_data[k] for k in param_names if k in input_data} # Call the function with the correct parameters tool_result = await tool(**kwargs) else: tool_result = await tool(input_data) print(f"[DEBUG] Tool result: {tool_result}") result[tool.tool_name] = tool_result # Use the tool's result as the final output if it's not None if tool_result is not None: final_output = tool_result else: print("[DEBUG] No tools found, using OpenAI API directly") # Format the input data for the API formatted_input = "" if isinstance(input_data, dict): if "query" in input_data: formatted_input += f"Research topic: {input_data['query']}\n" if "previous_answers" in input_data and input_data["previous_answers"]: for i, answer in enumerate(input_data["previous_answers"], 1): formatted_input += f"Answer {i}: {answer}\n" else: formatted_input = str(input_data) print(f"[DEBUG] Formatted input for API: {formatted_input}") # If no tools, use OpenAI's API directly response = await client.chat.completions.create( model=agent.model, messages=[ {"role": "system", "content": agent.description}, {"role": "user", "content": formatted_input} ], temperature=agent.model_settings.temperature, max_tokens=agent.model_settings.max_tokens ) result = {"response": response.choices[0].message.content} final_output = response.choices[0].message.content # If output_type is specified, try to parse the response as JSON if agent.output_type: try: # Try to parse the response as JSON json_data = json.loads(final_output) # Validate against the output type if it's a Pydantic model if hasattr(agent.output_type, 'model_validate'): final_output = agent.output_type.model_validate(json_data) else: final_output = json_data except json.JSONDecodeError: print(f"[DEBUG] Response is not valid JSON, using raw output") # Create and return the trace print("[DEBUG] Creating trace result") trace_result = create_trace( agent_name=agent.name, input_data=input_data, output_data=result ).dict() # Add the final output print(f"[DEBUG] Adding final_output to trace_result: {final_output}") trace_result['final_output'] = final_output print(f"[DEBUG] Final trace_result: {trace_result}") return trace_result except Exception as e: print(f"[ERROR] Error in Runner.run: {str(e)}") return { "error": str(e), "trace_id": trace_id, "agent_name": agent.name, "input": input_data, "output": {}, "final_output": None }