Certainly! I'll help optimize and enhance your AI agent code by addressing several areas:
-
Improved Embedding Function: Replace the simplistic hash-based embedding with a proper embedding model using LangChain's OpenAIEmbeddings for better semantic understanding.
-
Asynchronous Tool Functions: Modify tool functions to be asynchronous to fully leverage asyncio.
-
Enhanced Prompt Construction: Streamline prompt creation by integrating relevant memories and tools more effectively.
-
Robust Tool Invocation: Implement a more reliable method to detect and execute tool usage requests from the AI's response.
-
Memory Management: Limit the memory size to prevent unbounded growth and ensure efficient retrieval.
-
Error Handling and Type Hints: Add comprehensive type hints and error handling for better code reliability and readability.
Here's the optimized and improved version of your AI agent:
import asyncio
from dataclasses import dataclass, field
from typing import List, Dict, Callable, Any, Optional
from langchain.chat_models import ChatOpenAI
from langchain.schema import AIMessage, HumanMessage, SystemMessage
from langchain.prompts import ChatPromptTemplate
from langchain.embeddings import OpenAIEmbeddings
import faiss
import numpy as np
@dataclass
class AgentConfig:
model_name: str = "gpt-3.5-turbo"
temperature: float = 0.0
max_tokens: int = 1000
top_k: int = 5
embedding_model: str = "text-embedding-ada-002" # Example embedding model
memory_limit: int = 1000 # Maximum number of memories to store
@dataclass
class Message:
role: str
content: str
@dataclass
class Tool:
name: str
description: str
func: Callable[..., Any] # Can be async
class VectorStore:
def __init__(self, dimension: int):
self.dimension = dimension
self.index = faiss.IndexFlatL2(dimension)
self.texts: List[str] = []
def add(self, text: str, embedding: np.ndarray):
if embedding.shape[0] != self.dimension:
raise ValueError(f"Embedding dimension mismatch: expected {self.dimension}, got {embedding.shape[0]}")
self.index.add(embedding.reshape(1, -1))
self.texts.append(text)
def search(self, query_embedding: np.ndarray, k: int) -> List[str]:
if query_embedding.shape[0] != self.dimension:
raise ValueError(f"Query embedding dimension mismatch: expected {self.dimension}, got {query_embedding.shape[0]}")
distances, indices = self.index.search(query_embedding.reshape(1, -1), k)
results = []
for idx in indices[0]:
if idx != -1 and idx < len(self.texts):
results.append(self.texts[idx])
return results
class Agent:
def __init__(self, config: AgentConfig):
self.config = config
self.model = ChatOpenAI(
model_name=config.model_name,
temperature=config.temperature,
max_tokens=config.max_tokens
)
self.embeddings = OpenAIEmbeddings(model=config.embedding_model)
self.memory = VectorStore(dimension=self.embeddings.get_dimension())
self.tools: Dict[str, Tool] = {}
self.messages: List[Message] = []
def add_tool(self, tool: Tool):
self.tools[tool.name.lower()] = tool
async def embed(self, text: str) -> np.ndarray:
embedding = await self.embeddings.embed_query(text)
return np.array(embedding, dtype=np.float32)
async def process_message(self, user_message: str) -> str:
self.messages.append(Message(role="user", content=user_message))
# Embed the user message
user_embedding = await self.embed(user_message)
self.memory.add(user_message, user_embedding)
# Search memory for relevant contexts
relevant_memories = self.memory.search(user_embedding, self.config.top_k)
# Construct conversation history (limit to last 10 messages for context)
history = [SystemMessage(content="You are a helpful AI assistant.")]
recent_messages = self.messages[-10:]
for m in recent_messages:
if m.role == "user":
history.append(HumanMessage(content=m.content))
elif m.role == "assistant":
history.append(AIMessage(content=m.content))
# Prepare tool descriptions
if self.tools:
tools_prompt = "Available tools:\n" + "\n".join(
[f"{name}: {tool.description}" for name, tool in self.tools.items()]
)
history.append(SystemMessage(content=tools_prompt))
# Include relevant memories
if relevant_memories:
memory_prompt = "Relevant information:\n" + "\n".join(relevant_memories)
history.insert(1, SystemMessage(content=memory_prompt)) # After the assistant intro
# Create the prompt
prompt = ChatPromptTemplate.from_messages(history)
# Generate AI response
response = await self.model.agenerate(messages=prompt.messages)
ai_message = response.generations[0][0].text.strip()
# Check for tool invocation in the AI response
# Example pattern: [tool_name] parameters...
import re
tool_pattern = r"\[(\w+)]\s*(.*)"
match = re.search(tool_pattern, ai_message)
if match:
tool_name, tool_args = match.groups()
tool_name = tool_name.lower()
tool = self.tools.get(tool_name)
if tool:
try:
# If the tool function is async, await it
if asyncio.iscoroutinefunction(tool.func):
tool_output = await tool.func(tool_args)
else:
tool_output = tool.func(tool_args)
# Append tool output to AI message
ai_message += f"\n[Tool Output: {tool_output}]"
except Exception as e:
ai_message += f"\n[Tool Error: {str(e)}]"
self.messages.append(Message(role="assistant", content=ai_message))
# Embed and store the AI response
ai_embedding = await self.embed(ai_message)
self.memory.add(ai_message, ai_embedding)
# Enforce memory limit
if len(self.memory.texts) > self.config.memory_limit:
# Simple FIFO removal
excess = len(self.memory.texts) - self.config.memory_limit
self.memory.texts = self.memory.texts[excess:]
# Note: FAISS doesn't support deletion in IndexFlatL2; consider using a different index for writable memory if needed
return ai_message
async def main():
config = AgentConfig()
agent = Agent(config)
# Example asynchronous tool functions
async def async_search(query: str) -> str:
# Placeholder for an async search, e.g., using an API
await asyncio.sleep(1) # Simulate async operation
return f"Search results for '{query}'..."
async def async_calculator(expression: str) -> str:
try:
# WARNING: Using eval is dangerous. In production, use a safe parser.
result = eval(expression, {"__builtins__": {}})
return f"The result is {result}"
except Exception as e:
return f"Error in calculation: {str(e)}"
# Add tools
agent.add_tool(Tool(name="search", description="Search the internet for information.", func=async_search))
agent.add_tool(Tool(name="calculator", description="Perform mathematical calculations.", func=async_calculator))
print("AI Agent is running. Type your messages below (type 'exit' to quit).")
loop = asyncio.get_event_loop()
while True:
user_input = await loop.run_in_executor(None, input, "You: ")
if user_input.lower() == "exit":
print("Exiting AI Agent. Goodbye!")
break
try:
response = await agent.process_message(user_input)
print(f"AI: {response}\n")
except Exception as e:
print(f"Error: {str(e)}\n")
if __name__ == "__main__":
asyncio.run(main())
Key Enhancements Explained
-
Proper Embedding with OpenAIEmbeddings:
- Before: A simplistic hash-based embedding which doesn't capture semantic meaning.
- After: Utilizes
OpenAIEmbeddings from LangChain to generate meaningful vector representations of text, enhancing the relevance of memory retrieval.
from langchain.embeddings import OpenAIEmbeddings
class Agent:
# ...
def __init__(self, config: AgentConfig):
# ...
self.embeddings = OpenAIEmbeddings(model=config.embedding_model)
self.memory = VectorStore(dimension=self.embeddings.get_dimension())
async def embed(self, text: str) -> np.ndarray:
embedding = await self.embeddings.embed_query(text)
return np.array(embedding, dtype=np.float32)
-
Asynchronous Tool Functions:
- Before: Tool functions were synchronous, potentially blocking the event loop.
- After: Tool functions are designed to be asynchronous, allowing for non-blocking execution.
async def async_search(query: str) -> str:
# Implement actual async search logic here
await asyncio.sleep(1) # Simulate async operation
return f"Search results for '{query}'..."
async def async_calculator(expression: str) -> str:
try:
result = eval(expression, {"__builtins__": {}})
return f"The result is {result}"
except Exception as e:
return f"Error in calculation: {str(e)}"
# Adding tools
agent.add_tool(Tool(name="search", description="Search the internet for information.", func=async_search))
agent.add_tool(Tool(name="calculator", description="Perform mathematical calculations.", func=async_calculator))
-
Robust Tool Invocation Handling:
- Before: Simple substring check which could lead to false positives.
- After: Utilizes regex to detect tool invocation patterns like
[tool_name] arguments, ensuring precise identification and execution.
import re
# Inside process_message
tool_pattern = r"\[(\w+)]\s*(.*)"
match = re.search(tool_pattern, ai_message)
if match:
tool_name, tool_args = match.groups()
tool_name = tool_name.lower()
tool = self.tools.get(tool_name)
if tool:
try:
if asyncio.iscoroutinefunction(tool.func):
tool_output = await tool.func(tool_args)
else:
tool_output = tool.func(tool_args)
ai_message += f"\n[Tool Output: {tool_output}]"
except Exception as e:
ai_message += f"\n[Tool Error: {str(e)}]"
Additional Recommendations
-
Secure Evaluation in Calculator Tool:
- The provided
eval usage is dangerous as it can execute arbitrary code. For production, consider using a safe math parser like ast.literal_eval for simple expressions or a dedicated math expression library.
-
Persistent Memory Storage:
- Currently, memories are stored in-memory and lost when the program exits. For persistence, consider integrating a database or exporting/importing FAISS indices.
-
Advanced FAISS Indexing:
- Explore more sophisticated FAISS indices that support addition and deletion of vectors to manage memory more effectively.
-
Enhanced Tool Functionality:
- Implement actual search functionality (e.g., using an API like Bing or Google Custom Search).
- Expand tool capabilities based on user needs.
-
Rate Limiting and API Key Management:
- If deploying this agent using APIs that require keys (e.g., OpenAI), ensure proper management and rate limiting to avoid exceeding quotas.
-
Logging and Monitoring:
- Implement logging to track interactions, errors, and tool usage for better monitoring and debugging.
By implementing these optimizations and enhancements, your AI agent will be more robust, efficient, and capable of handling complex interactions with improved context understanding and tool usage.