Spaces:
No application file
No application file
Download agent.py from AyeshaZawar/ChatBot: direct link, hf CLI and curl.
- Browser
- Download file 8.97 kB
-
https://huggingface.co/spaces/AyeshaZawar/ChatBot/resolve/main/agent.py
- Command line
-
hf download hf://spaces/AyeshaZawar/ChatBot/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/AyeshaZawar/ChatBot/resolve/main/agent.py
8.97 kB
| #!/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") | |
| 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() |