Spaces:
No application file
No application file
File size: 8,971 Bytes
4eccf12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | #!/usr/bin/env python3
"""
AI Agent with Retrieval-Augmented Generation capabilities.
This script creates an AI agent using the OpenAI Agents SDK that integrates
with the existing Qdrant retrieval system to answer questions using book content only.
"""
import os
import json
import logging
from typing import List, Dict, Any, Optional
from agents import Agent, Runner, function_tool
from pydantic import BaseModel, Field
from agents import OpenAIChatCompletionsModel
from openai import AsyncOpenAI
# Load environment variables
from dotenv import load_dotenv
load_dotenv()
# Note: OpenRouter client will be initialized in the AgentWithRetrieval class
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class RetrievedChunk(BaseModel):
"""Represents a chunk retrieved from Qdrant."""
id: str
score: float
content: str
content_preview: str
source_url: str
source_title: str
chunk_index: int
chunk_total: int
created_at: str
original_word_count: int
class AgentWithRetrieval:
"""
AI Agent with Retrieval-Augmented Generation capabilities.
Uses OpenAI Agents SDK and integrates with existing Qdrant retrieval logic.
"""
def __init__(self):
"""Initialize the agent with OpenAI Agent SDK and retrieval tools."""
# Initialize the OpenRouter client with the free model you want to use
openrouter_api_key = os.getenv("OPENROUTER_API_KEY")
if not openrouter_api_key:
logger.warning("OPENROUTER_API_KEY environment variable not set. Please check your .env file.")
# Use your specified OpenRouter configuration
Client = AsyncOpenAI(
api_key=openrouter_api_key or "dummy-key-for-testing", # Will be replaced by actual key from .env
base_url="https://openrouter.ai/api/v1"
)
# Get model from environment variable, default to a free model if not set
openrouter_model = os.getenv("OPENROUTER_MODEL", "openrouter/mistral:mistral-7b-instruct:free")
third_party_model = OpenAIChatCompletionsModel(
openai_client=Client,
model=openrouter_model
)
# Create the agent with retrieval tools using the new Agent SDK
self.agent = Agent(
name="Book Content Assistant",
instructions=(
"You are a helpful assistant that answers questions based only on retrieved book content. "
"Always use the retrieval tool to get relevant information before answering. "
"Only provide information that comes from the retrieved chunks. "
"Do not make up information or hallucinate. "
"Always cite the source URLs when providing information."
),
model=third_party_model, # Using the OpenRouter model
tools=[self.search_qdrant_tool]
)
logger.info("Agent initialized with retrieval capabilities")
@function_tool
def _search_qdrant_function(self, query: str, top_k: int = 5) -> Dict[str, Any]:
"""
Search the Qdrant database for relevant book content chunks.
This is the tool function that will be called by the agent.
"""
# Call the existing search_qdrant method and return the result
chunks = self.search_qdrant(query, top_k)
# Format the output
output = {
"retrieved_chunks": chunks,
"count": len(chunks),
"sources": list(set([chunk["source_url"] for chunk in chunks if chunk["source_url"]]))
}
return output
# Reference the decorated function as the tool
search_qdrant_tool = _search_qdrant_function
def search_qdrant(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
"""
Search Qdrant for relevant content chunks.
This reuses the existing retrieval pipeline logic.
"""
try:
# Import the existing retrieval system from the backend
import sys
import os
# No need to modify path since we're already in the backend directory
from retrieve import RagRetrievalSystem
# Create retrieval system instance
retrieval_system = RagRetrievalSystem()
# Perform retrieval
results = retrieval_system.retrieve_and_validate(query, top_k=top_k)
# Extract relevant chunks
chunks = []
for chunk in results['retrieved_chunks']:
chunk_obj = RetrievedChunk(
id=chunk.get('id', ''),
score=chunk.get('score', 0.0),
content=chunk.get('content', ''),
content_preview=chunk.get('content_preview', ''),
source_url=chunk.get('source_url', ''),
source_title=chunk.get('source_title', ''),
chunk_index=chunk.get('chunk_index', 0),
chunk_total=chunk.get('chunk_total', 0),
created_at=chunk.get('created_at', ''),
original_word_count=chunk.get('original_word_count', 0)
)
chunks.append(chunk_obj.model_dump())
logger.info(f"Retrieved {len(chunks)} chunks for query: '{query[:50]}...'")
return chunks
except ImportError as e:
logger.error(f"Failed to import retrieval system: {str(e)}")
return []
except Exception as e:
logger.error(f"Error searching Qdrant: {str(e)}")
return []
async def run_query(self, query: str) -> str:
"""
Run a query through the agent and return the response.
The agent will use retrieval tools to get relevant content before answering.
"""
try:
# Run the agent using the new Agent SDK
result = await Runner.run(self.agent, query)
# Get the final output from the result
return result.final_output
except Exception as e:
logger.error(f"Error running query: {str(e)}")
return f"An error occurred while processing your query: {str(e)}"
async def test_connection(self) -> bool:
"""
Test the connection to both OpenAI and Qdrant.
"""
try:
# Test Qdrant connection by doing a simple search
test_chunks = self.search_qdrant("test", top_k=1)
# Test the agent by running a simple query
test_result = await self.run_query("Say hello")
logger.info("Connection test successful")
return True
except Exception as e:
logger.error(f"Connection test failed: {str(e)}")
return False
import asyncio
async def async_main():
"""Main async function to demonstrate the agent."""
logger.info("Initializing Agent with Retrieval...")
try:
# Create agent instance
agent = AgentWithRetrieval()
# Test connection
logger.info("Testing connections...")
if not await agent.test_connection():
logger.error("Failed to connect to services. Exiting.")
return
logger.info("Agent is ready to answer questions!")
logger.info("Type 'quit' to exit, 'help' for instructions")
# Interactive loop
while True:
try:
query = input("\nEnter your question: ").strip()
if query.lower() == 'quit':
logger.info("Exiting agent...")
break
elif query.lower() == 'help':
print("\nInstructions:")
print("- Ask any question about the book content")
print("- The agent will retrieve relevant information and answer based on it")
print("- Type 'quit' to exit")
continue
elif not query:
continue
logger.info(f"Processing query: '{query[:50]}...'")
# Get response from agent (now async)
response = await agent.run_query(query)
print(f"\nAgent Response:\n{response}")
except KeyboardInterrupt:
logger.info("\nExiting agent...")
break
except Exception as e:
logger.error(f"Error in main loop: {str(e)}")
print(f"An error occurred: {str(e)}")
except Exception as e:
logger.error(f"Failed to initialize agent: {str(e)}")
print(f"Error initializing agent: {str(e)}")
print("Please check your API keys and model availability.")
def main():
"""Main function to demonstrate the agent."""
# Run the async main function
asyncio.run(async_main())
if __name__ == "__main__":
main() |