Spaces:
Sleeping
Sleeping
Joachim M. Vis commited on
Upload 145 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .env_structure.txt +60 -0
- GAIA_ASSESSMENT_README.md +215 -0
- HF_README.md +22 -0
- IMPLEMENTATION_PLAN.md +155 -0
- README.md +294 -15
- README_original.md +294 -0
- SUPABASE_TABLES_README.md +122 -0
- SUPABASE_TEST_README.md +104 -0
- agent/__init__.py +22 -0
- agent/__pycache__/__init__.cpython-312.pyc +0 -0
- agent/__pycache__/__init__.cpython-313.pyc +0 -0
- agent/__pycache__/agent.cpython-312.pyc +0 -0
- agent/__pycache__/agent.cpython-313.pyc +0 -0
- agent/__pycache__/config.cpython-312.pyc +0 -0
- agent/__pycache__/config.cpython-313.pyc +0 -0
- agent/__pycache__/graph.cpython-312.pyc +0 -0
- agent/__pycache__/graph.cpython-313.pyc +0 -0
- agent/__pycache__/tool_registry.cpython-313.pyc +0 -0
- agent/agent.py +291 -0
- agent/config.py +186 -0
- agent/graph.py +452 -0
- agent/tool_registry.py +319 -0
- app.py +340 -195
- backup_tests/minimal_supabase_test.py +75 -0
- backup_tests/test_supabase_tables_final.py +167 -0
- backup_tests/test_supabase_tables_fix.py +276 -0
- backup_tests/test_supabase_tables_production.py +481 -0
- cleanup_results.txt +340 -0
- create_env_and_test.py +77 -0
- deploy_to_hf.py +161 -0
- deploy_to_huggingface.py +333 -0
- deploy_to_huggingface_credential.py +320 -0
- deploy_to_huggingface_dotenv.py +227 -0
- deploy_to_huggingface_env.py +203 -0
- deploy_with_token.py +176 -0
- deployment_readiness_report.md +97 -0
- docs/all_apis_integration_testing.md +170 -0
- docs/configuration.md +357 -0
- docs/connection_verification.md +114 -0
- docs/deployment.md +303 -0
- docs/duckduckgo_integration.md +156 -0
- docs/examples.md +197 -0
- docs/gaia_memory_integration.md +155 -0
- docs/index.md +63 -0
- docs/langchain_openai_integration.md +227 -0
- docs/multi_search_integration.md +318 -0
- docs/openai_integration_testing.md +138 -0
- docs/serper_integration.md +153 -0
- docs/supabase_memory_integration.md +175 -0
- docs/troubleshooting.md +281 -0
.env_structure.txt
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# API Keys and Endpoints
|
| 2 |
+
SUPABASE_URL=https://tjamxhvvtnypbadvrkjq.supabase.co
|
| 3 |
+
|
| 4 |
+
# API Endpoints
|
| 5 |
+
OPENAI_API_BASE=https://api.openai.com/v1
|
| 6 |
+
SERPER_API_URL=https://google.serper.dev/search
|
| 7 |
+
PERPLEXITY_API_URL=https://api.perplexity.ai
|
| 8 |
+
HUGGINGFACE_API_URL=https://api-inference.huggingface.co/models
|
| 9 |
+
|
| 10 |
+
# Model Configuration
|
| 11 |
+
DEFAULT_MODEL=gpt-4-turbo
|
| 12 |
+
EMBEDDING_MODEL=text-embedding-ada-002
|
| 13 |
+
FALLBACK_MODEL=gpt-3.5-turbo
|
| 14 |
+
VISION_MODEL=gpt-4-vision-preview
|
| 15 |
+
REASONING_MODEL=gpt-4-turbo
|
| 16 |
+
MODEL_TEMPERATURE=0.1
|
| 17 |
+
|
| 18 |
+
# Tool Parameters
|
| 19 |
+
WEB_SEARCH_RESULT_COUNT=5
|
| 20 |
+
WEB_SEARCH_TIMEOUT=10
|
| 21 |
+
ARXIV_MAX_RESULTS=3
|
| 22 |
+
DUCKDUCKGO_TIMEOUT=10
|
| 23 |
+
DUCKDUCKGO_MAX_RESULTS=5
|
| 24 |
+
PERPLEXITY_TIMEOUT=30
|
| 25 |
+
PERPLEXITY_MODEL=pplx-7b-online
|
| 26 |
+
WEB_SCRAPING_TIMEOUT=15
|
| 27 |
+
WEB_SCRAPING_MAX_LINKS=3
|
| 28 |
+
WEB_SCRAPING_MAX_CONTENT_LENGTH=10000
|
| 29 |
+
|
| 30 |
+
# Memory Settings
|
| 31 |
+
MEMORY_ENABLED=True
|
| 32 |
+
MEMORY_TABLE_NAME=gaia_memory
|
| 33 |
+
MEMORY_TTL=86400
|
| 34 |
+
MEMORY_CACHE_SIZE=100
|
| 35 |
+
MEMORY_SIMILARITY_THRESHOLD=0.85
|
| 36 |
+
MEMORY_MAX_ENTRIES=1000
|
| 37 |
+
|
| 38 |
+
# Agent Settings
|
| 39 |
+
MAX_ITERATIONS=10
|
| 40 |
+
VERBOSE=False
|
| 41 |
+
TIMEOUT=300
|
| 42 |
+
MAX_RETRIES=3
|
| 43 |
+
RETRY_DELAY=2
|
| 44 |
+
PARALLEL_TOOL_EXECUTION=False
|
| 45 |
+
|
| 46 |
+
# Logging Configuration
|
| 47 |
+
LOG_LEVEL=INFO
|
| 48 |
+
LOG_FILE=gaia_agent.log
|
| 49 |
+
LOG_FORMAT=%(asctime)s - %(name)s - %(levelname)s - %(message)s
|
| 50 |
+
|
| 51 |
+
# Multimodal Settings
|
| 52 |
+
IMAGE_MAX_SIZE=1024
|
| 53 |
+
IMAGE_FORMAT=JPEG
|
| 54 |
+
VISION_DETAIL_LEVEL=high
|
| 55 |
+
|
| 56 |
+
# Web Browsing Settings
|
| 57 |
+
USER_AGENT=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
|
| 58 |
+
BROWSER_TIMEOUT=30
|
| 59 |
+
BROWSER_HEADLESS=True
|
| 60 |
+
BROWSER_IMAGES_ENABLED=True
|
GAIA_ASSESSMENT_README.md
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA Assessment Final Integration Test
|
| 2 |
+
|
| 3 |
+
This document provides comprehensive information about the GAIA assessment, the Supabase tables fix, and how to run the final integration test.
|
| 4 |
+
|
| 5 |
+
## Table of Contents
|
| 6 |
+
|
| 7 |
+
1. [Overview](#overview)
|
| 8 |
+
2. [Supabase Tables Fix](#supabase-tables-fix)
|
| 9 |
+
3. [Scripts Created](#scripts-created)
|
| 10 |
+
4. [Running the GAIA Assessment](#running-the-gaia-assessment)
|
| 11 |
+
5. [Interpreting Results](#interpreting-results)
|
| 12 |
+
6. [Troubleshooting](#troubleshooting)
|
| 13 |
+
|
| 14 |
+
## Overview
|
| 15 |
+
|
| 16 |
+
The GAIA agent is an AI assistant that uses Supabase for memory storage. The agent uses several tables to store different types of memory:
|
| 17 |
+
|
| 18 |
+
- `gaia_memory`: Main memory table for general storage
|
| 19 |
+
- `gaia_memory_conversations`: Conversation history table
|
| 20 |
+
- `gaia_memory_cache`: Result cache table for performance optimization
|
| 21 |
+
- `gaia_memory_working`: Working memory table for complex reasoning
|
| 22 |
+
|
| 23 |
+
This integration test verifies that all components work together correctly, especially the Supabase tables fix.
|
| 24 |
+
|
| 25 |
+
## Supabase Tables Fix
|
| 26 |
+
|
| 27 |
+
### Issue Description
|
| 28 |
+
|
| 29 |
+
The original implementation had issues with the Supabase tables:
|
| 30 |
+
|
| 31 |
+
1. Tables were not being created automatically if they didn't exist
|
| 32 |
+
2. The memory system would fail if any of the required tables were missing
|
| 33 |
+
3. There was no proper error handling for table operations
|
| 34 |
+
4. The cache mechanism wasn't properly integrated with the other memory components
|
| 35 |
+
|
| 36 |
+
### Fix Implementation
|
| 37 |
+
|
| 38 |
+
The fix was implemented in the following files:
|
| 39 |
+
|
| 40 |
+
1. `memory/fix_supabase_tables.py`: Contains the main fix implementation
|
| 41 |
+
- `ensure_tables_exist()`: Creates all required tables if they don't exist
|
| 42 |
+
- `apply_monkey_patch()`: Patches the memory system to use the fixed implementation
|
| 43 |
+
|
| 44 |
+
2. `memory/supabase_memory_patch.py`: Contains the patched methods for the memory system
|
| 45 |
+
- Improved error handling
|
| 46 |
+
- Automatic table creation
|
| 47 |
+
- Better integration between memory components
|
| 48 |
+
|
| 49 |
+
3. `memory/simplified_memory_fix.py`: A simplified version of the fix for testing
|
| 50 |
+
|
| 51 |
+
The fix ensures that:
|
| 52 |
+
|
| 53 |
+
1. All required tables are created automatically if they don't exist
|
| 54 |
+
2. Operations gracefully handle missing tables by creating them
|
| 55 |
+
3. Proper error messages are provided when operations fail
|
| 56 |
+
4. The cache mechanism is properly integrated with the other memory components
|
| 57 |
+
|
| 58 |
+
## Scripts Created
|
| 59 |
+
|
| 60 |
+
The following scripts were created to test and verify the GAIA agent:
|
| 61 |
+
|
| 62 |
+
1. `verify_gaia_assessment.py`: The main integration test script
|
| 63 |
+
- Tests all components together
|
| 64 |
+
- Verifies that the Supabase tables fix is working correctly
|
| 65 |
+
- Tests with complex questions that exercise all memory types
|
| 66 |
+
- Verifies multi-turn conversations
|
| 67 |
+
- Checks caching for repeated questions
|
| 68 |
+
- Verifies working memory for complex reasoning
|
| 69 |
+
|
| 70 |
+
2. `run_gaia_with_fix.py`: A script to run the GAIA agent with the Supabase tables fix applied
|
| 71 |
+
|
| 72 |
+
3. `tests/test_supabase_tables.py`: A test script for the Supabase tables
|
| 73 |
+
- Tests table existence
|
| 74 |
+
- Tests basic memory operations
|
| 75 |
+
- Tests conversation memory
|
| 76 |
+
- Tests result cache
|
| 77 |
+
- Tests working memory
|
| 78 |
+
|
| 79 |
+
4. `tests/test_supabase_tables_comprehensive.py`: A comprehensive test for the Supabase tables
|
| 80 |
+
- More detailed tests for all memory components
|
| 81 |
+
- Performance testing for the cache mechanism
|
| 82 |
+
- Multi-turn conversation testing
|
| 83 |
+
|
| 84 |
+
5. `tests/test_all_supabase_tables.py`: A test script that verifies all Supabase tables are working correctly
|
| 85 |
+
|
| 86 |
+
6. `tests/test_gaia_with_tables.py`: A test script that verifies the GAIA agent works correctly with the Supabase tables
|
| 87 |
+
|
| 88 |
+
## Running the GAIA Assessment
|
| 89 |
+
|
| 90 |
+
### Prerequisites
|
| 91 |
+
|
| 92 |
+
Before running the GAIA assessment, make sure you have:
|
| 93 |
+
|
| 94 |
+
1. Python 3.8 or higher installed
|
| 95 |
+
2. All dependencies installed: `pip install -r requirements.txt`
|
| 96 |
+
3. Environment variables set:
|
| 97 |
+
- `OPENAI_API_KEY`: Your OpenAI API key
|
| 98 |
+
- `SUPABASE_URL`: Your Supabase URL
|
| 99 |
+
- `SUPABASE_KEY`: Your Supabase key
|
| 100 |
+
|
| 101 |
+
### Running the Final Verification
|
| 102 |
+
|
| 103 |
+
To run the final verification, use the `verify_gaia_assessment.py` script:
|
| 104 |
+
|
| 105 |
+
```bash
|
| 106 |
+
python verify_gaia_assessment.py [options]
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
Options:
|
| 110 |
+
- `--verbose`: Enable verbose logging
|
| 111 |
+
- `--show-all`: Show all table entries
|
| 112 |
+
- `--metrics`: Show detailed performance metrics
|
| 113 |
+
|
| 114 |
+
Example:
|
| 115 |
+
```bash
|
| 116 |
+
python verify_gaia_assessment.py --verbose
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
### What to Expect
|
| 120 |
+
|
| 121 |
+
The script will run a series of tests:
|
| 122 |
+
|
| 123 |
+
1. Simple Question Test: Tests a basic question to verify the agent works
|
| 124 |
+
2. Cached Question Test: Tests the same question again to verify caching
|
| 125 |
+
3. Follow-up Question Test: Tests a follow-up question to verify context retention
|
| 126 |
+
4. Complex Question Test: Tests a complex question that exercises all memory types
|
| 127 |
+
5. Multi-turn Conversation Test: Tests a multi-turn conversation to verify conversation history
|
| 128 |
+
|
| 129 |
+
After each test, the script will show:
|
| 130 |
+
- The question and answer
|
| 131 |
+
- Execution time
|
| 132 |
+
- Table state comparison (before and after)
|
| 133 |
+
- Detailed table content (if `--show-all` is specified)
|
| 134 |
+
|
| 135 |
+
The script will also verify:
|
| 136 |
+
- Working memory usage
|
| 137 |
+
- Conversation memory usage
|
| 138 |
+
- Cache usage
|
| 139 |
+
|
| 140 |
+
Finally, the script will save the results to a JSON file: `gaia_assessment_results_YYYYMMDD_HHMMSS.json`
|
| 141 |
+
|
| 142 |
+
## Interpreting Results
|
| 143 |
+
|
| 144 |
+
The results JSON file contains:
|
| 145 |
+
|
| 146 |
+
1. Timestamp: When the test was run
|
| 147 |
+
2. Tests: Results for each test
|
| 148 |
+
- Question and answer
|
| 149 |
+
- Execution time
|
| 150 |
+
- Initial and final table state
|
| 151 |
+
- Error (if any)
|
| 152 |
+
|
| 153 |
+
For the multi-turn conversation test, it also includes:
|
| 154 |
+
- All questions and answers
|
| 155 |
+
- Conversation history from memory
|
| 156 |
+
|
| 157 |
+
For the verification tests, it includes:
|
| 158 |
+
- Whether the memory component has entries
|
| 159 |
+
- The number of entries
|
| 160 |
+
- Example entries
|
| 161 |
+
|
| 162 |
+
A successful test should show:
|
| 163 |
+
- All questions answered correctly
|
| 164 |
+
- Faster execution time for cached questions
|
| 165 |
+
- Proper context retention for follow-up questions
|
| 166 |
+
- Working memory entries for complex questions
|
| 167 |
+
- Conversation history for multi-turn conversations
|
| 168 |
+
- Cache entries for repeated questions
|
| 169 |
+
|
| 170 |
+
## Troubleshooting
|
| 171 |
+
|
| 172 |
+
### Common Issues
|
| 173 |
+
|
| 174 |
+
1. **Missing Environment Variables**
|
| 175 |
+
- Error: "Missing required environment variables"
|
| 176 |
+
- Solution: Set the required environment variables (OPENAI_API_KEY, SUPABASE_URL, SUPABASE_KEY)
|
| 177 |
+
|
| 178 |
+
2. **Supabase Connection Issues**
|
| 179 |
+
- Error: "Error creating Supabase client"
|
| 180 |
+
- Solution: Check your Supabase URL and key, and make sure your Supabase instance is running
|
| 181 |
+
|
| 182 |
+
3. **OpenAI API Issues**
|
| 183 |
+
- Error: "Error initializing GAIA agent"
|
| 184 |
+
- Solution: Check your OpenAI API key and make sure you have sufficient credits
|
| 185 |
+
|
| 186 |
+
4. **Table Creation Issues**
|
| 187 |
+
- Error: "Error applying Supabase tables fix"
|
| 188 |
+
- Solution: Make sure your Supabase user has permission to create tables
|
| 189 |
+
|
| 190 |
+
5. **Memory System Issues**
|
| 191 |
+
- Error: "Error initializing memory system"
|
| 192 |
+
- Solution: Check the logs for more details, and make sure the Supabase tables fix is applied correctly
|
| 193 |
+
|
| 194 |
+
### Debugging Tips
|
| 195 |
+
|
| 196 |
+
1. Use the `--verbose` option to get more detailed logs
|
| 197 |
+
2. Check the logs for error messages and stack traces
|
| 198 |
+
3. Use the `--show-all` option to see all table entries
|
| 199 |
+
4. Check the Supabase dashboard to see if the tables were created correctly
|
| 200 |
+
5. Try running the individual test scripts to isolate issues
|
| 201 |
+
|
| 202 |
+
### Getting Help
|
| 203 |
+
|
| 204 |
+
If you encounter issues that you can't resolve, please:
|
| 205 |
+
|
| 206 |
+
1. Check the logs for error messages
|
| 207 |
+
2. Check the Supabase dashboard for table status
|
| 208 |
+
3. Try running the individual test scripts
|
| 209 |
+
4. Contact the GAIA team with the error message and logs
|
| 210 |
+
|
| 211 |
+
## Conclusion
|
| 212 |
+
|
| 213 |
+
The GAIA assessment with the Supabase tables fix should now be working correctly. The final integration test verifies that all components work together, and the fix ensures that the Supabase tables are created and used correctly.
|
| 214 |
+
|
| 215 |
+
If you have any questions or issues, please contact the GAIA team.
|
HF_README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA: Generative AI Assistant
|
| 2 |
+
|
| 3 |
+
A versatile AI assistant with memory, search capabilities, and multi-API integration.
|
| 4 |
+
|
| 5 |
+
## Features
|
| 6 |
+
|
| 7 |
+
- OpenAI integration with GPT-4 and fallback models
|
| 8 |
+
- Memory persistence with Supabase
|
| 9 |
+
- Web search capabilities via Serper and DuckDuckGo
|
| 10 |
+
- Agent-based architecture with tool registry
|
| 11 |
+
- Multi-turn conversation support
|
| 12 |
+
|
| 13 |
+
## Usage
|
| 14 |
+
|
| 15 |
+
1. Enter your query in the chat interface
|
| 16 |
+
2. GAIA will process your request, using tools as needed
|
| 17 |
+
3. Responses are retained in memory for context in future interactions
|
| 18 |
+
|
| 19 |
+
## Credits
|
| 20 |
+
|
| 21 |
+
Developed as part of the Hugging Face Agents Course
|
| 22 |
+
|
IMPLEMENTATION_PLAN.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA Agent Implementation Plan
|
| 2 |
+
|
| 3 |
+
This document outlines the detailed implementation plan for creating our GAIA agent using LangChain/LangGraph and the required tools. Each section represents a distinct implementation phase with specific tasks and deliverables.
|
| 4 |
+
|
| 5 |
+
## Phase 1: Project Setup and Dependencies
|
| 6 |
+
|
| 7 |
+
### Task 1.1: Environment Setup
|
| 8 |
+
- Create project structure with appropriate folders
|
| 9 |
+
- Set up virtual environment
|
| 10 |
+
- Update requirements.txt with all necessary dependencies:
|
| 11 |
+
```
|
| 12 |
+
gradio>=5.25.2
|
| 13 |
+
requests
|
| 14 |
+
langchain
|
| 15 |
+
langgraph
|
| 16 |
+
supabase
|
| 17 |
+
duckduckgo-search
|
| 18 |
+
beautifulsoup4
|
| 19 |
+
pillow
|
| 20 |
+
arxiv
|
| 21 |
+
perplexity-python
|
| 22 |
+
python-dotenv
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
### Task 1.2: Configuration Management
|
| 26 |
+
- Create `agent/config.py` for centralized configuration
|
| 27 |
+
- Implement environment variable loading with dotenv
|
| 28 |
+
- Define configuration for:
|
| 29 |
+
- API endpoints
|
| 30 |
+
- Model selection
|
| 31 |
+
- Tool parameters
|
| 32 |
+
- Memory settings
|
| 33 |
+
|
| 34 |
+
## Phase 2: Core Agent Architecture
|
| 35 |
+
|
| 36 |
+
### Task 2.1: Basic Agent Implementation
|
| 37 |
+
- Create `agent/agent.py` with the `GAIAAgent` class
|
| 38 |
+
- Implement the core `__call__` method to process questions
|
| 39 |
+
- Add logging and error handling
|
| 40 |
+
|
| 41 |
+
### Task 2.2: LangGraph Workflow
|
| 42 |
+
- Create `agent/graph.py` to define the agent's workflow
|
| 43 |
+
- Implement nodes for:
|
| 44 |
+
- Question analysis
|
| 45 |
+
- Planning
|
| 46 |
+
- Tool selection
|
| 47 |
+
- Tool execution
|
| 48 |
+
- Answer formulation
|
| 49 |
+
- Define edges between nodes and conditional routing
|
| 50 |
+
|
| 51 |
+
### Task 2.3: Memory Integration
|
| 52 |
+
- Create `memory/supabase_memory.py` for persistent memory
|
| 53 |
+
- Implement memory interfaces for:
|
| 54 |
+
- Storing intermediate results
|
| 55 |
+
- Caching previous answers
|
| 56 |
+
- Maintaining conversation context
|
| 57 |
+
|
| 58 |
+
## Phase 3: Tool Implementation
|
| 59 |
+
|
| 60 |
+
### Task 3.1: Web Browsing Tools
|
| 61 |
+
- Create `tools/web_tools.py` with implementations for:
|
| 62 |
+
- Web search (DuckDuckGo, Serper)
|
| 63 |
+
- Web page content extraction
|
| 64 |
+
- URL navigation and scraping
|
| 65 |
+
|
| 66 |
+
### Task 3.2: Reasoning Tools
|
| 67 |
+
- Create `tools/reasoning_tools.py` with implementations for:
|
| 68 |
+
- Step-by-step reasoning
|
| 69 |
+
- Mathematical calculations
|
| 70 |
+
- Fact verification
|
| 71 |
+
|
| 72 |
+
### Task 3.3: Multimodal Tools
|
| 73 |
+
- Create `tools/multimodal_tools.py` with implementations for:
|
| 74 |
+
- Image analysis and description
|
| 75 |
+
- Chart/graph interpretation
|
| 76 |
+
- Document parsing
|
| 77 |
+
|
| 78 |
+
### Task 3.4: Tool Registry
|
| 79 |
+
- Create `tools/__init__.py` with a tool registry
|
| 80 |
+
- Implement tool selection logic based on question requirements
|
| 81 |
+
- Add metadata to tools for better selection
|
| 82 |
+
|
| 83 |
+
## Phase 4: Question Processing
|
| 84 |
+
|
| 85 |
+
### Task 4.1: Question Analysis
|
| 86 |
+
- Create `utils/parsing.py` with functions for:
|
| 87 |
+
- Extracting key information from questions
|
| 88 |
+
- Identifying required tools
|
| 89 |
+
- Determining question complexity
|
| 90 |
+
|
| 91 |
+
### Task 4.2: Answer Formatting
|
| 92 |
+
- Implement answer extraction and formatting
|
| 93 |
+
- Ensure answers match the expected format (number, few words, comma-separated list)
|
| 94 |
+
- Add validation to verify answer format before submission
|
| 95 |
+
|
| 96 |
+
## Phase 5: Integration with Gradio Interface
|
| 97 |
+
|
| 98 |
+
### Task 5.1: Agent Integration
|
| 99 |
+
- Update `app.py` to use our new `GAIAAgent` class
|
| 100 |
+
- Ensure proper error handling and logging
|
| 101 |
+
- Implement progress tracking for long-running operations
|
| 102 |
+
|
| 103 |
+
### Task 5.2: UI Enhancements
|
| 104 |
+
- Add optional UI improvements:
|
| 105 |
+
- Progress indicators
|
| 106 |
+
- Detailed result views
|
| 107 |
+
- Error explanations
|
| 108 |
+
|
| 109 |
+
## Phase 6: Testing and Evaluation
|
| 110 |
+
|
| 111 |
+
### Task 6.1: Unit Testing
|
| 112 |
+
- Create test cases for individual components
|
| 113 |
+
- Implement automated tests for tools and utilities
|
| 114 |
+
- Add integration tests for the complete agent workflow
|
| 115 |
+
|
| 116 |
+
### Task 6.2: Benchmark Testing
|
| 117 |
+
- Test against sample GAIA questions
|
| 118 |
+
- Measure performance and accuracy
|
| 119 |
+
- Identify and address bottlenecks
|
| 120 |
+
|
| 121 |
+
## Phase 7: Documentation and Deployment
|
| 122 |
+
|
| 123 |
+
### Task 7.1: Code Documentation
|
| 124 |
+
- Add comprehensive docstrings to all functions and classes
|
| 125 |
+
- Create usage examples
|
| 126 |
+
- Document configuration options
|
| 127 |
+
|
| 128 |
+
### Task 7.2: Deployment Preparation
|
| 129 |
+
- Ensure all dependencies are properly specified
|
| 130 |
+
- Verify compatibility with Hugging Face Spaces
|
| 131 |
+
- Create deployment instructions
|
| 132 |
+
|
| 133 |
+
## Implementation Timeline
|
| 134 |
+
|
| 135 |
+
| Phase | Estimated Duration | Dependencies |
|
| 136 |
+
|-------|-------------------|--------------|
|
| 137 |
+
| 1: Project Setup | 1 day | None |
|
| 138 |
+
| 2: Core Architecture | 2 days | Phase 1 |
|
| 139 |
+
| 3: Tool Implementation | 3 days | Phase 2 |
|
| 140 |
+
| 4: Question Processing | 2 days | Phase 2 |
|
| 141 |
+
| 5: Gradio Integration | 1 day | Phases 2-4 |
|
| 142 |
+
| 6: Testing | 2 days | Phases 1-5 |
|
| 143 |
+
| 7: Documentation | 1 day | Phases 1-6 |
|
| 144 |
+
|
| 145 |
+
## Success Criteria
|
| 146 |
+
|
| 147 |
+
- Agent successfully answers at least 30% of GAIA benchmark questions
|
| 148 |
+
- Code is well-organized, documented, and maintainable
|
| 149 |
+
- Implementation follows best practices for LangChain/LangGraph
|
| 150 |
+
- All tools function correctly and efficiently
|
| 151 |
+
- Submission process works end-to-end
|
| 152 |
+
|
| 153 |
+
## Next Steps
|
| 154 |
+
|
| 155 |
+
After reviewing this implementation plan, we will proceed with Phase 1 by setting up the project structure and installing dependencies. Each subsequent phase will be implemented as a separate task, with regular testing and validation throughout the process.
|
README.md
CHANGED
|
@@ -1,15 +1,294 @@
|
|
| 1 |
-
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA Agent - Hugging Face Agents Course Final Project
|
| 2 |
+
|
| 3 |
+
## Project Overview
|
| 4 |
+
|
| 5 |
+
This project implements an intelligent agent capable of answering questions from the GAIA (Grounded AI Alignment) benchmark as part of the Hugging Face Agents Course final assignment. The agent leverages LangChain/LangGraph frameworks and various tools to solve complex, multi-step reasoning tasks.
|
| 6 |
+
|
| 7 |
+
## What is GAIA?
|
| 8 |
+
|
| 9 |
+
GAIA is a benchmark designed to evaluate AI assistants on real-world tasks that require a combination of core capabilities:
|
| 10 |
+
- Reasoning across multiple steps
|
| 11 |
+
- Multimodal understanding (text, images, etc.)
|
| 12 |
+
- Web browsing and information retrieval
|
| 13 |
+
- Proficient tool use
|
| 14 |
+
|
| 15 |
+
The benchmark consists of 466 carefully curated questions that are conceptually simple for humans (~92% success rate) but challenging for current AI systems (GPT-4 with plugins: ~15% success rate).
|
| 16 |
+
|
| 17 |
+
## Challenge Requirements
|
| 18 |
+
|
| 19 |
+
- **Task**: Create an agent that answers questions from a subset of GAIA (20 questions from level 1)
|
| 20 |
+
- **Success Criteria**: Score at least 30% on the benchmark
|
| 21 |
+
- **Evaluation Method**: Exact match comparison with ground truth answers
|
| 22 |
+
- **Response Format**: Answers should be concise (number, few words, or comma-separated list)
|
| 23 |
+
|
| 24 |
+
## Technical Architecture
|
| 25 |
+
|
| 26 |
+
Our implementation uses:
|
| 27 |
+
|
| 28 |
+
1. **LangChain/LangGraph**: For creating a flexible, modular agent architecture
|
| 29 |
+
2. **Supabase**: For memory management and persistence
|
| 30 |
+
3. **Web Tools**: Integration with search engines (DuckDuckGo, Serper), academic resources (arXiv), and AI assistants (Perplexity)
|
| 31 |
+
4. **Gradio**: For the user interface and submission process
|
| 32 |
+
|
| 33 |
+
## Project Structure
|
| 34 |
+
|
| 35 |
+
```
|
| 36 |
+
├── README.md # Project documentation
|
| 37 |
+
├── app.py # Main application file with Gradio interface
|
| 38 |
+
├── requirements.txt # Project dependencies
|
| 39 |
+
├── agent/ # Agent implementation
|
| 40 |
+
│ ├── __init__.py # Package initialization
|
| 41 |
+
│ ├── agent.py # Main agent class
|
| 42 |
+
│ ├── config.py # Configuration settings
|
| 43 |
+
│ ├── graph.py # LangGraph workflow definition
|
| 44 |
+
│ └── tool_registry.py # Tool registration and management
|
| 45 |
+
├── tools/ # Tool implementations
|
| 46 |
+
│ ├── __init__.py # Package initialization
|
| 47 |
+
│ ├── web_tools.py # Web browsing and search tools
|
| 48 |
+
│ ├── reasoning_tools.py # Reasoning and analysis tools
|
| 49 |
+
│ ├── multimodal_tools.py # Tools for handling images and other media
|
| 50 |
+
│ ├── arxiv_tool.py # Tools for searching academic papers
|
| 51 |
+
│ └── perplexity_tool.py # Integration with Perplexity AI
|
| 52 |
+
├── memory/ # Memory management
|
| 53 |
+
│ ├── __init__.py # Package initialization
|
| 54 |
+
│ ├── supabase_memory.py # Supabase integration for memory
|
| 55 |
+
│ ├── supabase_memory_patch.py # Patches for Supabase memory
|
| 56 |
+
│ └── simplified_memory_fix.py # Simplified memory implementation
|
| 57 |
+
└── utils/ # Utility functions
|
| 58 |
+
├── __init__.py # Package initialization
|
| 59 |
+
├── parsing.py # Functions for parsing questions and answers
|
| 60 |
+
└── formatting.py # Formatting utilities
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
## Implementation Approach
|
| 64 |
+
|
| 65 |
+
Our agent follows a multi-step process to answer GAIA questions:
|
| 66 |
+
|
| 67 |
+
1. **Question Analysis**: Parse and understand the question, identifying required tools and information sources
|
| 68 |
+
2. **Planning**: Develop a step-by-step plan to answer the question
|
| 69 |
+
3. **Tool Execution**: Use appropriate tools in the correct sequence
|
| 70 |
+
4. **Answer Formulation**: Extract and format the precise answer from the results
|
| 71 |
+
5. **Verification**: Validate the answer format and content before submission
|
| 72 |
+
|
| 73 |
+
## Key Features
|
| 74 |
+
|
| 75 |
+
- **Modular Architecture**: Easily extensible with new tools and capabilities
|
| 76 |
+
- **Robust Error Handling**: Graceful recovery from tool failures or unexpected results
|
| 77 |
+
- **Efficient Tool Selection**: Smart selection of the most appropriate tools for each question
|
| 78 |
+
- **Answer Precision**: Focus on extracting exact answers that match the ground truth format
|
| 79 |
+
- **Memory Integration**: Persistent memory across sessions using Supabase
|
| 80 |
+
|
| 81 |
+
## Getting Started
|
| 82 |
+
|
| 83 |
+
### Prerequisites
|
| 84 |
+
|
| 85 |
+
- Python 3.8 or higher
|
| 86 |
+
- OpenAI API key
|
| 87 |
+
- Supabase account and API key (for memory features)
|
| 88 |
+
- Optional: Serper API key (for enhanced search)
|
| 89 |
+
- Optional: Perplexity API key (for enhanced reasoning)
|
| 90 |
+
|
| 91 |
+
### Installation
|
| 92 |
+
|
| 93 |
+
1. Clone this repository
|
| 94 |
+
2. Install dependencies:
|
| 95 |
+
```bash
|
| 96 |
+
pip install -r requirements.txt
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
> **Note**: If you encounter issues with the `langchain_openai` dependency, make sure you have the latest version installed:
|
| 100 |
+
> ```bash
|
| 101 |
+
> pip install --upgrade langchain_openai
|
| 102 |
+
> ```
|
| 103 |
+
|
| 104 |
+
3. Set up environment variables (create a `.env` file in the project root):
|
| 105 |
+
```
|
| 106 |
+
OPENAI_API_KEY=your_openai_api_key
|
| 107 |
+
SUPABASE_KEY=your_supabase_api_key
|
| 108 |
+
SERPER_API_KEY=your_serper_api_key (optional)
|
| 109 |
+
PERPLEXITY_API_KEY=your_perplexity_api_key (optional)
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
4. Run the application:
|
| 113 |
+
```bash
|
| 114 |
+
python app.py
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
5. Log in with your Hugging Face account
|
| 118 |
+
6. Click "Run Evaluation & Submit All Answers" to test the agent
|
| 119 |
+
|
| 120 |
+
## Testing
|
| 121 |
+
|
| 122 |
+
The project includes comprehensive unit tests for all components:
|
| 123 |
+
|
| 124 |
+
- **Agent Tests**: Test the GAIAAgent class and its workflow
|
| 125 |
+
- **Tools Tests**: Test the web, reasoning, and multimodal tools
|
| 126 |
+
- **Memory Tests**: Test the memory components and Supabase integration
|
| 127 |
+
- **Utils Tests**: Test utility functions for parsing and formatting
|
| 128 |
+
- **Integration Tests**: Test integration with external APIs like OpenAI and Perplexity
|
| 129 |
+
|
| 130 |
+
To run all tests:
|
| 131 |
+
```bash
|
| 132 |
+
python -m unittest discover tests
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
To run specific test files:
|
| 136 |
+
```bash
|
| 137 |
+
python -m unittest tests.test_agent
|
| 138 |
+
python -m unittest tests.test_tools
|
| 139 |
+
python -m unittest tests.test_memory
|
| 140 |
+
python -m unittest tests.test_utils
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
### OpenAI Integration Testing
|
| 144 |
+
|
| 145 |
+
The project includes specialized tests for OpenAI integration with newer models:
|
| 146 |
+
|
| 147 |
+
```bash
|
| 148 |
+
# Test OpenAI integration with newer models
|
| 149 |
+
python tests/test_openai_integration.py
|
| 150 |
+
|
| 151 |
+
# Test OpenAI integration with GAIA agent
|
| 152 |
+
python tests/test_openai_integration.py --test-agent
|
| 153 |
+
|
| 154 |
+
# Test GAIA agent with multiple AI providers (OpenAI and Perplexity)
|
| 155 |
+
python tests/test_gaia_multi_provider.py
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
For convenience, you can run all OpenAI integration tests at once:
|
| 159 |
+
|
| 160 |
+
```bash
|
| 161 |
+
# Run all OpenAI integration tests
|
| 162 |
+
python tests/run_openai_tests.py
|
| 163 |
+
|
| 164 |
+
# Run all tests with verbose logging
|
| 165 |
+
python tests/run_openai_tests.py --verbose
|
| 166 |
+
|
| 167 |
+
# Run all tests and save results to a custom directory
|
| 168 |
+
python tests/run_openai_tests.py --output my_test_results
|
| 169 |
+
|
| 170 |
+
# Stop running tests after the first failure
|
| 171 |
+
python tests/run_openai_tests.py --stop-on-failure
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
These tests verify that:
|
| 175 |
+
- The OpenAI API connection works correctly
|
| 176 |
+
- Newer models like GPT-4o can be used successfully
|
| 177 |
+
- The GAIA agent can use both OpenAI and Perplexity tools together
|
| 178 |
+
|
| 179 |
+
### API Integration Testing
|
| 180 |
+
|
| 181 |
+
To test all API integrations together:
|
| 182 |
+
|
| 183 |
+
```bash
|
| 184 |
+
# Run all API integration tests
|
| 185 |
+
python tests/run_all_apis_integration_test.py
|
| 186 |
+
|
| 187 |
+
# Run with verbose logging
|
| 188 |
+
python tests/run_all_apis_integration_test.py --verbose
|
| 189 |
+
|
| 190 |
+
# Specify a custom output file
|
| 191 |
+
python tests/run_all_apis_integration_test.py --report-file my_report.json
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
### Supabase Integration Testing
|
| 195 |
+
|
| 196 |
+
To test the Supabase memory integration:
|
| 197 |
+
|
| 198 |
+
```bash
|
| 199 |
+
# Run all Supabase integration tests
|
| 200 |
+
python tests/run_supabase_integration_tests.py
|
| 201 |
+
|
| 202 |
+
# Run with verbose logging
|
| 203 |
+
python tests/run_supabase_integration_tests.py --verbose
|
| 204 |
+
|
| 205 |
+
# Specify a custom output directory
|
| 206 |
+
python tests/run_supabase_integration_tests.py --output-dir custom_docs
|
| 207 |
+
```
|
| 208 |
+
|
| 209 |
+
## Evaluation
|
| 210 |
+
|
| 211 |
+
The agent is evaluated on its ability to provide exact matches to the ground truth answers for the GAIA benchmark questions. The submission process includes:
|
| 212 |
+
|
| 213 |
+
- Fetching questions from the course API
|
| 214 |
+
- Running the agent on each question
|
| 215 |
+
- Submitting answers for scoring
|
| 216 |
+
- Viewing results on the leaderboard
|
| 217 |
+
|
| 218 |
+
## Benchmark Testing
|
| 219 |
+
|
| 220 |
+
The project includes a benchmark testing framework to evaluate the agent's performance:
|
| 221 |
+
|
| 222 |
+
```bash
|
| 223 |
+
# Run benchmark tests with default settings
|
| 224 |
+
python -m tests.benchmark --output benchmark_results.json
|
| 225 |
+
|
| 226 |
+
# Run benchmark tests with custom questions
|
| 227 |
+
python -m tests.benchmark --questions custom_questions.json --output benchmark_results.json
|
| 228 |
+
|
| 229 |
+
# Run benchmark tests with a specific number of questions
|
| 230 |
+
python -m tests.benchmark --max-questions 5 --output benchmark_results.json
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
The benchmark testing framework:
|
| 234 |
+
- Tests the agent against sample questions
|
| 235 |
+
- Measures performance metrics (accuracy, latency, resource usage)
|
| 236 |
+
- Generates detailed reports of benchmark results
|
| 237 |
+
- Allows comparison of different agent configurations
|
| 238 |
+
|
| 239 |
+
## Troubleshooting
|
| 240 |
+
|
| 241 |
+
### Common Issues
|
| 242 |
+
|
| 243 |
+
#### 1. langchain_openai Dependency Issues
|
| 244 |
+
|
| 245 |
+
If you encounter errors related to the `langchain_openai` package, such as:
|
| 246 |
+
- `ImportError: No module named 'langchain_openai'`
|
| 247 |
+
- `AttributeError: module 'langchain_openai' has no attribute 'ChatOpenAI'`
|
| 248 |
+
|
| 249 |
+
Try the following solutions:
|
| 250 |
+
- Ensure you have the latest version installed: `pip install --upgrade langchain_openai`
|
| 251 |
+
- Make sure you're using the correct import: `from langchain_openai import ChatOpenAI`
|
| 252 |
+
- Check for conflicts with older langchain versions: `pip uninstall langchain-openai` (note the hyphen)
|
| 253 |
+
|
| 254 |
+
#### 2. API Connection Issues
|
| 255 |
+
|
| 256 |
+
If you're having trouble connecting to external APIs:
|
| 257 |
+
- Verify that your API keys are correctly set in the environment variables
|
| 258 |
+
- Check that the API service is not experiencing downtime
|
| 259 |
+
- Ensure you have a stable internet connection
|
| 260 |
+
- Check for rate limiting or quota issues
|
| 261 |
+
|
| 262 |
+
#### 3. Supabase Connection Issues
|
| 263 |
+
|
| 264 |
+
If you're having trouble with Supabase:
|
| 265 |
+
- Verify that your Supabase URL and API key are correctly set
|
| 266 |
+
- Ensure that the required tables exist in your Supabase project
|
| 267 |
+
- Check that your API key has the necessary permissions
|
| 268 |
+
- Verify that your Supabase project is active
|
| 269 |
+
|
| 270 |
+
#### 4. Memory Issues
|
| 271 |
+
|
| 272 |
+
If you're experiencing issues with the agent's memory:
|
| 273 |
+
- Check that memory is enabled in the configuration
|
| 274 |
+
- Verify that the table names are correctly set
|
| 275 |
+
- Ensure that the TTL and cache size settings are appropriate
|
| 276 |
+
- Check for errors in the Supabase logs
|
| 277 |
+
|
| 278 |
+
## Documentation
|
| 279 |
+
|
| 280 |
+
Comprehensive documentation is available in the `docs/` directory:
|
| 281 |
+
|
| 282 |
+
- [Usage Examples](docs/examples.md): Examples of how to use the GAIA agent in different scenarios
|
| 283 |
+
- [Configuration Guide](docs/configuration.md): Detailed information about configuration options
|
| 284 |
+
- [Deployment Guide](docs/deployment.md): Instructions for deploying the agent in various environments
|
| 285 |
+
- [OpenAI Integration Testing](docs/openai_integration_testing.md): Guide for testing OpenAI integration with newer models
|
| 286 |
+
- [Connection Verification](docs/connection_verification.md): Guide for verifying connections to external services
|
| 287 |
+
- [Supabase Memory Integration](docs/supabase_memory_integration.md): Guide for setting up and using Supabase memory
|
| 288 |
+
- [All APIs Integration Testing](docs/all_apis_integration_testing.md): Guide for testing all API integrations together
|
| 289 |
+
- [Multi-Search Integration](docs/multi_search_integration.md): Guide for using multiple search providers
|
| 290 |
+
- [GAIA Memory Integration](docs/gaia_memory_integration.md): Guide for using memory in the GAIA agent
|
| 291 |
+
|
| 292 |
+
## License
|
| 293 |
+
|
| 294 |
+
This project is part of the Hugging Face Agents Course and follows its licensing terms.
|
README_original.md
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA Agent - Hugging Face Agents Course Final Project
|
| 2 |
+
|
| 3 |
+
## Project Overview
|
| 4 |
+
|
| 5 |
+
This project implements an intelligent agent capable of answering questions from the GAIA (Grounded AI Alignment) benchmark as part of the Hugging Face Agents Course final assignment. The agent leverages LangChain/LangGraph frameworks and various tools to solve complex, multi-step reasoning tasks.
|
| 6 |
+
|
| 7 |
+
## What is GAIA?
|
| 8 |
+
|
| 9 |
+
GAIA is a benchmark designed to evaluate AI assistants on real-world tasks that require a combination of core capabilities:
|
| 10 |
+
- Reasoning across multiple steps
|
| 11 |
+
- Multimodal understanding (text, images, etc.)
|
| 12 |
+
- Web browsing and information retrieval
|
| 13 |
+
- Proficient tool use
|
| 14 |
+
|
| 15 |
+
The benchmark consists of 466 carefully curated questions that are conceptually simple for humans (~92% success rate) but challenging for current AI systems (GPT-4 with plugins: ~15% success rate).
|
| 16 |
+
|
| 17 |
+
## Challenge Requirements
|
| 18 |
+
|
| 19 |
+
- **Task**: Create an agent that answers questions from a subset of GAIA (20 questions from level 1)
|
| 20 |
+
- **Success Criteria**: Score at least 30% on the benchmark
|
| 21 |
+
- **Evaluation Method**: Exact match comparison with ground truth answers
|
| 22 |
+
- **Response Format**: Answers should be concise (number, few words, or comma-separated list)
|
| 23 |
+
|
| 24 |
+
## Technical Architecture
|
| 25 |
+
|
| 26 |
+
Our implementation uses:
|
| 27 |
+
|
| 28 |
+
1. **LangChain/LangGraph**: For creating a flexible, modular agent architecture
|
| 29 |
+
2. **Supabase**: For memory management and persistence
|
| 30 |
+
3. **Web Tools**: Integration with search engines (DuckDuckGo, Serper), academic resources (arXiv), and AI assistants (Perplexity)
|
| 31 |
+
4. **Gradio**: For the user interface and submission process
|
| 32 |
+
|
| 33 |
+
## Project Structure
|
| 34 |
+
|
| 35 |
+
```
|
| 36 |
+
├── README.md # Project documentation
|
| 37 |
+
├── app.py # Main application file with Gradio interface
|
| 38 |
+
├── requirements.txt # Project dependencies
|
| 39 |
+
├── agent/ # Agent implementation
|
| 40 |
+
│ ├── __init__.py # Package initialization
|
| 41 |
+
│ ├── agent.py # Main agent class
|
| 42 |
+
│ ├── config.py # Configuration settings
|
| 43 |
+
│ ├── graph.py # LangGraph workflow definition
|
| 44 |
+
│ └── tool_registry.py # Tool registration and management
|
| 45 |
+
├── tools/ # Tool implementations
|
| 46 |
+
│ ├── __init__.py # Package initialization
|
| 47 |
+
│ ├── web_tools.py # Web browsing and search tools
|
| 48 |
+
│ ├── reasoning_tools.py # Reasoning and analysis tools
|
| 49 |
+
│ ├── multimodal_tools.py # Tools for handling images and other media
|
| 50 |
+
│ ├── arxiv_tool.py # Tools for searching academic papers
|
| 51 |
+
│ └── perplexity_tool.py # Integration with Perplexity AI
|
| 52 |
+
├── memory/ # Memory management
|
| 53 |
+
│ ├── __init__.py # Package initialization
|
| 54 |
+
│ ├── supabase_memory.py # Supabase integration for memory
|
| 55 |
+
│ ├── supabase_memory_patch.py # Patches for Supabase memory
|
| 56 |
+
│ └── simplified_memory_fix.py # Simplified memory implementation
|
| 57 |
+
└── utils/ # Utility functions
|
| 58 |
+
├── __init__.py # Package initialization
|
| 59 |
+
├── parsing.py # Functions for parsing questions and answers
|
| 60 |
+
└── formatting.py # Formatting utilities
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
## Implementation Approach
|
| 64 |
+
|
| 65 |
+
Our agent follows a multi-step process to answer GAIA questions:
|
| 66 |
+
|
| 67 |
+
1. **Question Analysis**: Parse and understand the question, identifying required tools and information sources
|
| 68 |
+
2. **Planning**: Develop a step-by-step plan to answer the question
|
| 69 |
+
3. **Tool Execution**: Use appropriate tools in the correct sequence
|
| 70 |
+
4. **Answer Formulation**: Extract and format the precise answer from the results
|
| 71 |
+
5. **Verification**: Validate the answer format and content before submission
|
| 72 |
+
|
| 73 |
+
## Key Features
|
| 74 |
+
|
| 75 |
+
- **Modular Architecture**: Easily extensible with new tools and capabilities
|
| 76 |
+
- **Robust Error Handling**: Graceful recovery from tool failures or unexpected results
|
| 77 |
+
- **Efficient Tool Selection**: Smart selection of the most appropriate tools for each question
|
| 78 |
+
- **Answer Precision**: Focus on extracting exact answers that match the ground truth format
|
| 79 |
+
- **Memory Integration**: Persistent memory across sessions using Supabase
|
| 80 |
+
|
| 81 |
+
## Getting Started
|
| 82 |
+
|
| 83 |
+
### Prerequisites
|
| 84 |
+
|
| 85 |
+
- Python 3.8 or higher
|
| 86 |
+
- OpenAI API key
|
| 87 |
+
- Supabase account and API key (for memory features)
|
| 88 |
+
- Optional: Serper API key (for enhanced search)
|
| 89 |
+
- Optional: Perplexity API key (for enhanced reasoning)
|
| 90 |
+
|
| 91 |
+
### Installation
|
| 92 |
+
|
| 93 |
+
1. Clone this repository
|
| 94 |
+
2. Install dependencies:
|
| 95 |
+
```bash
|
| 96 |
+
pip install -r requirements.txt
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
> **Note**: If you encounter issues with the `langchain_openai` dependency, make sure you have the latest version installed:
|
| 100 |
+
> ```bash
|
| 101 |
+
> pip install --upgrade langchain_openai
|
| 102 |
+
> ```
|
| 103 |
+
|
| 104 |
+
3. Set up environment variables (create a `.env` file in the project root):
|
| 105 |
+
```
|
| 106 |
+
OPENAI_API_KEY=your_openai_api_key
|
| 107 |
+
SUPABASE_KEY=your_supabase_api_key
|
| 108 |
+
SERPER_API_KEY=your_serper_api_key (optional)
|
| 109 |
+
PERPLEXITY_API_KEY=your_perplexity_api_key (optional)
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
4. Run the application:
|
| 113 |
+
```bash
|
| 114 |
+
python app.py
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
5. Log in with your Hugging Face account
|
| 118 |
+
6. Click "Run Evaluation & Submit All Answers" to test the agent
|
| 119 |
+
|
| 120 |
+
## Testing
|
| 121 |
+
|
| 122 |
+
The project includes comprehensive unit tests for all components:
|
| 123 |
+
|
| 124 |
+
- **Agent Tests**: Test the GAIAAgent class and its workflow
|
| 125 |
+
- **Tools Tests**: Test the web, reasoning, and multimodal tools
|
| 126 |
+
- **Memory Tests**: Test the memory components and Supabase integration
|
| 127 |
+
- **Utils Tests**: Test utility functions for parsing and formatting
|
| 128 |
+
- **Integration Tests**: Test integration with external APIs like OpenAI and Perplexity
|
| 129 |
+
|
| 130 |
+
To run all tests:
|
| 131 |
+
```bash
|
| 132 |
+
python -m unittest discover tests
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
To run specific test files:
|
| 136 |
+
```bash
|
| 137 |
+
python -m unittest tests.test_agent
|
| 138 |
+
python -m unittest tests.test_tools
|
| 139 |
+
python -m unittest tests.test_memory
|
| 140 |
+
python -m unittest tests.test_utils
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
### OpenAI Integration Testing
|
| 144 |
+
|
| 145 |
+
The project includes specialized tests for OpenAI integration with newer models:
|
| 146 |
+
|
| 147 |
+
```bash
|
| 148 |
+
# Test OpenAI integration with newer models
|
| 149 |
+
python tests/test_openai_integration.py
|
| 150 |
+
|
| 151 |
+
# Test OpenAI integration with GAIA agent
|
| 152 |
+
python tests/test_openai_integration.py --test-agent
|
| 153 |
+
|
| 154 |
+
# Test GAIA agent with multiple AI providers (OpenAI and Perplexity)
|
| 155 |
+
python tests/test_gaia_multi_provider.py
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
For convenience, you can run all OpenAI integration tests at once:
|
| 159 |
+
|
| 160 |
+
```bash
|
| 161 |
+
# Run all OpenAI integration tests
|
| 162 |
+
python tests/run_openai_tests.py
|
| 163 |
+
|
| 164 |
+
# Run all tests with verbose logging
|
| 165 |
+
python tests/run_openai_tests.py --verbose
|
| 166 |
+
|
| 167 |
+
# Run all tests and save results to a custom directory
|
| 168 |
+
python tests/run_openai_tests.py --output my_test_results
|
| 169 |
+
|
| 170 |
+
# Stop running tests after the first failure
|
| 171 |
+
python tests/run_openai_tests.py --stop-on-failure
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
These tests verify that:
|
| 175 |
+
- The OpenAI API connection works correctly
|
| 176 |
+
- Newer models like GPT-4o can be used successfully
|
| 177 |
+
- The GAIA agent can use both OpenAI and Perplexity tools together
|
| 178 |
+
|
| 179 |
+
### API Integration Testing
|
| 180 |
+
|
| 181 |
+
To test all API integrations together:
|
| 182 |
+
|
| 183 |
+
```bash
|
| 184 |
+
# Run all API integration tests
|
| 185 |
+
python tests/run_all_apis_integration_test.py
|
| 186 |
+
|
| 187 |
+
# Run with verbose logging
|
| 188 |
+
python tests/run_all_apis_integration_test.py --verbose
|
| 189 |
+
|
| 190 |
+
# Specify a custom output file
|
| 191 |
+
python tests/run_all_apis_integration_test.py --report-file my_report.json
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
### Supabase Integration Testing
|
| 195 |
+
|
| 196 |
+
To test the Supabase memory integration:
|
| 197 |
+
|
| 198 |
+
```bash
|
| 199 |
+
# Run all Supabase integration tests
|
| 200 |
+
python tests/run_supabase_integration_tests.py
|
| 201 |
+
|
| 202 |
+
# Run with verbose logging
|
| 203 |
+
python tests/run_supabase_integration_tests.py --verbose
|
| 204 |
+
|
| 205 |
+
# Specify a custom output directory
|
| 206 |
+
python tests/run_supabase_integration_tests.py --output-dir custom_docs
|
| 207 |
+
```
|
| 208 |
+
|
| 209 |
+
## Evaluation
|
| 210 |
+
|
| 211 |
+
The agent is evaluated on its ability to provide exact matches to the ground truth answers for the GAIA benchmark questions. The submission process includes:
|
| 212 |
+
|
| 213 |
+
- Fetching questions from the course API
|
| 214 |
+
- Running the agent on each question
|
| 215 |
+
- Submitting answers for scoring
|
| 216 |
+
- Viewing results on the leaderboard
|
| 217 |
+
|
| 218 |
+
## Benchmark Testing
|
| 219 |
+
|
| 220 |
+
The project includes a benchmark testing framework to evaluate the agent's performance:
|
| 221 |
+
|
| 222 |
+
```bash
|
| 223 |
+
# Run benchmark tests with default settings
|
| 224 |
+
python -m tests.benchmark --output benchmark_results.json
|
| 225 |
+
|
| 226 |
+
# Run benchmark tests with custom questions
|
| 227 |
+
python -m tests.benchmark --questions custom_questions.json --output benchmark_results.json
|
| 228 |
+
|
| 229 |
+
# Run benchmark tests with a specific number of questions
|
| 230 |
+
python -m tests.benchmark --max-questions 5 --output benchmark_results.json
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
The benchmark testing framework:
|
| 234 |
+
- Tests the agent against sample questions
|
| 235 |
+
- Measures performance metrics (accuracy, latency, resource usage)
|
| 236 |
+
- Generates detailed reports of benchmark results
|
| 237 |
+
- Allows comparison of different agent configurations
|
| 238 |
+
|
| 239 |
+
## Troubleshooting
|
| 240 |
+
|
| 241 |
+
### Common Issues
|
| 242 |
+
|
| 243 |
+
#### 1. langchain_openai Dependency Issues
|
| 244 |
+
|
| 245 |
+
If you encounter errors related to the `langchain_openai` package, such as:
|
| 246 |
+
- `ImportError: No module named 'langchain_openai'`
|
| 247 |
+
- `AttributeError: module 'langchain_openai' has no attribute 'ChatOpenAI'`
|
| 248 |
+
|
| 249 |
+
Try the following solutions:
|
| 250 |
+
- Ensure you have the latest version installed: `pip install --upgrade langchain_openai`
|
| 251 |
+
- Make sure you're using the correct import: `from langchain_openai import ChatOpenAI`
|
| 252 |
+
- Check for conflicts with older langchain versions: `pip uninstall langchain-openai` (note the hyphen)
|
| 253 |
+
|
| 254 |
+
#### 2. API Connection Issues
|
| 255 |
+
|
| 256 |
+
If you're having trouble connecting to external APIs:
|
| 257 |
+
- Verify that your API keys are correctly set in the environment variables
|
| 258 |
+
- Check that the API service is not experiencing downtime
|
| 259 |
+
- Ensure you have a stable internet connection
|
| 260 |
+
- Check for rate limiting or quota issues
|
| 261 |
+
|
| 262 |
+
#### 3. Supabase Connection Issues
|
| 263 |
+
|
| 264 |
+
If you're having trouble with Supabase:
|
| 265 |
+
- Verify that your Supabase URL and API key are correctly set
|
| 266 |
+
- Ensure that the required tables exist in your Supabase project
|
| 267 |
+
- Check that your API key has the necessary permissions
|
| 268 |
+
- Verify that your Supabase project is active
|
| 269 |
+
|
| 270 |
+
#### 4. Memory Issues
|
| 271 |
+
|
| 272 |
+
If you're experiencing issues with the agent's memory:
|
| 273 |
+
- Check that memory is enabled in the configuration
|
| 274 |
+
- Verify that the table names are correctly set
|
| 275 |
+
- Ensure that the TTL and cache size settings are appropriate
|
| 276 |
+
- Check for errors in the Supabase logs
|
| 277 |
+
|
| 278 |
+
## Documentation
|
| 279 |
+
|
| 280 |
+
Comprehensive documentation is available in the `docs/` directory:
|
| 281 |
+
|
| 282 |
+
- [Usage Examples](docs/examples.md): Examples of how to use the GAIA agent in different scenarios
|
| 283 |
+
- [Configuration Guide](docs/configuration.md): Detailed information about configuration options
|
| 284 |
+
- [Deployment Guide](docs/deployment.md): Instructions for deploying the agent in various environments
|
| 285 |
+
- [OpenAI Integration Testing](docs/openai_integration_testing.md): Guide for testing OpenAI integration with newer models
|
| 286 |
+
- [Connection Verification](docs/connection_verification.md): Guide for verifying connections to external services
|
| 287 |
+
- [Supabase Memory Integration](docs/supabase_memory_integration.md): Guide for setting up and using Supabase memory
|
| 288 |
+
- [All APIs Integration Testing](docs/all_apis_integration_testing.md): Guide for testing all API integrations together
|
| 289 |
+
- [Multi-Search Integration](docs/multi_search_integration.md): Guide for using multiple search providers
|
| 290 |
+
- [GAIA Memory Integration](docs/gaia_memory_integration.md): Guide for using memory in the GAIA agent
|
| 291 |
+
|
| 292 |
+
## License
|
| 293 |
+
|
| 294 |
+
This project is part of the Hugging Face Agents Course and follows its licensing terms.
|
SUPABASE_TABLES_README.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Supabase Tables for GAIA Agent
|
| 2 |
+
|
| 3 |
+
This document explains the issue with Supabase tables in the GAIA agent and how to fix it.
|
| 4 |
+
|
| 5 |
+
## Issue
|
| 6 |
+
|
| 7 |
+
The GAIA agent uses multiple Supabase tables for different types of memory:
|
| 8 |
+
|
| 9 |
+
1. `gaia_memory`: Main memory table for storing key-value pairs
|
| 10 |
+
2. `gaia_memory_working`: Working memory table for storing intermediate results during reasoning
|
| 11 |
+
3. `gaia_memory_conversations`: Conversation history table for storing message history
|
| 12 |
+
4. `gaia_memory_cache`: Cache table for storing frequently accessed results
|
| 13 |
+
|
| 14 |
+
However, only the main memory table (`gaia_memory`) and the test connection table are being populated, while the other tables remain empty. This is because the specialized memory classes (`WorkingMemory`, `ConversationMemory`, `ResultCache`) set their own table names but when calling methods on the base memory object, they were always using the base memory's table.
|
| 15 |
+
|
| 16 |
+
## Fix
|
| 17 |
+
|
| 18 |
+
We've created two fix scripts:
|
| 19 |
+
|
| 20 |
+
1. `memory/fix_supabase_tables.py`: A comprehensive fix that modifies all memory classes to use their respective tables
|
| 21 |
+
2. `memory/simplified_memory_fix.py`: A simplified fix that focuses only on the working memory table
|
| 22 |
+
|
| 23 |
+
The fix modifies the `SupabaseMemory` class to accept a `table_name` parameter in its methods, and updates the specialized memory classes to pass their table name when calling the base memory methods.
|
| 24 |
+
|
| 25 |
+
## How to Use the Fix
|
| 26 |
+
|
| 27 |
+
### Option 1: Run the GAIA agent with the fix applied
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
python run_gaia_with_fix.py --question "Your question here"
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
This script applies the fix, runs the GAIA agent with your question, and shows the content of all tables after the question is answered.
|
| 34 |
+
|
| 35 |
+
### Option 2: Apply the fix manually
|
| 36 |
+
|
| 37 |
+
```bash
|
| 38 |
+
# For all tables
|
| 39 |
+
python -m memory.fix_supabase_tables
|
| 40 |
+
|
| 41 |
+
# For working memory only
|
| 42 |
+
python -m memory.simplified_memory_fix
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
### Option 3: Run tests
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
# Simple test for working memory
|
| 49 |
+
python -m tests.test_supabase_tables_simple
|
| 50 |
+
|
| 51 |
+
# Comprehensive test for all tables
|
| 52 |
+
python -m tests.test_gaia_with_all_tables
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
## Table Descriptions
|
| 56 |
+
|
| 57 |
+
### gaia_memory
|
| 58 |
+
|
| 59 |
+
The main memory table for storing key-value pairs. This is the default table used by the `SupabaseMemory` class.
|
| 60 |
+
|
| 61 |
+
### gaia_memory_working
|
| 62 |
+
|
| 63 |
+
The working memory table for storing intermediate results during reasoning. This table is used by the `WorkingMemory` class to store temporary data during the reasoning process, such as:
|
| 64 |
+
|
| 65 |
+
- Parsed question
|
| 66 |
+
- Identified entities
|
| 67 |
+
- Intermediate reasoning steps
|
| 68 |
+
- Search results
|
| 69 |
+
- Final answer
|
| 70 |
+
|
| 71 |
+
### gaia_memory_conversations
|
| 72 |
+
|
| 73 |
+
The conversation history table for storing message history. This table is used by the `ConversationMemory` class to store the conversation history, including:
|
| 74 |
+
|
| 75 |
+
- User messages
|
| 76 |
+
- Assistant messages
|
| 77 |
+
- Timestamps
|
| 78 |
+
- Metadata
|
| 79 |
+
|
| 80 |
+
### gaia_memory_cache
|
| 81 |
+
|
| 82 |
+
The cache table for storing frequently accessed results. This table is used by the `ResultCache` class to store cached results, which can improve performance by avoiding redundant computations.
|
| 83 |
+
|
| 84 |
+
## Performance Benefits
|
| 85 |
+
|
| 86 |
+
Using the specialized tables provides several benefits:
|
| 87 |
+
|
| 88 |
+
1. **Improved organization**: Each type of memory has its own table, making it easier to manage and query.
|
| 89 |
+
2. **Better performance**: Smaller, specialized tables are faster to query than a single large table.
|
| 90 |
+
3. **Enhanced debugging**: It's easier to debug issues when each memory type has its own table.
|
| 91 |
+
4. **Reduced data conflicts**: Separate tables reduce the risk of key conflicts between different memory types.
|
| 92 |
+
|
| 93 |
+
## Implementation Details
|
| 94 |
+
|
| 95 |
+
The fix works by monkey-patching the following methods:
|
| 96 |
+
|
| 97 |
+
### SupabaseMemory
|
| 98 |
+
|
| 99 |
+
- `store`: Modified to accept a `table_name` parameter
|
| 100 |
+
- `retrieve`: Modified to accept a `table_name` parameter
|
| 101 |
+
- `delete`: Modified to accept a `table_name` parameter
|
| 102 |
+
- `list_keys`: Modified to accept a `table_name` parameter
|
| 103 |
+
|
| 104 |
+
### WorkingMemory
|
| 105 |
+
|
| 106 |
+
- `store_intermediate_result`: Modified to use the working memory table
|
| 107 |
+
- `get_intermediate_result`: Modified to use the working memory table
|
| 108 |
+
- `list_intermediate_results`: Modified to use the working memory table
|
| 109 |
+
- `clear`: Modified to use the working memory table
|
| 110 |
+
|
| 111 |
+
### ConversationMemory
|
| 112 |
+
|
| 113 |
+
- `add_message`: Modified to use the conversations table
|
| 114 |
+
- `get_messages`: Modified to use the conversations table
|
| 115 |
+
- `clear`: Modified to use the conversations table
|
| 116 |
+
|
| 117 |
+
### ResultCache
|
| 118 |
+
|
| 119 |
+
- `cache_result`: Modified to use the cache table
|
| 120 |
+
- `get_result`: Modified to use the cache table
|
| 121 |
+
- `invalidate`: Modified to use the cache table
|
| 122 |
+
- `clear`: Modified to use the cache table
|
SUPABASE_TEST_README.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Standalone Supabase Connection Test
|
| 2 |
+
|
| 3 |
+
This directory contains scripts for testing the Supabase connection without relying on any project modules.
|
| 4 |
+
|
| 5 |
+
## Main Script: `supabase_direct_test.py`
|
| 6 |
+
|
| 7 |
+
This script tests the connection to Supabase, verifies access to all required tables, and performs basic CRUD operations on the test_connection table.
|
| 8 |
+
|
| 9 |
+
### Prerequisites
|
| 10 |
+
|
| 11 |
+
- Python 3.6+
|
| 12 |
+
- Required packages:
|
| 13 |
+
- supabase
|
| 14 |
+
- python-dotenv
|
| 15 |
+
|
| 16 |
+
You can install the required packages with:
|
| 17 |
+
|
| 18 |
+
```bash
|
| 19 |
+
pip install supabase python-dotenv
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
### Usage
|
| 23 |
+
|
| 24 |
+
You can run the script in several ways:
|
| 25 |
+
|
| 26 |
+
1. Using environment variables:
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
# Set environment variables
|
| 30 |
+
export SUPABASE_URL=https://your-project-id.supabase.co
|
| 31 |
+
export SUPABASE_KEY=your-supabase-api-key
|
| 32 |
+
|
| 33 |
+
# Run the test
|
| 34 |
+
python supabase_direct_test.py
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
2. Using command-line arguments:
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
python supabase_direct_test.py --key your-supabase-api-key
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
3. Using a .env file:
|
| 44 |
+
|
| 45 |
+
Create a `.env` file in the same directory with the following content:
|
| 46 |
+
|
| 47 |
+
```
|
| 48 |
+
SUPABASE_URL=https://your-project-id.supabase.co
|
| 49 |
+
SUPABASE_KEY=your-supabase-api-key
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
Then run the script:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
python supabase_direct_test.py
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
### Options
|
| 59 |
+
|
| 60 |
+
- `--verbose`: Enable verbose logging
|
| 61 |
+
- `--url`: Specify the Supabase URL (overrides environment variable)
|
| 62 |
+
- `--key`: Specify the Supabase API key (overrides environment variable)
|
| 63 |
+
|
| 64 |
+
Example with verbose logging:
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
python supabase_direct_test.py --verbose --key your-supabase-api-key
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
## Helper Scripts
|
| 71 |
+
|
| 72 |
+
The repository also includes several helper scripts for troubleshooting:
|
| 73 |
+
|
| 74 |
+
- `check_supabase_env.py`: Checks if the required Supabase environment variables are set
|
| 75 |
+
- `supabase_import_test.py`: Tests importing the Supabase library
|
| 76 |
+
- `supabase_init_test.py`: Tests initializing the Supabase client
|
| 77 |
+
- `supabase_minimal_test.py`: Minimal test for Supabase connection
|
| 78 |
+
- `create_env_and_test.py`: Creates a .env file and tests the connection
|
| 79 |
+
|
| 80 |
+
## Tables Tested
|
| 81 |
+
|
| 82 |
+
The script verifies connection to the following tables:
|
| 83 |
+
|
| 84 |
+
1. `gaia_memory`: Main memory table
|
| 85 |
+
2. `gaia_memory_conversations`: Conversation history table
|
| 86 |
+
3. `gaia_memory_cache`: Cache table
|
| 87 |
+
4. `gaia_memory_working`: Working memory table
|
| 88 |
+
5. `test_connection`: Test table for connection verification
|
| 89 |
+
|
| 90 |
+
If any of these tables don't exist, you can create them by running the SQL statements in `supabase_tables.sql`.
|
| 91 |
+
|
| 92 |
+
## Troubleshooting
|
| 93 |
+
|
| 94 |
+
If you encounter issues:
|
| 95 |
+
|
| 96 |
+
1. Check that your Supabase API key is correct
|
| 97 |
+
2. Verify that the Supabase URL is correct
|
| 98 |
+
3. Ensure that the required tables exist in your Supabase project
|
| 99 |
+
4. Check network connectivity to Supabase
|
| 100 |
+
5. Run with the `--verbose` flag for more detailed error information
|
| 101 |
+
|
| 102 |
+
## Security Note
|
| 103 |
+
|
| 104 |
+
Never hardcode your Supabase API key in your scripts. Always use environment variables, .env files, or command-line arguments to provide the key securely.
|
agent/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Agent module for GAIA implementation.
|
| 3 |
+
Contains the core agent architecture and configuration.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from agent.agent import GAIAAgent
|
| 7 |
+
from agent.config import (
|
| 8 |
+
get_logging_config,
|
| 9 |
+
get_model_config,
|
| 10 |
+
get_tool_config,
|
| 11 |
+
get_memory_config,
|
| 12 |
+
get_agent_config
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
'GAIAAgent',
|
| 17 |
+
'get_logging_config',
|
| 18 |
+
'get_model_config',
|
| 19 |
+
'get_tool_config',
|
| 20 |
+
'get_memory_config',
|
| 21 |
+
'get_agent_config'
|
| 22 |
+
]
|
agent/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (635 Bytes). View file
|
|
|
agent/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (635 Bytes). View file
|
|
|
agent/__pycache__/agent.cpython-312.pyc
ADDED
|
Binary file (13.2 kB). View file
|
|
|
agent/__pycache__/agent.cpython-313.pyc
ADDED
|
Binary file (12.8 kB). View file
|
|
|
agent/__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (6.18 kB). View file
|
|
|
agent/__pycache__/config.cpython-313.pyc
ADDED
|
Binary file (6.09 kB). View file
|
|
|
agent/__pycache__/graph.cpython-312.pyc
ADDED
|
Binary file (16.8 kB). View file
|
|
|
agent/__pycache__/graph.cpython-313.pyc
ADDED
|
Binary file (16.8 kB). View file
|
|
|
agent/__pycache__/tool_registry.cpython-313.pyc
ADDED
|
Binary file (14.3 kB). View file
|
|
|
agent/agent.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Main agent implementation for the GAIA benchmark.
|
| 3 |
+
|
| 4 |
+
This module contains the GAIAAgent class which is responsible for:
|
| 5 |
+
- Processing questions from the GAIA benchmark
|
| 6 |
+
- Selecting and executing appropriate tools
|
| 7 |
+
- Formulating precise answers
|
| 8 |
+
- Handling errors and logging
|
| 9 |
+
|
| 10 |
+
The agent uses LangGraph for workflow management and Supabase for memory,
|
| 11 |
+
with configuration from the config module. It can be extended with
|
| 12 |
+
additional capabilities as needed.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import logging
|
| 16 |
+
import time
|
| 17 |
+
import traceback
|
| 18 |
+
import uuid
|
| 19 |
+
from typing import Dict, Any, Optional, List, Union, Tuple
|
| 20 |
+
|
| 21 |
+
from agent.config import (
|
| 22 |
+
get_logging_config,
|
| 23 |
+
get_model_config,
|
| 24 |
+
get_tool_config,
|
| 25 |
+
get_memory_config,
|
| 26 |
+
get_agent_config,
|
| 27 |
+
VERBOSE
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# Import LangGraph workflow
|
| 31 |
+
from agent.graph import run_agent_graph
|
| 32 |
+
|
| 33 |
+
from memory import SupabaseMemory, ConversationMemory, ResultCache, WorkingMemory
|
| 34 |
+
|
| 35 |
+
logging_config = get_logging_config()
|
| 36 |
+
logging.basicConfig(
|
| 37 |
+
level=logging_config["level"],
|
| 38 |
+
format=logging_config["format"],
|
| 39 |
+
filename=logging_config["filename"]
|
| 40 |
+
)
|
| 41 |
+
logger = logging.getLogger("gaia_agent")
|
| 42 |
+
|
| 43 |
+
class GAIAAgent:
|
| 44 |
+
"""
|
| 45 |
+
Agent for answering questions from the GAIA benchmark.
|
| 46 |
+
|
| 47 |
+
This agent processes questions, selects appropriate tools,
|
| 48 |
+
executes a reasoning process, and formulates precise answers.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __init__(self, config: Optional[Dict[str, Any]] = None):
|
| 52 |
+
"""
|
| 53 |
+
Initialize the GAIA agent with configuration.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
config (Optional[Dict[str, Any]]): Custom configuration dictionary.
|
| 57 |
+
If None, the default configuration from config.py is used.
|
| 58 |
+
"""
|
| 59 |
+
logger.info("Initializing GAIAAgent")
|
| 60 |
+
|
| 61 |
+
self.config = config or {
|
| 62 |
+
"model": get_model_config(),
|
| 63 |
+
"tools": get_tool_config(),
|
| 64 |
+
"memory": get_memory_config(),
|
| 65 |
+
"agent": get_agent_config()
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
if VERBOSE:
|
| 69 |
+
logger.setLevel(logging.DEBUG)
|
| 70 |
+
if not any(isinstance(h, logging.StreamHandler) for h in logger.handlers):
|
| 71 |
+
console_handler = logging.StreamHandler()
|
| 72 |
+
console_handler.setLevel(logging.DEBUG)
|
| 73 |
+
console_handler.setFormatter(logging.Formatter(logging_config["format"]))
|
| 74 |
+
logger.addHandler(console_handler)
|
| 75 |
+
|
| 76 |
+
self._initialize_memory()
|
| 77 |
+
|
| 78 |
+
self.reset_state()
|
| 79 |
+
|
| 80 |
+
logger.info("GAIAAgent initialized successfully")
|
| 81 |
+
|
| 82 |
+
def _initialize_memory(self) -> None:
|
| 83 |
+
"""Initialize memory components."""
|
| 84 |
+
|
| 85 |
+
try:
|
| 86 |
+
self.memory = SupabaseMemory(self.config["memory"])
|
| 87 |
+
|
| 88 |
+
self.session_id = str(uuid.uuid4())
|
| 89 |
+
|
| 90 |
+
self.conversation_memory = ConversationMemory(self.memory, self.session_id)
|
| 91 |
+
self.result_cache = ResultCache(self.memory)
|
| 92 |
+
self.working_memory = WorkingMemory(self.memory, self.session_id)
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
logger.error(f"Error initializing memory components: {str(e)}")
|
| 96 |
+
logger.warning("Continuing without persistent memory")
|
| 97 |
+
|
| 98 |
+
self.memory = None
|
| 99 |
+
self.conversation_memory = None
|
| 100 |
+
self.result_cache = None
|
| 101 |
+
self.working_memory = None
|
| 102 |
+
|
| 103 |
+
def reset_state(self) -> None:
|
| 104 |
+
"""Reset the agent's internal state."""
|
| 105 |
+
self.state = {
|
| 106 |
+
"current_question": None,
|
| 107 |
+
"tools_used": [],
|
| 108 |
+
"intermediate_results": [],
|
| 109 |
+
"start_time": None,
|
| 110 |
+
"end_time": None,
|
| 111 |
+
"error": None
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
def __call__(self, question: str) -> str:
|
| 115 |
+
"""
|
| 116 |
+
Process a question and return an answer.
|
| 117 |
+
|
| 118 |
+
This is the main entry point for the agent. It takes a question,
|
| 119 |
+
processes it, and returns a concise answer.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
question (str): The question to answer
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
str: The answer to the question
|
| 126 |
+
|
| 127 |
+
Raises:
|
| 128 |
+
Exception: If an error occurs during processing
|
| 129 |
+
"""
|
| 130 |
+
self.reset_state()
|
| 131 |
+
self.state["current_question"] = question
|
| 132 |
+
self.state["start_time"] = time.time()
|
| 133 |
+
|
| 134 |
+
logger.info(f"Processing question: {question[:100]}...")
|
| 135 |
+
|
| 136 |
+
try:
|
| 137 |
+
max_retries = self.config["agent"]["max_retries"]
|
| 138 |
+
retry_delay = self.config["agent"]["retry_delay"]
|
| 139 |
+
|
| 140 |
+
for attempt in range(max_retries):
|
| 141 |
+
try:
|
| 142 |
+
answer = self._process_question(question)
|
| 143 |
+
|
| 144 |
+
self.state["end_time"] = time.time()
|
| 145 |
+
processing_time = self.state["end_time"] - self.state["start_time"]
|
| 146 |
+
logger.info(f"Question processed in {processing_time:.2f} seconds. Answer: {answer[:100]}...")
|
| 147 |
+
|
| 148 |
+
return answer
|
| 149 |
+
|
| 150 |
+
except Exception as e:
|
| 151 |
+
if attempt < max_retries - 1:
|
| 152 |
+
logger.warning(f"Attempt {attempt + 1}/{max_retries} failed: {str(e)}. Retrying in {retry_delay} seconds...")
|
| 153 |
+
time.sleep(retry_delay)
|
| 154 |
+
else:
|
| 155 |
+
raise
|
| 156 |
+
|
| 157 |
+
except Exception as e:
|
| 158 |
+
self.state["error"] = str(e)
|
| 159 |
+
self.state["end_time"] = time.time()
|
| 160 |
+
processing_time = self.state["end_time"] - self.state["start_time"]
|
| 161 |
+
|
| 162 |
+
logger.error(f"Error processing question after {processing_time:.2f} seconds: {str(e)}")
|
| 163 |
+
logger.error(traceback.format_exc())
|
| 164 |
+
|
| 165 |
+
if self.config["agent"].get("return_error_message", False):
|
| 166 |
+
return f"Error: {str(e)}"
|
| 167 |
+
else:
|
| 168 |
+
raise
|
| 169 |
+
|
| 170 |
+
def _process_question(self, question: str) -> str:
|
| 171 |
+
"""
|
| 172 |
+
Internal method to process a question and generate an answer.
|
| 173 |
+
|
| 174 |
+
This method implements the core logic of the agent using LangGraph:
|
| 175 |
+
1. Analyze the question
|
| 176 |
+
2. Plan the approach
|
| 177 |
+
3. Execute tools
|
| 178 |
+
4. Formulate the answer
|
| 179 |
+
|
| 180 |
+
Args:
|
| 181 |
+
question (str): The question to process
|
| 182 |
+
|
| 183 |
+
Returns:
|
| 184 |
+
str: The answer to the question
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
if self.result_cache:
|
| 188 |
+
import hashlib
|
| 189 |
+
cache_key = f"answer:{hashlib.md5(question.encode()).hexdigest()}"
|
| 190 |
+
|
| 191 |
+
cached_answer = self.result_cache.get_result(cache_key)
|
| 192 |
+
if cached_answer:
|
| 193 |
+
logger.info(f"Using cached answer for question: {question[:30]}...")
|
| 194 |
+
return cached_answer
|
| 195 |
+
|
| 196 |
+
graph_config = {
|
| 197 |
+
"recursion_limit": self.config["agent"].get("max_iterations", 10),
|
| 198 |
+
"timeout": self.config["agent"].get("timeout", 300)
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
try:
|
| 202 |
+
result = run_agent_graph(question, graph_config)
|
| 203 |
+
|
| 204 |
+
if result.get("answer"):
|
| 205 |
+
answer = result["answer"]
|
| 206 |
+
elif result.get("error"):
|
| 207 |
+
raise Exception(result["error"])
|
| 208 |
+
else:
|
| 209 |
+
answer = f"Unable to answer: {question[:30]}..."
|
| 210 |
+
|
| 211 |
+
if self.result_cache:
|
| 212 |
+
self.result_cache.cache_result(cache_key, answer)
|
| 213 |
+
|
| 214 |
+
if self.working_memory:
|
| 215 |
+
if result.get("analysis"):
|
| 216 |
+
self.working_memory.store_intermediate_result(
|
| 217 |
+
"analysis", result["analysis"]
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
if result.get("plan"):
|
| 221 |
+
self.working_memory.store_intermediate_result(
|
| 222 |
+
"plan", result["plan"]
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
if result.get("tool_results"):
|
| 226 |
+
self.working_memory.store_intermediate_result(
|
| 227 |
+
"tool_results", result["tool_results"]
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
if self.conversation_memory:
|
| 231 |
+
self.conversation_memory.add_message("user", question)
|
| 232 |
+
self.conversation_memory.add_message("assistant", answer)
|
| 233 |
+
|
| 234 |
+
return answer
|
| 235 |
+
except Exception as e:
|
| 236 |
+
logger.error(f"Error running LangGraph workflow: {str(e)}")
|
| 237 |
+
raise
|
| 238 |
+
|
| 239 |
+
def get_memory_snapshot(self) -> Dict[str, Any]:
|
| 240 |
+
"""
|
| 241 |
+
Get a snapshot of the agent's memory.
|
| 242 |
+
|
| 243 |
+
This method returns a dictionary containing the current state of the
|
| 244 |
+
agent's memory, including conversation history, cached results, and
|
| 245 |
+
intermediate results.
|
| 246 |
+
|
| 247 |
+
Returns:
|
| 248 |
+
Dict[str, Any]: Memory snapshot
|
| 249 |
+
"""
|
| 250 |
+
snapshot = {
|
| 251 |
+
"conversation": [],
|
| 252 |
+
"cached_results": {},
|
| 253 |
+
"intermediate_results": {}
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
if self.conversation_memory:
|
| 257 |
+
snapshot["conversation"] = self.conversation_memory.get_messages()
|
| 258 |
+
|
| 259 |
+
if self.result_cache and self.memory:
|
| 260 |
+
cache_keys = self.memory.list_keys("cache:")
|
| 261 |
+
for key in cache_keys:
|
| 262 |
+
original_key = key[6:] # Remove "cache:" prefix
|
| 263 |
+
|
| 264 |
+
result = self.memory.retrieve(key)
|
| 265 |
+
|
| 266 |
+
snapshot["cached_results"][original_key] = result
|
| 267 |
+
|
| 268 |
+
if self.working_memory:
|
| 269 |
+
snapshot["intermediate_results"] = self.working_memory.list_intermediate_results()
|
| 270 |
+
|
| 271 |
+
return snapshot
|
| 272 |
+
|
| 273 |
+
def clear_memory(self) -> None:
|
| 274 |
+
"""
|
| 275 |
+
Clear the agent's memory.
|
| 276 |
+
|
| 277 |
+
This method clears all memory components, including conversation history,
|
| 278 |
+
cached results, and intermediate results.
|
| 279 |
+
"""
|
| 280 |
+
logger.info("Clearing agent memory")
|
| 281 |
+
|
| 282 |
+
if self.conversation_memory:
|
| 283 |
+
self.conversation_memory.clear()
|
| 284 |
+
|
| 285 |
+
if self.result_cache:
|
| 286 |
+
self.result_cache.clear()
|
| 287 |
+
|
| 288 |
+
if self.working_memory:
|
| 289 |
+
self.working_memory.clear()
|
| 290 |
+
|
| 291 |
+
logger.info("Agent memory cleared")
|
agent/config.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Configuration module for the GAIA agent.
|
| 3 |
+
|
| 4 |
+
This module centralizes all configuration settings for the agent, including:
|
| 5 |
+
- API endpoints
|
| 6 |
+
- Model selection
|
| 7 |
+
- Tool parameters
|
| 8 |
+
- Memory settings
|
| 9 |
+
- Logging configuration
|
| 10 |
+
- Web browsing settings
|
| 11 |
+
- Multimodal processing parameters
|
| 12 |
+
|
| 13 |
+
It uses python-dotenv to load environment variables for sensitive credentials.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import logging
|
| 18 |
+
from typing import Dict, Any, Optional, List, Union, Tuple
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
from dotenv import load_dotenv
|
| 22 |
+
load_dotenv(verbose=False)
|
| 23 |
+
except ImportError:
|
| 24 |
+
def load_dotenv(*args, **kwargs):
|
| 25 |
+
|
| 26 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
|
| 27 |
+
SERPER_API_KEY = os.getenv("SERPER_API_KEY", "")
|
| 28 |
+
PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY", "")
|
| 29 |
+
SUPABASE_KEY = os.getenv("SUPABASE_KEY", "")
|
| 30 |
+
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 31 |
+
|
| 32 |
+
# Supabase Configuration (partially hardcoded)
|
| 33 |
+
SUPABASE_URL = "https://tjamxhvvtnypbadvrkjq.supabase.co"
|
| 34 |
+
SUPABASE_PROJECT_ID = "tjamxhvvtnypbadvrkjq"
|
| 35 |
+
SUPABASE_PROJECT_NAME = "HF_GAIA_Assessment_AGT"
|
| 36 |
+
|
| 37 |
+
OPENAI_API_BASE = "https://api.openai.com/v1"
|
| 38 |
+
SERPER_API_URL = "https://google.serper.dev/search"
|
| 39 |
+
PERPLEXITY_API_URL = "https://api.perplexity.ai"
|
| 40 |
+
HUGGINGFACE_API_URL = "https://api-inference.huggingface.co/models"
|
| 41 |
+
|
| 42 |
+
# Model Configuration (hardcoded with updated models)
|
| 43 |
+
DEFAULT_MODEL = "gpt-4o" # Updated from gpt-4-turbo
|
| 44 |
+
EMBEDDING_MODEL = "text-embedding-3-large" # Updated from text-embedding-ada-002
|
| 45 |
+
FALLBACK_MODEL = "gpt-3.5-turbo"
|
| 46 |
+
VISION_MODEL = "gpt-4o" # Updated from gpt-4-vision-preview
|
| 47 |
+
REASONING_MODEL = "gpt-4o" # Updated from gpt-4-turbo
|
| 48 |
+
MODEL_TEMPERATURE = 0.1
|
| 49 |
+
MODEL_MAX_TOKENS = 4096
|
| 50 |
+
|
| 51 |
+
# Tool Parameters (hardcoded)
|
| 52 |
+
WEB_SEARCH_RESULT_COUNT = 5
|
| 53 |
+
WEB_SEARCH_TIMEOUT = 10
|
| 54 |
+
ARXIV_MAX_RESULTS = 3
|
| 55 |
+
DUCKDUCKGO_TIMEOUT = 10
|
| 56 |
+
DUCKDUCKGO_MAX_RESULTS = 5
|
| 57 |
+
PERPLEXITY_TIMEOUT = 30
|
| 58 |
+
PERPLEXITY_MODEL = "sonar-reasoning"
|
| 59 |
+
WEB_SCRAPING_TIMEOUT = 15
|
| 60 |
+
WEB_SCRAPING_MAX_LINKS = 3
|
| 61 |
+
WEB_SCRAPING_MAX_CONTENT_LENGTH = 10000
|
| 62 |
+
|
| 63 |
+
# Memory Settings (hardcoded)
|
| 64 |
+
MEMORY_ENABLED = True
|
| 65 |
+
MEMORY_TABLE_NAME = "gaia_memory"
|
| 66 |
+
MEMORY_TTL = 86400 # 24 hours in seconds
|
| 67 |
+
MEMORY_CACHE_SIZE = 100
|
| 68 |
+
MEMORY_SIMILARITY_THRESHOLD = 0.85
|
| 69 |
+
MEMORY_MAX_ENTRIES = 1000
|
| 70 |
+
|
| 71 |
+
# Agent Settings (hardcoded)
|
| 72 |
+
MAX_ITERATIONS = 10
|
| 73 |
+
VERBOSE = False
|
| 74 |
+
TIMEOUT = 300 # 5 minutes in seconds
|
| 75 |
+
MAX_RETRIES = 3
|
| 76 |
+
RETRY_DELAY = 2 # seconds
|
| 77 |
+
PARALLEL_TOOL_EXECUTION = False
|
| 78 |
+
|
| 79 |
+
# Logging Configuration (hardcoded)
|
| 80 |
+
LOG_LEVEL = "INFO"
|
| 81 |
+
LOG_FILE = "gaia_agent.log"
|
| 82 |
+
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
| 83 |
+
|
| 84 |
+
# Multimodal Settings (hardcoded)
|
| 85 |
+
IMAGE_MAX_SIZE = 1024 # pixels
|
| 86 |
+
IMAGE_FORMAT = "JPEG"
|
| 87 |
+
VISION_DETAIL_LEVEL = "high" # low, medium, high
|
| 88 |
+
|
| 89 |
+
# Web Browsing Settings (hardcoded)
|
| 90 |
+
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
|
| 91 |
+
BROWSER_TIMEOUT = 30
|
| 92 |
+
BROWSER_HEADLESS = True
|
| 93 |
+
BROWSER_IMAGES_ENABLED = True
|
| 94 |
+
|
| 95 |
+
def get_logging_config() -> Dict[str, Any]:
|
| 96 |
+
"""
|
| 97 |
+
Returns a dictionary with logging configuration.
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
Dict[str, Any]: Logging configuration dictionary
|
| 101 |
+
"""
|
| 102 |
+
return {
|
| 103 |
+
"level": getattr(logging, LOG_LEVEL.upper(), logging.INFO),
|
| 104 |
+
"format": LOG_FORMAT,
|
| 105 |
+
"filename": LOG_FILE if LOG_FILE else None,
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
def get_model_config() -> Dict[str, Any]:
|
| 109 |
+
"""
|
| 110 |
+
Returns a dictionary with model configuration.
|
| 111 |
+
|
| 112 |
+
Returns:
|
| 113 |
+
Dict[str, Any]: Model configuration dictionary
|
| 114 |
+
"""
|
| 115 |
+
return {
|
| 116 |
+
"default_model": DEFAULT_MODEL,
|
| 117 |
+
"embedding_model": EMBEDDING_MODEL,
|
| 118 |
+
"fallback_model": FALLBACK_MODEL,
|
| 119 |
+
"vision_model": VISION_MODEL,
|
| 120 |
+
"reasoning_model": REASONING_MODEL,
|
| 121 |
+
"temperature": MODEL_TEMPERATURE,
|
| 122 |
+
"max_tokens": MODEL_MAX_TOKENS,
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
def get_tool_config() -> Dict[str, Dict[str, Any]]:
|
| 126 |
+
"""
|
| 127 |
+
Returns a dictionary with tool configurations.
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
Dict[str, Dict[str, Any]]: Tool configuration dictionary
|
| 131 |
+
"""
|
| 132 |
+
return {
|
| 133 |
+
"web_search": {
|
| 134 |
+
"result_count": WEB_SEARCH_RESULT_COUNT,
|
| 135 |
+
"timeout": WEB_SEARCH_TIMEOUT,
|
| 136 |
+
},
|
| 137 |
+
"arxiv": {
|
| 138 |
+
"max_results": ARXIV_MAX_RESULTS,
|
| 139 |
+
},
|
| 140 |
+
"duckduckgo": {
|
| 141 |
+
"timeout": DUCKDUCKGO_TIMEOUT,
|
| 142 |
+
"max_results": DUCKDUCKGO_MAX_RESULTS,
|
| 143 |
+
},
|
| 144 |
+
"perplexity": {
|
| 145 |
+
"timeout": PERPLEXITY_TIMEOUT,
|
| 146 |
+
"model": PERPLEXITY_MODEL,
|
| 147 |
+
"api_url": PERPLEXITY_API_URL,
|
| 148 |
+
},
|
| 149 |
+
"web_scraping": {
|
| 150 |
+
"timeout": WEB_SCRAPING_TIMEOUT,
|
| 151 |
+
"max_links": WEB_SCRAPING_MAX_LINKS,
|
| 152 |
+
"max_content_length": WEB_SCRAPING_MAX_CONTENT_LENGTH,
|
| 153 |
+
},
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
def get_memory_config() -> Dict[str, Any]:
|
| 157 |
+
"""
|
| 158 |
+
Returns a dictionary with memory configuration.
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
Dict[str, Any]: Memory configuration dictionary
|
| 162 |
+
"""
|
| 163 |
+
return {
|
| 164 |
+
"enabled": MEMORY_ENABLED,
|
| 165 |
+
"table_name": MEMORY_TABLE_NAME,
|
| 166 |
+
"ttl": MEMORY_TTL,
|
| 167 |
+
"cache_size": MEMORY_CACHE_SIZE,
|
| 168 |
+
"similarity_threshold": MEMORY_SIMILARITY_THRESHOLD,
|
| 169 |
+
"max_entries": MEMORY_MAX_ENTRIES,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
def get_agent_config() -> Dict[str, Any]:
|
| 173 |
+
"""
|
| 174 |
+
Returns a dictionary with agent configuration.
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
Dict[str, Any]: Agent configuration dictionary
|
| 178 |
+
"""
|
| 179 |
+
return {
|
| 180 |
+
"max_iterations": MAX_ITERATIONS,
|
| 181 |
+
"verbose": VERBOSE,
|
| 182 |
+
"timeout": TIMEOUT,
|
| 183 |
+
"max_retries": MAX_RETRIES,
|
| 184 |
+
"retry_delay": RETRY_DELAY,
|
| 185 |
+
"parallel_tool_execution": PARALLEL_TOOL_EXECUTION,
|
| 186 |
+
}
|
agent/graph.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LangGraph workflow definition for the GAIA agent.
|
| 3 |
+
|
| 4 |
+
This module defines the workflow graph for the GAIA agent using LangGraph.
|
| 5 |
+
It implements nodes for question analysis, planning, tool selection,
|
| 6 |
+
tool execution, and answer formulation, as well as the edges between them.
|
| 7 |
+
|
| 8 |
+
The graph is designed to be integrated with the GAIAAgent class and can be
|
| 9 |
+
extended with additional nodes and edges as needed.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import logging
|
| 13 |
+
from typing import Dict, Any, List, Tuple, Optional, Annotated, TypedDict, Literal, Union, cast
|
| 14 |
+
|
| 15 |
+
from langchain.prompts import PromptTemplate
|
| 16 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
| 17 |
+
from langchain_core.runnables import RunnableConfig
|
| 18 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 19 |
+
from langchain_openai import ChatOpenAI
|
| 20 |
+
|
| 21 |
+
from langgraph.graph import StateGraph, END
|
| 22 |
+
from langgraph.prebuilt import ToolNode
|
| 23 |
+
|
| 24 |
+
from agent.config import get_model_config, get_agent_config, VERBOSE
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger("gaia_agent.graph")
|
| 27 |
+
|
| 28 |
+
class QuestionAnalysis(TypedDict):
|
| 29 |
+
"""Type for question analysis results."""
|
| 30 |
+
question_type: str
|
| 31 |
+
required_tools: List[str]
|
| 32 |
+
information_sources: List[str]
|
| 33 |
+
complexity: str
|
| 34 |
+
|
| 35 |
+
class PlanStep(TypedDict):
|
| 36 |
+
"""Type for a single step in the plan."""
|
| 37 |
+
step_number: int
|
| 38 |
+
description: str
|
| 39 |
+
tool: Optional[str]
|
| 40 |
+
tool_input: Optional[Dict[str, Any]]
|
| 41 |
+
|
| 42 |
+
class ToolResult(TypedDict):
|
| 43 |
+
"""Type for tool execution results."""
|
| 44 |
+
tool_name: str
|
| 45 |
+
success: bool
|
| 46 |
+
result: Any
|
| 47 |
+
error: Optional[str]
|
| 48 |
+
|
| 49 |
+
class AgentState(TypedDict):
|
| 50 |
+
"""Type for the agent state."""
|
| 51 |
+
question: str
|
| 52 |
+
analysis: Optional[QuestionAnalysis]
|
| 53 |
+
plan: Optional[List[PlanStep]]
|
| 54 |
+
current_step: int
|
| 55 |
+
tools_to_use: Optional[List[str]]
|
| 56 |
+
tool_results: List[ToolResult]
|
| 57 |
+
intermediate_thoughts: List[str]
|
| 58 |
+
answer: Optional[str]
|
| 59 |
+
error: Optional[str]
|
| 60 |
+
|
| 61 |
+
def analyze_question(state: AgentState) -> AgentState:
|
| 62 |
+
"""
|
| 63 |
+
Analyze the question to determine its requirements.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
state: The current agent state
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
Updated agent state with question analysis
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
model_config = get_model_config()
|
| 73 |
+
|
| 74 |
+
analysis_prompt = PromptTemplate.from_template(
|
| 75 |
+
"""You are an expert question analyzer for the GAIA benchmark.
|
| 76 |
+
|
| 77 |
+
Your task is to analyze the following question and determine:
|
| 78 |
+
1. The question type (factual, mathematical, reasoning, etc.)
|
| 79 |
+
2. The tools required to answer it (web_search, calculator, reasoning, etc.)
|
| 80 |
+
3. The information sources needed (web, knowledge base, computation, etc.)
|
| 81 |
+
4. The complexity level (simple, medium, complex)
|
| 82 |
+
|
| 83 |
+
Question: {question}
|
| 84 |
+
|
| 85 |
+
Provide your analysis in the following JSON format:
|
| 86 |
+
{{
|
| 87 |
+
"question_type": "type of question",
|
| 88 |
+
"required_tools": ["tool1", "tool2", ...],
|
| 89 |
+
"information_sources": ["source1", "source2", ...],
|
| 90 |
+
"complexity": "complexity level"
|
| 91 |
+
}}
|
| 92 |
+
|
| 93 |
+
Analysis:"""
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
model = ChatOpenAI(
|
| 97 |
+
model=model_config["reasoning_model"],
|
| 98 |
+
temperature=model_config["temperature"],
|
| 99 |
+
max_tokens=model_config["max_tokens"]
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
chain = analysis_prompt | model | StrOutputParser()
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
analysis_str = chain.invoke({"question": state["question"]})
|
| 106 |
+
|
| 107 |
+
import json
|
| 108 |
+
analysis = json.loads(analysis_str)
|
| 109 |
+
|
| 110 |
+
new_state = state.copy()
|
| 111 |
+
new_state["analysis"] = analysis
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
return new_state
|
| 115 |
+
except Exception as e:
|
| 116 |
+
logger.error(f"Error analyzing question: {str(e)}")
|
| 117 |
+
|
| 118 |
+
new_state = state.copy()
|
| 119 |
+
new_state["error"] = f"Error analyzing question: {str(e)}"
|
| 120 |
+
|
| 121 |
+
return new_state
|
| 122 |
+
|
| 123 |
+
def create_plan(state: AgentState) -> AgentState:
|
| 124 |
+
"""
|
| 125 |
+
Create a plan to answer the question based on the analysis.
|
| 126 |
+
|
| 127 |
+
Args:
|
| 128 |
+
state: The current agent state
|
| 129 |
+
|
| 130 |
+
Returns:
|
| 131 |
+
Updated agent state with plan
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
if state.get("error"):
|
| 135 |
+
return state
|
| 136 |
+
|
| 137 |
+
model_config = get_model_config()
|
| 138 |
+
|
| 139 |
+
planning_prompt = PromptTemplate.from_template(
|
| 140 |
+
"""You are an expert planner for the GAIA benchmark.
|
| 141 |
+
|
| 142 |
+
Your task is to create a step-by-step plan to answer the following question:
|
| 143 |
+
|
| 144 |
+
Question: {question}
|
| 145 |
+
|
| 146 |
+
Question Analysis:
|
| 147 |
+
{analysis}
|
| 148 |
+
|
| 149 |
+
Create a detailed plan with the following steps:
|
| 150 |
+
1. Break down the question into logical steps
|
| 151 |
+
2. For each step, specify which tool to use (if any)
|
| 152 |
+
3. Specify the inputs for each tool
|
| 153 |
+
4. Describe how to combine the results to formulate the final answer
|
| 154 |
+
|
| 155 |
+
Provide your plan in the following JSON format:
|
| 156 |
+
[
|
| 157 |
+
{{
|
| 158 |
+
"step_number": 1,
|
| 159 |
+
"description": "description of step",
|
| 160 |
+
"tool": "tool_name or null if no tool needed",
|
| 161 |
+
"tool_input": {{ "param1": "value1", ... }} or null if no tool needed
|
| 162 |
+
}},
|
| 163 |
+
...
|
| 164 |
+
]
|
| 165 |
+
|
| 166 |
+
Plan:"""
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
model = ChatOpenAI(
|
| 170 |
+
model=model_config["reasoning_model"],
|
| 171 |
+
temperature=model_config["temperature"],
|
| 172 |
+
max_tokens=model_config["max_tokens"]
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
chain = planning_prompt | model | StrOutputParser()
|
| 176 |
+
|
| 177 |
+
try:
|
| 178 |
+
plan_str = chain.invoke({
|
| 179 |
+
"question": state["question"],
|
| 180 |
+
"analysis": state["analysis"]
|
| 181 |
+
})
|
| 182 |
+
|
| 183 |
+
import json
|
| 184 |
+
plan = json.loads(plan_str)
|
| 185 |
+
|
| 186 |
+
new_state = state.copy()
|
| 187 |
+
new_state["plan"] = plan
|
| 188 |
+
new_state["current_step"] = 0
|
| 189 |
+
|
| 190 |
+
tools_to_use = []
|
| 191 |
+
for step in plan:
|
| 192 |
+
if step.get("tool"):
|
| 193 |
+
tools_to_use.append(step["tool"])
|
| 194 |
+
|
| 195 |
+
new_state["tools_to_use"] = list(set(tools_to_use)) # Remove duplicates
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
return new_state
|
| 199 |
+
except Exception as e:
|
| 200 |
+
logger.error(f"Error creating plan: {str(e)}")
|
| 201 |
+
|
| 202 |
+
new_state = state.copy()
|
| 203 |
+
new_state["error"] = f"Error creating plan: {str(e)}"
|
| 204 |
+
|
| 205 |
+
return new_state
|
| 206 |
+
|
| 207 |
+
def select_tool(state: AgentState) -> Dict[str, Any]:
|
| 208 |
+
"""
|
| 209 |
+
Select the next tool to execute based on the plan.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
state: The current agent state
|
| 213 |
+
|
| 214 |
+
Returns:
|
| 215 |
+
Dictionary with the selected tool and its input
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
if state.get("error"):
|
| 219 |
+
return {"next": END}
|
| 220 |
+
|
| 221 |
+
if state["current_step"] >= len(state["plan"]):
|
| 222 |
+
return {"next": "formulate_answer"}
|
| 223 |
+
|
| 224 |
+
current_step = state["plan"][state["current_step"]]
|
| 225 |
+
|
| 226 |
+
if not current_step.get("tool"):
|
| 227 |
+
new_state = state.copy()
|
| 228 |
+
new_state["current_step"] += 1
|
| 229 |
+
|
| 230 |
+
thought = f"Step {current_step['step_number']}: {current_step['description']} - No tool needed, moving to next step."
|
| 231 |
+
new_state["intermediate_thoughts"] = state.get("intermediate_thoughts", []) + [thought]
|
| 232 |
+
|
| 233 |
+
return {"next": "select_tool", "state": new_state}
|
| 234 |
+
|
| 235 |
+
return {"next": "execute_tool"}
|
| 236 |
+
|
| 237 |
+
def execute_tool(state: AgentState) -> AgentState:
|
| 238 |
+
"""
|
| 239 |
+
Execute the selected tool based on the current plan step.
|
| 240 |
+
|
| 241 |
+
Args:
|
| 242 |
+
state: The current agent state
|
| 243 |
+
|
| 244 |
+
Returns:
|
| 245 |
+
Updated agent state with tool execution results
|
| 246 |
+
"""
|
| 247 |
+
if state.get("error"):
|
| 248 |
+
return state
|
| 249 |
+
|
| 250 |
+
current_step = state["plan"][state["current_step"]]
|
| 251 |
+
tool_name = current_step.get("tool")
|
| 252 |
+
tool_input = current_step.get("tool_input", {})
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
try:
|
| 256 |
+
result = f"Simulated result for {tool_name} with input {tool_input}"
|
| 257 |
+
|
| 258 |
+
tool_result = {
|
| 259 |
+
"tool_name": tool_name,
|
| 260 |
+
"success": True,
|
| 261 |
+
"result": result,
|
| 262 |
+
"error": None
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
new_state = state.copy()
|
| 266 |
+
new_state["tool_results"] = state.get("tool_results", []) + [tool_result]
|
| 267 |
+
new_state["current_step"] += 1
|
| 268 |
+
|
| 269 |
+
thought = f"Step {current_step['step_number']}: {current_step['description']} - Executed {tool_name} and got result: {result}"
|
| 270 |
+
new_state["intermediate_thoughts"] = state.get("intermediate_thoughts", []) + [thought]
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
return new_state
|
| 274 |
+
except Exception as e:
|
| 275 |
+
logger.error(f"Error executing tool {tool_name}: {str(e)}")
|
| 276 |
+
|
| 277 |
+
tool_result = {
|
| 278 |
+
"tool_name": tool_name,
|
| 279 |
+
"success": False,
|
| 280 |
+
"result": None,
|
| 281 |
+
"error": str(e)
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
new_state = state.copy()
|
| 285 |
+
new_state["tool_results"] = state.get("tool_results", []) + [tool_result]
|
| 286 |
+
new_state["current_step"] += 1
|
| 287 |
+
|
| 288 |
+
thought = f"Step {current_step['step_number']}: {current_step['description']} - Failed to execute {tool_name}: {str(e)}"
|
| 289 |
+
new_state["intermediate_thoughts"] = state.get("intermediate_thoughts", []) + [thought]
|
| 290 |
+
|
| 291 |
+
return new_state
|
| 292 |
+
|
| 293 |
+
def formulate_answer(state: AgentState) -> AgentState:
|
| 294 |
+
"""
|
| 295 |
+
Formulate the final answer based on tool results.
|
| 296 |
+
|
| 297 |
+
Args:
|
| 298 |
+
state: The current agent state
|
| 299 |
+
|
| 300 |
+
Returns:
|
| 301 |
+
Updated agent state with answer
|
| 302 |
+
"""
|
| 303 |
+
|
| 304 |
+
if state.get("error"):
|
| 305 |
+
return state
|
| 306 |
+
|
| 307 |
+
model_config = get_model_config()
|
| 308 |
+
|
| 309 |
+
answer_prompt = PromptTemplate.from_template(
|
| 310 |
+
"""You are an expert answer formulator for the GAIA benchmark.
|
| 311 |
+
|
| 312 |
+
Your task is to formulate a precise, concise answer to the following question based on the tool results:
|
| 313 |
+
|
| 314 |
+
Question: {question}
|
| 315 |
+
|
| 316 |
+
Question Analysis:
|
| 317 |
+
{analysis}
|
| 318 |
+
|
| 319 |
+
Plan:
|
| 320 |
+
{plan}
|
| 321 |
+
|
| 322 |
+
Tool Results:
|
| 323 |
+
{tool_results}
|
| 324 |
+
|
| 325 |
+
Intermediate Thoughts:
|
| 326 |
+
{thoughts}
|
| 327 |
+
|
| 328 |
+
Remember, GAIA benchmark answers should be very concise - either a number, a few words, or a comma-separated list.
|
| 329 |
+
Do not provide explanations or additional context in your answer.
|
| 330 |
+
|
| 331 |
+
Concise Answer:"""
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
model = ChatOpenAI(
|
| 335 |
+
model=model_config["reasoning_model"],
|
| 336 |
+
temperature=model_config["temperature"],
|
| 337 |
+
max_tokens=model_config["max_tokens"]
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
chain = answer_prompt | model | StrOutputParser()
|
| 341 |
+
|
| 342 |
+
try:
|
| 343 |
+
answer = chain.invoke({
|
| 344 |
+
"question": state["question"],
|
| 345 |
+
"analysis": state["analysis"],
|
| 346 |
+
"plan": state["plan"],
|
| 347 |
+
"tool_results": state["tool_results"],
|
| 348 |
+
"thoughts": state.get("intermediate_thoughts", [])
|
| 349 |
+
})
|
| 350 |
+
|
| 351 |
+
new_state = state.copy()
|
| 352 |
+
new_state["answer"] = answer.strip()
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
return new_state
|
| 356 |
+
except Exception as e:
|
| 357 |
+
logger.error(f"Error formulating answer: {str(e)}")
|
| 358 |
+
|
| 359 |
+
new_state = state.copy()
|
| 360 |
+
new_state["error"] = f"Error formulating answer: {str(e)}"
|
| 361 |
+
|
| 362 |
+
return new_state
|
| 363 |
+
|
| 364 |
+
def should_retry(state: AgentState) -> Dict[str, Any]:
|
| 365 |
+
"""
|
| 366 |
+
Determine if the agent should retry the workflow based on errors or incomplete results.
|
| 367 |
+
|
| 368 |
+
Args:
|
| 369 |
+
state: The current agent state
|
| 370 |
+
|
| 371 |
+
Returns:
|
| 372 |
+
Dictionary indicating the next node
|
| 373 |
+
"""
|
| 374 |
+
if state.get("error"):
|
| 375 |
+
agent_config = get_agent_config()
|
| 376 |
+
|
| 377 |
+
logger.error(f"Workflow ended with error: {state['error']}")
|
| 378 |
+
return {"next": END}
|
| 379 |
+
|
| 380 |
+
if state.get("answer"):
|
| 381 |
+
return {"next": END}
|
| 382 |
+
|
| 383 |
+
return {"next": "analyze_question"}
|
| 384 |
+
|
| 385 |
+
def create_agent_graph() -> Tuple[StateGraph, Dict[str, Any]]:
|
| 386 |
+
"""
|
| 387 |
+
Create the agent workflow graph.
|
| 388 |
+
|
| 389 |
+
Returns:
|
| 390 |
+
Tuple containing the StateGraph and the initial state
|
| 391 |
+
"""
|
| 392 |
+
workflow = StateGraph(AgentState)
|
| 393 |
+
|
| 394 |
+
workflow.add_node("analyze_question", analyze_question)
|
| 395 |
+
workflow.add_node("create_plan", create_plan)
|
| 396 |
+
workflow.add_node("select_tool", select_tool)
|
| 397 |
+
workflow.add_node("execute_tool", execute_tool)
|
| 398 |
+
workflow.add_node("formulate_answer", formulate_answer)
|
| 399 |
+
|
| 400 |
+
workflow.add_edge("analyze_question", "create_plan")
|
| 401 |
+
workflow.add_edge("create_plan", "select_tool")
|
| 402 |
+
workflow.add_conditional_edges(
|
| 403 |
+
"select_tool",
|
| 404 |
+
should_retry,
|
| 405 |
+
{
|
| 406 |
+
"execute_tool": "execute_tool",
|
| 407 |
+
"formulate_answer": "formulate_answer",
|
| 408 |
+
END: END
|
| 409 |
+
}
|
| 410 |
+
)
|
| 411 |
+
workflow.add_edge("execute_tool", "select_tool")
|
| 412 |
+
workflow.add_edge("formulate_answer", END)
|
| 413 |
+
|
| 414 |
+
workflow.set_entry_point("analyze_question")
|
| 415 |
+
|
| 416 |
+
initial_state = {
|
| 417 |
+
"question": "",
|
| 418 |
+
"analysis": None,
|
| 419 |
+
"plan": None,
|
| 420 |
+
"current_step": 0,
|
| 421 |
+
"tools_to_use": None,
|
| 422 |
+
"tool_results": [],
|
| 423 |
+
"intermediate_thoughts": [],
|
| 424 |
+
"answer": None,
|
| 425 |
+
"error": None
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
return workflow, initial_state
|
| 429 |
+
|
| 430 |
+
def run_agent_graph(question: str, config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
| 431 |
+
"""
|
| 432 |
+
Run the agent workflow graph with a question.
|
| 433 |
+
|
| 434 |
+
Args:
|
| 435 |
+
question: The question to answer
|
| 436 |
+
config: Optional configuration for the graph
|
| 437 |
+
|
| 438 |
+
Returns:
|
| 439 |
+
The final state of the graph
|
| 440 |
+
"""
|
| 441 |
+
workflow, initial_state = create_agent_graph()
|
| 442 |
+
|
| 443 |
+
app = workflow.compile()
|
| 444 |
+
|
| 445 |
+
state = initial_state.copy()
|
| 446 |
+
state["question"] = question
|
| 447 |
+
|
| 448 |
+
runnable_config = RunnableConfig(config or {})
|
| 449 |
+
|
| 450 |
+
result = app.invoke(state, config=runnable_config)
|
| 451 |
+
|
| 452 |
+
return result
|
agent/tool_registry.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tool registry for the GAIA agent.
|
| 3 |
+
|
| 4 |
+
This module provides a registry for tools that can be used by the GAIA agent.
|
| 5 |
+
It includes factory functions for creating tool instances and a registry class
|
| 6 |
+
for managing tool instances.
|
| 7 |
+
|
| 8 |
+
The registry is designed to be used with the LangGraph workflow in agent/graph.py.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
import os
|
| 13 |
+
from typing import Dict, Any, Optional, List, Callable
|
| 14 |
+
|
| 15 |
+
from tools.web_tools import (
|
| 16 |
+
DuckDuckGoSearchTool,
|
| 17 |
+
SerperSearchTool,
|
| 18 |
+
create_duckduckgo_search,
|
| 19 |
+
create_serper_search
|
| 20 |
+
)
|
| 21 |
+
from tools.perplexity_tool import PerplexityTool, create_perplexity_tool
|
| 22 |
+
from tools.arxiv_tool import ArxivSearchTool, create_arxiv_search
|
| 23 |
+
|
| 24 |
+
logger = logging.getLogger("gaia_agent.tool_registry")
|
| 25 |
+
|
| 26 |
+
class ToolRegistry:
|
| 27 |
+
"""Registry for tools used by the GAIA agent."""
|
| 28 |
+
|
| 29 |
+
def __init__(self):
|
| 30 |
+
"""Initialize an empty tool registry."""
|
| 31 |
+
self.tools = {}
|
| 32 |
+
|
| 33 |
+
def register_tool(self, name: str, tool: Any) -> None:
|
| 34 |
+
"""
|
| 35 |
+
Register a tool in the registry.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
name: The name of the tool
|
| 39 |
+
tool: The tool instance
|
| 40 |
+
"""
|
| 41 |
+
self.tools[name] = tool
|
| 42 |
+
|
| 43 |
+
def get_tool(self, name: str) -> Optional[Any]:
|
| 44 |
+
"""
|
| 45 |
+
Get a tool from the registry.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
name: The name of the tool
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
The tool instance, or None if not found
|
| 52 |
+
"""
|
| 53 |
+
tool = self.tools.get(name)
|
| 54 |
+
if not tool:
|
| 55 |
+
logger.warning(f"Tool not found in registry: {name}")
|
| 56 |
+
return tool
|
| 57 |
+
|
| 58 |
+
def list_tools(self) -> List[str]:
|
| 59 |
+
"""
|
| 60 |
+
List all tools in the registry.
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
List of tool names
|
| 64 |
+
"""
|
| 65 |
+
return list(self.tools.keys())
|
| 66 |
+
|
| 67 |
+
def execute_tool(self, name: str, **kwargs) -> Any:
|
| 68 |
+
"""
|
| 69 |
+
Execute a tool from the registry.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
name: The name of the tool
|
| 73 |
+
**kwargs: Arguments to pass to the tool
|
| 74 |
+
|
| 75 |
+
Returns:
|
| 76 |
+
The result of the tool execution
|
| 77 |
+
|
| 78 |
+
Raises:
|
| 79 |
+
Exception: If the tool is not found or execution fails
|
| 80 |
+
"""
|
| 81 |
+
tool = self.get_tool(name)
|
| 82 |
+
if not tool:
|
| 83 |
+
raise Exception(f"Tool not found in registry: {name}")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
if name in ["duckduckgo_search", "serper_search"]:
|
| 88 |
+
query = kwargs.get("query")
|
| 89 |
+
if not query:
|
| 90 |
+
raise ValueError("Query is required for search tools")
|
| 91 |
+
return tool.search(query)
|
| 92 |
+
|
| 93 |
+
elif name == "perplexity_search":
|
| 94 |
+
query = kwargs.get("query")
|
| 95 |
+
if not query:
|
| 96 |
+
raise ValueError("Query is required for Perplexity search")
|
| 97 |
+
return tool.search(query)
|
| 98 |
+
|
| 99 |
+
elif name == "arxiv_search":
|
| 100 |
+
query = kwargs.get("query")
|
| 101 |
+
max_results = kwargs.get("max_results")
|
| 102 |
+
if not query:
|
| 103 |
+
raise ValueError("Query is required for arXiv search")
|
| 104 |
+
return tool.search(query, max_results)
|
| 105 |
+
|
| 106 |
+
elif name == "arxiv_get_paper":
|
| 107 |
+
paper_id = kwargs.get("paper_id")
|
| 108 |
+
if not paper_id:
|
| 109 |
+
raise ValueError("Paper ID is required for arXiv paper retrieval")
|
| 110 |
+
return tool.get_paper_by_id(paper_id)
|
| 111 |
+
|
| 112 |
+
elif name == "arxiv_search_category":
|
| 113 |
+
category = kwargs.get("category")
|
| 114 |
+
max_results = kwargs.get("max_results")
|
| 115 |
+
if not category:
|
| 116 |
+
raise ValueError("Category is required for arXiv category search")
|
| 117 |
+
return tool.search_by_category(category, max_results)
|
| 118 |
+
|
| 119 |
+
else:
|
| 120 |
+
return tool.run(**kwargs)
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
logger.error(f"Error executing tool {name}: {str(e)}")
|
| 124 |
+
raise
|
| 125 |
+
|
| 126 |
+
def create_default_registry() -> ToolRegistry:
|
| 127 |
+
"""
|
| 128 |
+
Create a default tool registry with all available tools.
|
| 129 |
+
|
| 130 |
+
Returns:
|
| 131 |
+
ToolRegistry: A registry with all available tools
|
| 132 |
+
"""
|
| 133 |
+
registry = ToolRegistry()
|
| 134 |
+
|
| 135 |
+
# Register DuckDuckGo search tool (no API key required)
|
| 136 |
+
try:
|
| 137 |
+
duckduckgo_tool = create_duckduckgo_search()
|
| 138 |
+
registry.register_tool("duckduckgo_search", duckduckgo_tool)
|
| 139 |
+
except Exception as e:
|
| 140 |
+
logger.warning(f"Failed to create DuckDuckGo search tool: {str(e)}")
|
| 141 |
+
|
| 142 |
+
# Register Serper search tool if API key is available
|
| 143 |
+
serper_api_key = os.environ.get("SERPER_API_KEY")
|
| 144 |
+
if serper_api_key:
|
| 145 |
+
try:
|
| 146 |
+
serper_tool = create_serper_search()
|
| 147 |
+
registry.register_tool("serper_search", serper_tool)
|
| 148 |
+
except Exception as e:
|
| 149 |
+
logger.warning(f"Failed to create Serper search tool: {str(e)}")
|
| 150 |
+
else:
|
| 151 |
+
logger.warning("Serper API key not available, skipping Serper search tool")
|
| 152 |
+
|
| 153 |
+
# Register Perplexity tool if API key is available
|
| 154 |
+
perplexity_api_key = os.environ.get("PERPLEXITY_API_KEY")
|
| 155 |
+
if perplexity_api_key:
|
| 156 |
+
try:
|
| 157 |
+
perplexity_tool = create_perplexity_tool()
|
| 158 |
+
registry.register_tool("perplexity_search", perplexity_tool)
|
| 159 |
+
except Exception as e:
|
| 160 |
+
logger.warning(f"Failed to create Perplexity tool: {str(e)}")
|
| 161 |
+
else:
|
| 162 |
+
logger.warning("Perplexity API key not available, skipping Perplexity tool")
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
arxiv_tool = create_arxiv_search()
|
| 166 |
+
registry.register_tool("arxiv_search", arxiv_tool)
|
| 167 |
+
registry.register_tool("arxiv_get_paper", arxiv_tool)
|
| 168 |
+
registry.register_tool("arxiv_search_category", arxiv_tool)
|
| 169 |
+
except Exception as e:
|
| 170 |
+
logger.warning(f"Failed to create arXiv search tool: {str(e)}")
|
| 171 |
+
|
| 172 |
+
logger.info(f"Created default tool registry with {len(registry.list_tools())} tools")
|
| 173 |
+
return registry
|
| 174 |
+
|
| 175 |
+
def robust_search(registry: ToolRegistry, query: str) -> Dict[str, Any]:
|
| 176 |
+
"""
|
| 177 |
+
Perform a robust search using multiple providers.
|
| 178 |
+
|
| 179 |
+
This function tries multiple search providers in order, falling back to
|
| 180 |
+
the next provider if one fails.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
registry: The tool registry
|
| 184 |
+
query: The search query
|
| 185 |
+
|
| 186 |
+
Returns:
|
| 187 |
+
Dict with provider name and search results
|
| 188 |
+
|
| 189 |
+
Raises:
|
| 190 |
+
Exception: If all search providers fail
|
| 191 |
+
"""
|
| 192 |
+
# Try DuckDuckGo first (no API key required)
|
| 193 |
+
if registry.get_tool("duckduckgo_search"):
|
| 194 |
+
try:
|
| 195 |
+
results = registry.execute_tool("duckduckgo_search", query=query)
|
| 196 |
+
if results:
|
| 197 |
+
return {"provider": "duckduckgo", "results": results}
|
| 198 |
+
except Exception as e:
|
| 199 |
+
logger.warning(f"DuckDuckGo search failed: {str(e)}")
|
| 200 |
+
|
| 201 |
+
# Try Serper as fallback
|
| 202 |
+
if registry.get_tool("serper_search"):
|
| 203 |
+
try:
|
| 204 |
+
results = registry.execute_tool("serper_search", query=query)
|
| 205 |
+
if results:
|
| 206 |
+
return {"provider": "serper", "results": results}
|
| 207 |
+
except Exception as e:
|
| 208 |
+
logger.warning(f"Serper search failed: {str(e)}")
|
| 209 |
+
|
| 210 |
+
# Try Perplexity as last resort
|
| 211 |
+
if registry.get_tool("perplexity_search"):
|
| 212 |
+
try:
|
| 213 |
+
results = registry.execute_tool("perplexity_search", query=query)
|
| 214 |
+
if results:
|
| 215 |
+
return {"provider": "perplexity", "results": results}
|
| 216 |
+
except Exception as e:
|
| 217 |
+
logger.warning(f"Perplexity search failed: {str(e)}")
|
| 218 |
+
|
| 219 |
+
if registry.get_tool("arxiv_search"):
|
| 220 |
+
try:
|
| 221 |
+
results = registry.execute_tool("arxiv_search", query=query)
|
| 222 |
+
if results:
|
| 223 |
+
return {"provider": "arxiv", "results": results}
|
| 224 |
+
except Exception as e:
|
| 225 |
+
logger.warning(f"arXiv search failed: {str(e)}")
|
| 226 |
+
|
| 227 |
+
raise Exception("All search providers failed")
|
| 228 |
+
|
| 229 |
+
def merged_search(registry: ToolRegistry, query: str) -> Dict[str, Any]:
|
| 230 |
+
"""
|
| 231 |
+
Perform a merged search using multiple providers.
|
| 232 |
+
|
| 233 |
+
This function collects results from all available search providers and
|
| 234 |
+
merges them into a single result set, removing duplicates.
|
| 235 |
+
|
| 236 |
+
Args:
|
| 237 |
+
registry: The tool registry
|
| 238 |
+
query: The search query
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
Dict with merged results and Perplexity context
|
| 242 |
+
"""
|
| 243 |
+
results = {
|
| 244 |
+
"duckduckgo": [],
|
| 245 |
+
"serper": [],
|
| 246 |
+
"perplexity": None,
|
| 247 |
+
"arxiv": []
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
if registry.get_tool("duckduckgo_search"):
|
| 251 |
+
try:
|
| 252 |
+
results["duckduckgo"] = registry.execute_tool("duckduckgo_search", query=query)
|
| 253 |
+
except Exception as e:
|
| 254 |
+
logger.warning(f"DuckDuckGo search failed: {str(e)}")
|
| 255 |
+
|
| 256 |
+
if registry.get_tool("serper_search"):
|
| 257 |
+
try:
|
| 258 |
+
results["serper"] = registry.execute_tool("serper_search", query=query)
|
| 259 |
+
except Exception as e:
|
| 260 |
+
logger.warning(f"Serper search failed: {str(e)}")
|
| 261 |
+
|
| 262 |
+
if registry.get_tool("perplexity_search"):
|
| 263 |
+
try:
|
| 264 |
+
results["perplexity"] = registry.execute_tool("perplexity_search", query=query)
|
| 265 |
+
except Exception as e:
|
| 266 |
+
logger.warning(f"Perplexity search failed: {str(e)}")
|
| 267 |
+
merged = []
|
| 268 |
+
seen_urls = set()
|
| 269 |
+
|
| 270 |
+
# Add DuckDuckGo results
|
| 271 |
+
for result in results["duckduckgo"]:
|
| 272 |
+
if result["link"] not in seen_urls:
|
| 273 |
+
merged.append(result)
|
| 274 |
+
seen_urls.add(result["link"])
|
| 275 |
+
|
| 276 |
+
# Add Serper results
|
| 277 |
+
for result in results["serper"]:
|
| 278 |
+
if result["link"] not in seen_urls:
|
| 279 |
+
merged.append(result)
|
| 280 |
+
seen_urls.add(result["link"])
|
| 281 |
+
|
| 282 |
+
arxiv_results = []
|
| 283 |
+
for result in results["arxiv"]:
|
| 284 |
+
if "url" in result and result["url"] not in seen_urls:
|
| 285 |
+
formatted_result = {
|
| 286 |
+
"title": result.get("title", ""),
|
| 287 |
+
"link": result.get("url", ""),
|
| 288 |
+
"snippet": result.get("summary", "")[:200] + "..." if result.get("summary") else ""
|
| 289 |
+
}
|
| 290 |
+
merged.append(formatted_result)
|
| 291 |
+
seen_urls.add(result["url"])
|
| 292 |
+
arxiv_results.append(result) # Keep original format for context
|
| 293 |
+
|
| 294 |
+
# Add Perplexity content as context
|
| 295 |
+
perplexity_content = results["perplexity"].get("content") if results["perplexity"] else None
|
| 296 |
+
|
| 297 |
+
return {
|
| 298 |
+
"merged_results": merged,
|
| 299 |
+
"perplexity_context": perplexity_content,
|
| 300 |
+
"arxiv_context": arxiv_results
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
if __name__ == "__main__":
|
| 304 |
+
logging.basicConfig(level=logging.INFO)
|
| 305 |
+
|
| 306 |
+
registry = create_default_registry()
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
try:
|
| 310 |
+
query = "latest Python version"
|
| 311 |
+
result = robust_search(registry, query)
|
| 312 |
+
except Exception as e:
|
| 313 |
+
|
| 314 |
+
try:
|
| 315 |
+
query = "latest Python version"
|
| 316 |
+
result = merged_search(registry, query)
|
| 317 |
+
if result["perplexity_context"]:
|
| 318 |
+
if result.get("arxiv_context"):
|
| 319 |
+
except Exception as e:
|
app.py
CHANGED
|
@@ -1,196 +1,341 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import requests
|
| 4 |
-
import inspect
|
| 5 |
-
import pandas as pd
|
| 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 |
-
return
|
| 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 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
import inspect
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import logging
|
| 7 |
+
import time
|
| 8 |
+
from typing import Dict, Any, List, Optional, Tuple, Union
|
| 9 |
+
|
| 10 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
+
|
| 12 |
+
from agent import GAIAAgent
|
| 13 |
+
from agent.config import VERBOSE
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger("gaia_app")
|
| 16 |
+
if VERBOSE:
|
| 17 |
+
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 18 |
+
else:
|
| 19 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 20 |
+
|
| 21 |
+
def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None, progress=gr.Progress()) -> Tuple[str, Optional[pd.DataFrame]]:
|
| 22 |
+
"""
|
| 23 |
+
Fetches all questions, runs the GAIA Agent on them, submits all answers,
|
| 24 |
+
and displays the results with progress tracking.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
profile: Hugging Face user profile for authentication
|
| 28 |
+
progress: Gradio progress tracker
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
Tuple containing status message and results dataframe
|
| 32 |
+
"""
|
| 33 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 34 |
+
|
| 35 |
+
if profile:
|
| 36 |
+
username = f"{profile.username}"
|
| 37 |
+
logger.info(f"User logged in: {username}")
|
| 38 |
+
else:
|
| 39 |
+
logger.warning("User not logged in.")
|
| 40 |
+
return "Please Login to Hugging Face with the button.", None
|
| 41 |
+
|
| 42 |
+
api_url = DEFAULT_API_URL
|
| 43 |
+
questions_url = f"{api_url}/questions"
|
| 44 |
+
submit_url = f"{api_url}/submit"
|
| 45 |
+
|
| 46 |
+
progress(0, desc="Initializing GAIA Agent...")
|
| 47 |
+
try:
|
| 48 |
+
start_time = time.time()
|
| 49 |
+
agent = GAIAAgent()
|
| 50 |
+
init_time = time.time() - start_time
|
| 51 |
+
logger.info(f"GAIA Agent initialized successfully in {init_time:.2f} seconds.")
|
| 52 |
+
progress(0.1, desc=f"Agent initialized in {init_time:.2f}s")
|
| 53 |
+
except Exception as e:
|
| 54 |
+
error_msg = f"Error initializing GAIA agent: {e}"
|
| 55 |
+
logger.error(error_msg)
|
| 56 |
+
return error_msg, None
|
| 57 |
+
|
| 58 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 59 |
+
logger.info(f"Agent code URL: {agent_code}")
|
| 60 |
+
|
| 61 |
+
progress(0.15, desc="Fetching questions...")
|
| 62 |
+
logger.info(f"Fetching questions from: {questions_url}")
|
| 63 |
+
try:
|
| 64 |
+
response = requests.get(questions_url, timeout=15)
|
| 65 |
+
response.raise_for_status()
|
| 66 |
+
questions_data = response.json()
|
| 67 |
+
if not questions_data:
|
| 68 |
+
error_msg = "Fetched questions list is empty or invalid format."
|
| 69 |
+
logger.warning(error_msg)
|
| 70 |
+
return error_msg, None
|
| 71 |
+
|
| 72 |
+
question_count = len(questions_data)
|
| 73 |
+
logger.info(f"Fetched {question_count} questions.")
|
| 74 |
+
progress(0.2, desc=f"Fetched {question_count} questions")
|
| 75 |
+
except requests.exceptions.RequestException as e:
|
| 76 |
+
error_msg = f"Error fetching questions: {e}"
|
| 77 |
+
logger.error(error_msg)
|
| 78 |
+
return error_msg, None
|
| 79 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 80 |
+
error_msg = f"Error decoding JSON response from questions endpoint: {e}"
|
| 81 |
+
logger.error(f"{error_msg}\nResponse text: {response.text[:500]}")
|
| 82 |
+
return error_msg, None
|
| 83 |
+
except Exception as e:
|
| 84 |
+
error_msg = f"An unexpected error occurred fetching questions: {e}"
|
| 85 |
+
logger.error(error_msg)
|
| 86 |
+
return error_msg, None
|
| 87 |
+
|
| 88 |
+
results_log = []
|
| 89 |
+
answers_payload = []
|
| 90 |
+
total_questions = len(questions_data)
|
| 91 |
+
|
| 92 |
+
logger.info(f"Running agent on {total_questions} questions...")
|
| 93 |
+
|
| 94 |
+
question_progress_increment = 0.6 / total_questions # 60% of progress bar for processing questions
|
| 95 |
+
|
| 96 |
+
for i, item in enumerate(questions_data):
|
| 97 |
+
task_id = item.get("task_id")
|
| 98 |
+
question_text = item.get("question")
|
| 99 |
+
|
| 100 |
+
if not task_id or question_text is None:
|
| 101 |
+
logger.warning(f"Skipping item with missing task_id or question: {item}")
|
| 102 |
+
continue
|
| 103 |
+
|
| 104 |
+
progress_value = 0.2 + (i * question_progress_increment)
|
| 105 |
+
progress(progress_value, desc=f"Processing question {i+1}/{total_questions}...")
|
| 106 |
+
|
| 107 |
+
logger.info(f"Processing question {i+1}/{total_questions}: {question_text[:50]}...")
|
| 108 |
+
question_start_time = time.time()
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
submitted_answer = agent(question_text)
|
| 112 |
+
processing_time = time.time() - question_start_time
|
| 113 |
+
|
| 114 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 115 |
+
results_log.append({
|
| 116 |
+
"Task ID": task_id,
|
| 117 |
+
"Question": question_text,
|
| 118 |
+
"Submitted Answer": submitted_answer,
|
| 119 |
+
"Processing Time": f"{processing_time:.2f}s",
|
| 120 |
+
"Status": "Success"
|
| 121 |
+
})
|
| 122 |
+
|
| 123 |
+
logger.info(f"Question {i+1} processed in {processing_time:.2f}s. Answer: {submitted_answer[:50]}...")
|
| 124 |
+
|
| 125 |
+
except Exception as e:
|
| 126 |
+
error_msg = f"Error running agent on task {task_id}: {e}"
|
| 127 |
+
logger.error(error_msg)
|
| 128 |
+
|
| 129 |
+
results_log.append({
|
| 130 |
+
"Task ID": task_id,
|
| 131 |
+
"Question": question_text,
|
| 132 |
+
"Submitted Answer": f"AGENT ERROR: {e}",
|
| 133 |
+
"Processing Time": f"{time.time() - question_start_time:.2f}s",
|
| 134 |
+
"Status": "Error"
|
| 135 |
+
})
|
| 136 |
+
|
| 137 |
+
if not answers_payload:
|
| 138 |
+
error_msg = "Agent did not produce any answers to submit."
|
| 139 |
+
logger.warning(error_msg)
|
| 140 |
+
return error_msg, pd.DataFrame(results_log)
|
| 141 |
+
|
| 142 |
+
progress(0.8, desc="Preparing submission...")
|
| 143 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 144 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 145 |
+
logger.info(status_update)
|
| 146 |
+
|
| 147 |
+
progress(0.9, desc=f"Submitting {len(answers_payload)} answers...")
|
| 148 |
+
logger.info(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 149 |
+
try:
|
| 150 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 151 |
+
response.raise_for_status()
|
| 152 |
+
result_data = response.json()
|
| 153 |
+
|
| 154 |
+
correct_count = result_data.get('correct_count', 0)
|
| 155 |
+
total_attempted = result_data.get('total_attempted', 0)
|
| 156 |
+
score = result_data.get('score', 'N/A')
|
| 157 |
+
|
| 158 |
+
final_status = (
|
| 159 |
+
f"✅ Submission Successful!\n"
|
| 160 |
+
f"User: {result_data.get('username')}\n"
|
| 161 |
+
f"Overall Score: {score}% "
|
| 162 |
+
f"({correct_count}/{total_attempted} correct)\n"
|
| 163 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 164 |
+
)
|
| 165 |
+
logger.info("Submission successful.")
|
| 166 |
+
|
| 167 |
+
results_df = pd.DataFrame(results_log)
|
| 168 |
+
|
| 169 |
+
if not results_df.empty:
|
| 170 |
+
success_count = sum(1 for status in results_df.get("Status", []) if status == "Success")
|
| 171 |
+
error_count = sum(1 for status in results_df.get("Status", []) if status == "Error")
|
| 172 |
+
|
| 173 |
+
try:
|
| 174 |
+
avg_time = sum(float(time.strip('s')) for time in results_df["Processing Time"]) / len(results_df)
|
| 175 |
+
avg_time_str = f"{avg_time:.2f}s"
|
| 176 |
+
except:
|
| 177 |
+
avg_time_str = "N/A"
|
| 178 |
+
|
| 179 |
+
logger.info(f"Processed {len(results_df)} questions: {success_count} successes, {error_count} errors, avg time: {avg_time_str}")
|
| 180 |
+
|
| 181 |
+
progress(1.0, desc="Evaluation complete!")
|
| 182 |
+
return final_status, results_df
|
| 183 |
+
except requests.exceptions.HTTPError as e:
|
| 184 |
+
progress(1.0, desc="Submission failed!")
|
| 185 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 186 |
+
try:
|
| 187 |
+
error_json = e.response.json()
|
| 188 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 189 |
+
except requests.exceptions.JSONDecodeError:
|
| 190 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 191 |
+
status_message = f"❌ Submission Failed: {error_detail}"
|
| 192 |
+
logger.error(status_message)
|
| 193 |
+
results_df = pd.DataFrame(results_log)
|
| 194 |
+
return status_message, results_df
|
| 195 |
+
except requests.exceptions.Timeout:
|
| 196 |
+
progress(1.0, desc="Submission timed out!")
|
| 197 |
+
status_message = "❌ Submission Failed: The request timed out."
|
| 198 |
+
logger.error(status_message)
|
| 199 |
+
results_df = pd.DataFrame(results_log)
|
| 200 |
+
return status_message, results_df
|
| 201 |
+
except requests.exceptions.RequestException as e:
|
| 202 |
+
progress(1.0, desc="Network error!")
|
| 203 |
+
status_message = f"❌ Submission Failed: Network error - {e}"
|
| 204 |
+
logger.error(status_message)
|
| 205 |
+
results_df = pd.DataFrame(results_log)
|
| 206 |
+
return status_message, results_df
|
| 207 |
+
except Exception as e:
|
| 208 |
+
progress(1.0, desc="Error during submission!")
|
| 209 |
+
status_message = f"❌ An unexpected error occurred during submission: {e}"
|
| 210 |
+
logger.error(status_message)
|
| 211 |
+
results_df = pd.DataFrame(results_log)
|
| 212 |
+
return status_message, results_df
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 216 |
+
gr.Markdown("# GAIA Agent Evaluation Runner")
|
| 217 |
+
|
| 218 |
+
with gr.Tabs():
|
| 219 |
+
with gr.TabItem("Run Evaluation"):
|
| 220 |
+
gr.Markdown(
|
| 221 |
+
"""
|
| 222 |
+
**Instructions:**
|
| 223 |
+
|
| 224 |
+
1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 225 |
+
2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run the GAIA agent, submit answers, and see the score.
|
| 226 |
+
3. The progress bar will show you the current status of the evaluation.
|
| 227 |
+
4. Results will appear in the table below once processing is complete.
|
| 228 |
+
|
| 229 |
+
**Note:** Running the evaluation may take some time as the agent processes all questions. Please be patient.
|
| 230 |
+
"""
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
with gr.Row():
|
| 234 |
+
with gr.Column(scale=1):
|
| 235 |
+
gr.LoginButton()
|
| 236 |
+
with gr.Column(scale=2):
|
| 237 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary", size="lg")
|
| 238 |
+
|
| 239 |
+
status_output = gr.Textbox(
|
| 240 |
+
label="Run Status / Submission Result",
|
| 241 |
+
lines=6,
|
| 242 |
+
interactive=False,
|
| 243 |
+
elem_id="status_output"
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
with gr.Accordion("Results", open=False, elem_id="results_accordion"):
|
| 247 |
+
results_table = gr.DataFrame(
|
| 248 |
+
label="Questions and Agent Answers",
|
| 249 |
+
wrap=True,
|
| 250 |
+
elem_id="results_table"
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
with gr.Row():
|
| 254 |
+
with gr.Column():
|
| 255 |
+
gr.Markdown("### Result Statistics")
|
| 256 |
+
stats_output = gr.JSON(label="Statistics", visible=True)
|
| 257 |
+
|
| 258 |
+
with gr.TabItem("About GAIA Agent"):
|
| 259 |
+
gr.Markdown(
|
| 260 |
+
"""
|
| 261 |
+
## About GAIA Agent
|
| 262 |
+
|
| 263 |
+
This agent is designed to answer questions from the GAIA (Grounded AI Alignment) benchmark.
|
| 264 |
+
|
| 265 |
+
### Key Features:
|
| 266 |
+
|
| 267 |
+
- **Architecture**: Built with LangChain/LangGraph for workflow management
|
| 268 |
+
- **Tools**: Integrates multiple tools for web search, reasoning, and multimodal understanding
|
| 269 |
+
- **Memory**: Implements memory components for context retention
|
| 270 |
+
- **Structured Approach**: Uses a systematic process for question analysis and answer formulation
|
| 271 |
+
|
| 272 |
+
### Components:
|
| 273 |
+
|
| 274 |
+
1. **Web Tools**: Search engines, content extraction, and web navigation
|
| 275 |
+
2. **Reasoning Tools**: Step-by-step reasoning, mathematical calculations, fact verification
|
| 276 |
+
3. **Multimodal Tools**: Image analysis, chart interpretation, document parsing
|
| 277 |
+
4. **Memory Components**: Conversation history, working memory, result caching
|
| 278 |
+
|
| 279 |
+
### Performance Metrics:
|
| 280 |
+
|
| 281 |
+
The agent's performance is evaluated based on:
|
| 282 |
+
- Accuracy of answers
|
| 283 |
+
- Reasoning quality
|
| 284 |
+
- Ability to use appropriate tools
|
| 285 |
+
- Handling of edge cases
|
| 286 |
+
"""
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
with gr.TabItem("Help & Troubleshooting"):
|
| 290 |
+
gr.Markdown(
|
| 291 |
+
"""
|
| 292 |
+
## Help & Troubleshooting
|
| 293 |
+
|
| 294 |
+
### Common Issues:
|
| 295 |
+
|
| 296 |
+
1. **Login Problems**: Make sure you're logged in to Hugging Face before running the evaluation.
|
| 297 |
+
2. **Timeout Errors**: If the agent takes too long to process a question, try running the evaluation again.
|
| 298 |
+
3. **API Errors**: If you encounter API errors, check your internet connection and try again.
|
| 299 |
+
|
| 300 |
+
### Error Messages:
|
| 301 |
+
|
| 302 |
+
- **"Please Login to Hugging Face"**: You need to log in using the login button.
|
| 303 |
+
- **"Error initializing GAIA agent"**: There was a problem setting up the agent. Check the logs for details.
|
| 304 |
+
- **"Error fetching questions"**: The system couldn't retrieve questions from the API.
|
| 305 |
+
- **"Submission Failed"**: There was a problem submitting your answers. Check the error details.
|
| 306 |
+
|
| 307 |
+
### Contact:
|
| 308 |
+
|
| 309 |
+
If you continue to experience issues, please open an issue on the GitHub repository or contact the course instructors.
|
| 310 |
+
"""
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
run_button.click(
|
| 314 |
+
fn=run_and_submit_all,
|
| 315 |
+
outputs=[status_output, results_table]
|
| 316 |
+
).then(
|
| 317 |
+
fn=lambda df: {
|
| 318 |
+
"Total Questions": len(df) if df is not None else 0,
|
| 319 |
+
"Successful": sum(1 for status in df.get("Status", []) if status == "Success") if df is not None else 0,
|
| 320 |
+
"Errors": sum(1 for status in df.get("Status", []) if status == "Error") if df is not None else 0,
|
| 321 |
+
"Average Processing Time": f"{sum(float(time.strip('s')) for time in df['Processing Time']) / len(df):.2f}s" if df is not None and len(df) > 0 else "N/A"
|
| 322 |
+
} if df is not None else {},
|
| 323 |
+
inputs=[results_table],
|
| 324 |
+
outputs=[stats_output]
|
| 325 |
+
).then(
|
| 326 |
+
fn=lambda: gr.update(open=True),
|
| 327 |
+
outputs=[gr.Accordion.update(visible=True)]
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
if __name__ == "__main__":
|
| 331 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
| 332 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 333 |
+
|
| 334 |
+
if space_host_startup:
|
| 335 |
+
else:
|
| 336 |
+
|
| 337 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 338 |
+
else:
|
| 339 |
+
|
| 340 |
+
|
| 341 |
demo.launch(debug=True, share=False)
|
backup_tests/minimal_supabase_test.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Minimal Supabase Connection Test
|
| 3 |
+
|
| 4 |
+
This script performs a minimal test of the Supabase connection.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import logging
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
|
| 12 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 13 |
+
logger = logging.getLogger("minimal_supabase_test")
|
| 14 |
+
|
| 15 |
+
dotenv_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.env')
|
| 16 |
+
logger.info(f"Loading environment variables from {dotenv_path}")
|
| 17 |
+
load_dotenv(dotenv_path)
|
| 18 |
+
|
| 19 |
+
supabase_url = os.environ.get("SUPABASE_URL")
|
| 20 |
+
supabase_key = os.environ.get("SUPABASE_KEY")
|
| 21 |
+
|
| 22 |
+
logger.info(f"SUPABASE_URL: {supabase_url}")
|
| 23 |
+
logger.info(f"SUPABASE_KEY: {'***' if supabase_key else None}")
|
| 24 |
+
|
| 25 |
+
if not supabase_url or not supabase_key:
|
| 26 |
+
logger.error("Supabase URL or key not provided")
|
| 27 |
+
logger.error("Please set SUPABASE_URL and SUPABASE_KEY environment variables")
|
| 28 |
+
sys.exit(1)
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
from supabase import create_client, Client
|
| 32 |
+
logger.info("Supabase package imported successfully")
|
| 33 |
+
except ImportError as e:
|
| 34 |
+
logger.error(f"Error importing supabase: {str(e)}")
|
| 35 |
+
logger.error("Please install the supabase package with: pip install supabase")
|
| 36 |
+
sys.exit(1)
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
logger.info(f"Connecting to Supabase at {supabase_url}")
|
| 40 |
+
client = create_client(supabase_url, supabase_key)
|
| 41 |
+
logger.info("Supabase client created successfully")
|
| 42 |
+
|
| 43 |
+
import time
|
| 44 |
+
from datetime import datetime
|
| 45 |
+
|
| 46 |
+
test_id = int(time.time())
|
| 47 |
+
test_name = f"Test Record {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 48 |
+
|
| 49 |
+
logger.info(f"Inserting test record with ID {test_id} and name '{test_name}'...")
|
| 50 |
+
insert_result = client.table("test_connection").insert({
|
| 51 |
+
"id": test_id,
|
| 52 |
+
"name": test_name
|
| 53 |
+
}).execute()
|
| 54 |
+
|
| 55 |
+
if insert_result.data:
|
| 56 |
+
logger.info("Test record inserted successfully")
|
| 57 |
+
else:
|
| 58 |
+
logger.warning("Failed to insert test record")
|
| 59 |
+
|
| 60 |
+
logger.info("Querying test_connection table...")
|
| 61 |
+
result = client.table("test_connection").select("*").limit(5).execute()
|
| 62 |
+
|
| 63 |
+
if result.data is not None:
|
| 64 |
+
logger.info(f"Query successful, found {len(result.data)} records")
|
| 65 |
+
for record in result.data:
|
| 66 |
+
else:
|
| 67 |
+
logger.warning("Query successful but no data returned")
|
| 68 |
+
|
| 69 |
+
logger.info("Connection to Supabase successful")
|
| 70 |
+
except Exception as e:
|
| 71 |
+
logger.error(f"Error connecting to Supabase: {str(e)}")
|
| 72 |
+
import traceback
|
| 73 |
+
logger.error(f"Traceback: {traceback.format_exc()}")
|
| 74 |
+
sys.exit(1)
|
| 75 |
+
|
backup_tests/test_supabase_tables_final.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Final test script for Supabase tables in GAIA Agent.
|
| 3 |
+
|
| 4 |
+
This script applies the fix to ensure all Supabase tables are properly utilized,
|
| 5 |
+
then runs a simple test to verify the fix works correctly.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
python -m tests.test_supabase_tables_final
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import json
|
| 14 |
+
import logging
|
| 15 |
+
import time
|
| 16 |
+
import uuid
|
| 17 |
+
import datetime
|
| 18 |
+
from typing import Dict, Any, List, Optional
|
| 19 |
+
|
| 20 |
+
logging.basicConfig(
|
| 21 |
+
level=logging.INFO,
|
| 22 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
| 23 |
+
)
|
| 24 |
+
logger = logging.getLogger("test_supabase_tables_final")
|
| 25 |
+
|
| 26 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
from memory.supabase_memory import (
|
| 30 |
+
SupabaseMemory,
|
| 31 |
+
WorkingMemory
|
| 32 |
+
)
|
| 33 |
+
from agent.config import get_memory_config
|
| 34 |
+
|
| 35 |
+
from memory.fix_supabase_tables import apply_monkey_patch, ensure_tables_exist
|
| 36 |
+
except ImportError as e:
|
| 37 |
+
logger.error(f"Error importing required components: {str(e)}")
|
| 38 |
+
sys.exit(1)
|
| 39 |
+
|
| 40 |
+
def apply_fix_and_verify():
|
| 41 |
+
"""Apply the fix and verify it works correctly."""
|
| 42 |
+
logger.info("Applying fix for Supabase tables...")
|
| 43 |
+
|
| 44 |
+
if not ensure_tables_exist():
|
| 45 |
+
logger.error("Failed to ensure tables exist")
|
| 46 |
+
return False
|
| 47 |
+
|
| 48 |
+
if not apply_monkey_patch():
|
| 49 |
+
logger.error("Failed to apply monkey patch")
|
| 50 |
+
return False
|
| 51 |
+
|
| 52 |
+
logger.info("Fix applied successfully")
|
| 53 |
+
return True
|
| 54 |
+
|
| 55 |
+
def test_working_memory():
|
| 56 |
+
"""Test if working memory is using the correct table."""
|
| 57 |
+
logger.info("Testing working memory...")
|
| 58 |
+
|
| 59 |
+
memory_config = get_memory_config()
|
| 60 |
+
memory_config["enabled"] = True
|
| 61 |
+
|
| 62 |
+
base_memory = SupabaseMemory(config=memory_config)
|
| 63 |
+
session_id = f"test-session-{uuid.uuid4()}"
|
| 64 |
+
working_memory = WorkingMemory(base_memory, session_id)
|
| 65 |
+
|
| 66 |
+
logger.info(f"Base memory table: {base_memory.table_name}")
|
| 67 |
+
logger.info(f"Working memory table: {working_memory.table_name}")
|
| 68 |
+
|
| 69 |
+
test_key = f"test_working_{int(time.time())}"
|
| 70 |
+
test_value = {
|
| 71 |
+
"test_data": "This is test data for working memory",
|
| 72 |
+
"timestamp": time.time(),
|
| 73 |
+
"random_id": str(uuid.uuid4())
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
logger.info(f"Storing data in working memory: {test_key}")
|
| 77 |
+
store_result = working_memory.store_intermediate_result(test_key, test_value)
|
| 78 |
+
|
| 79 |
+
if not store_result:
|
| 80 |
+
logger.error("Failed to store test value")
|
| 81 |
+
return False
|
| 82 |
+
|
| 83 |
+
logger.info(f"Retrieving data from working memory: {test_key}")
|
| 84 |
+
retrieved_value = working_memory.get_intermediate_result(test_key)
|
| 85 |
+
|
| 86 |
+
if retrieved_value != test_value:
|
| 87 |
+
logger.error(f"Retrieved value does not match test value")
|
| 88 |
+
logger.error(f"Expected: {test_value}")
|
| 89 |
+
logger.error(f"Got: {retrieved_value}")
|
| 90 |
+
return False
|
| 91 |
+
|
| 92 |
+
logger.info("✅ Store and retrieve operations successful")
|
| 93 |
+
|
| 94 |
+
logger.info("Verifying data was stored in the working memory table...")
|
| 95 |
+
|
| 96 |
+
if base_memory.client and base_memory.initialized:
|
| 97 |
+
try:
|
| 98 |
+
working_key = f"working:{session_id}:{test_key}"
|
| 99 |
+
response = base_memory.client.table(working_memory.table_name).select("*").eq("key", working_key).execute()
|
| 100 |
+
|
| 101 |
+
if not response.data or len(response.data) == 0:
|
| 102 |
+
logger.error("No data found in working memory table")
|
| 103 |
+
|
| 104 |
+
response = base_memory.client.table(base_memory.table_name).select("*").eq("key", working_key).execute()
|
| 105 |
+
|
| 106 |
+
if response.data and len(response.data) > 0:
|
| 107 |
+
logger.error("❌ Data was stored in base memory table instead of working memory table")
|
| 108 |
+
return False
|
| 109 |
+
else:
|
| 110 |
+
logger.error("❌ Data was not stored in any table")
|
| 111 |
+
return False
|
| 112 |
+
|
| 113 |
+
logger.info(f"✅ Data found in working memory table: {len(response.data)} entries")
|
| 114 |
+
|
| 115 |
+
entry_data = response.data[0]
|
| 116 |
+
stored_value = entry_data.get("value")
|
| 117 |
+
|
| 118 |
+
if isinstance(stored_value, str):
|
| 119 |
+
try:
|
| 120 |
+
stored_value = json.loads(stored_value)
|
| 121 |
+
except json.JSONDecodeError:
|
| 122 |
+
pass
|
| 123 |
+
|
| 124 |
+
if stored_value == test_value or stored_value == json.dumps(test_value):
|
| 125 |
+
logger.info("✅ Stored data matches expected value")
|
| 126 |
+
else:
|
| 127 |
+
logger.error("❌ Stored data does not match expected value")
|
| 128 |
+
logger.error(f"Expected: {test_value}")
|
| 129 |
+
logger.error(f"Got: {stored_value}")
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
+
logger.info("Cleaning up test data...")
|
| 133 |
+
working_memory.clear()
|
| 134 |
+
|
| 135 |
+
return True
|
| 136 |
+
except Exception as e:
|
| 137 |
+
logger.error(f"Error verifying data storage: {str(e)}")
|
| 138 |
+
return False
|
| 139 |
+
|
| 140 |
+
return False
|
| 141 |
+
|
| 142 |
+
def main():
|
| 143 |
+
"""Main entry point for the test script."""
|
| 144 |
+
|
| 145 |
+
if not apply_fix_and_verify():
|
| 146 |
+
sys.exit(1)
|
| 147 |
+
|
| 148 |
+
if test_working_memory():
|
| 149 |
+
|
| 150 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 151 |
+
filename = f"gaia_memory_test_results_{timestamp}.json"
|
| 152 |
+
|
| 153 |
+
results = {
|
| 154 |
+
"timestamp": timestamp,
|
| 155 |
+
"success": True,
|
| 156 |
+
"message": "Working memory table is now being used correctly"
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
with open(filename, "w") as f:
|
| 160 |
+
json.dump(results, f, indent=2)
|
| 161 |
+
|
| 162 |
+
sys.exit(0)
|
| 163 |
+
else:
|
| 164 |
+
sys.exit(1)
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
main()
|
backup_tests/test_supabase_tables_fix.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test script for verifying the Supabase tables fix.
|
| 3 |
+
|
| 4 |
+
This script tests if the working memory table (gaia_memory_working) is properly
|
| 5 |
+
utilized by the GAIA agent. It verifies that data is correctly stored in and
|
| 6 |
+
retrieved from the working memory table.
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
python -m tests.test_supabase_tables_fix
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
+
import time
|
| 17 |
+
import uuid
|
| 18 |
+
from typing import Dict, Any, List, Optional
|
| 19 |
+
|
| 20 |
+
logging.basicConfig(
|
| 21 |
+
level=logging.INFO,
|
| 22 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
| 23 |
+
)
|
| 24 |
+
logger = logging.getLogger("test_supabase_tables")
|
| 25 |
+
|
| 26 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
from memory.supabase_memory import (
|
| 30 |
+
SupabaseMemory,
|
| 31 |
+
WorkingMemory
|
| 32 |
+
)
|
| 33 |
+
from agent.config import get_memory_config
|
| 34 |
+
|
| 35 |
+
from memory.simplified_memory_fix import apply_fix, create_working_memory_table
|
| 36 |
+
except ImportError as e:
|
| 37 |
+
logger.error(f"Error importing required components: {str(e)}")
|
| 38 |
+
sys.exit(1)
|
| 39 |
+
|
| 40 |
+
class SupabaseTablesTest:
|
| 41 |
+
"""Test class for verifying Supabase tables."""
|
| 42 |
+
|
| 43 |
+
def __init__(self):
|
| 44 |
+
"""Initialize the test class."""
|
| 45 |
+
self.memory_config = get_memory_config()
|
| 46 |
+
self.memory_config["enabled"] = True
|
| 47 |
+
|
| 48 |
+
self.base_memory = None
|
| 49 |
+
self.working_memory = None
|
| 50 |
+
self.session_id = str(uuid.uuid4())
|
| 51 |
+
|
| 52 |
+
self.table_names = {
|
| 53 |
+
"base": "gaia_memory",
|
| 54 |
+
"working": "gaia_memory_working"
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
self.results = {
|
| 58 |
+
"initialization": False,
|
| 59 |
+
"table_existence": {},
|
| 60 |
+
"working_memory": {}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
def initialize_memory(self) -> bool:
|
| 64 |
+
"""Initialize memory components."""
|
| 65 |
+
logger.info("Initializing memory components...")
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
self.base_memory = SupabaseMemory(self.memory_config)
|
| 69 |
+
|
| 70 |
+
self.working_memory = WorkingMemory(self.base_memory, self.session_id)
|
| 71 |
+
|
| 72 |
+
if self.base_memory and self.base_memory.initialized:
|
| 73 |
+
logger.info("✅ Memory components initialized successfully")
|
| 74 |
+
self.results["initialization"] = True
|
| 75 |
+
return True
|
| 76 |
+
else:
|
| 77 |
+
logger.error("❌ Memory components initialization failed")
|
| 78 |
+
self.results["initialization"] = False
|
| 79 |
+
return False
|
| 80 |
+
|
| 81 |
+
except Exception as e:
|
| 82 |
+
logger.error(f"Error initializing memory components: {str(e)}")
|
| 83 |
+
self.results["initialization"] = False
|
| 84 |
+
return False
|
| 85 |
+
|
| 86 |
+
def check_table_existence(self) -> Dict[str, bool]:
|
| 87 |
+
"""Check if the required tables exist."""
|
| 88 |
+
logger.info("Checking table existence...")
|
| 89 |
+
|
| 90 |
+
results = {}
|
| 91 |
+
|
| 92 |
+
if not self.base_memory or not self.base_memory.initialized:
|
| 93 |
+
logger.error("Memory components not initialized")
|
| 94 |
+
return {"error": "Memory components not initialized"}
|
| 95 |
+
|
| 96 |
+
for table_type, table_name in self.table_names.items():
|
| 97 |
+
try:
|
| 98 |
+
response = self.base_memory.client.table(table_name).select("*").limit(1).execute()
|
| 99 |
+
|
| 100 |
+
if hasattr(response, "data"):
|
| 101 |
+
logger.info(f"✅ Table {table_name} exists")
|
| 102 |
+
results[table_name] = True
|
| 103 |
+
else:
|
| 104 |
+
logger.warning(f"❌ Table {table_name} query failed")
|
| 105 |
+
results[table_name] = False
|
| 106 |
+
|
| 107 |
+
except Exception as e:
|
| 108 |
+
logger.error(f"Error checking table {table_name}: {str(e)}")
|
| 109 |
+
results[table_name] = False
|
| 110 |
+
|
| 111 |
+
self.results["table_existence"] = results
|
| 112 |
+
return results
|
| 113 |
+
|
| 114 |
+
def test_working_memory(self) -> Dict[str, bool]:
|
| 115 |
+
"""Test working memory operations."""
|
| 116 |
+
logger.info("Testing working memory operations...")
|
| 117 |
+
|
| 118 |
+
results = {}
|
| 119 |
+
|
| 120 |
+
if not self.working_memory:
|
| 121 |
+
logger.error("Working memory not initialized")
|
| 122 |
+
return {"error": "Working memory not initialized"}
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
test_key = f"test_working_{int(time.time())}"
|
| 126 |
+
test_value = {
|
| 127 |
+
"test_data": "This is test data for working memory",
|
| 128 |
+
"timestamp": time.time(),
|
| 129 |
+
"random_id": str(uuid.uuid4())
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
logger.info(f"Storing data in working memory: {test_key}")
|
| 133 |
+
store_result = self.working_memory.store_intermediate_result(test_key, test_value)
|
| 134 |
+
|
| 135 |
+
if store_result:
|
| 136 |
+
logger.info("✅ Store operation successful")
|
| 137 |
+
results["store"] = True
|
| 138 |
+
else:
|
| 139 |
+
logger.warning("❌ Store operation failed")
|
| 140 |
+
results["store"] = False
|
| 141 |
+
|
| 142 |
+
logger.info(f"Retrieving data from working memory: {test_key}")
|
| 143 |
+
retrieved_value = self.working_memory.get_intermediate_result(test_key)
|
| 144 |
+
|
| 145 |
+
if retrieved_value and retrieved_value == test_value:
|
| 146 |
+
logger.info("✅ Retrieve operation successful")
|
| 147 |
+
results["retrieve"] = True
|
| 148 |
+
else:
|
| 149 |
+
logger.warning(f"❌ Retrieve operation failed or data mismatch")
|
| 150 |
+
logger.warning(f"Expected: {test_value}")
|
| 151 |
+
logger.warning(f"Got: {retrieved_value}")
|
| 152 |
+
results["retrieve"] = False
|
| 153 |
+
|
| 154 |
+
logger.info("Verifying data was stored in the correct table...")
|
| 155 |
+
|
| 156 |
+
if self.base_memory.client and self.base_memory.initialized:
|
| 157 |
+
try:
|
| 158 |
+
working_key = f"working:{self.session_id}:{test_key}"
|
| 159 |
+
response = self.base_memory.client.table(self.table_names["working"]).select("*").eq("key", working_key).execute()
|
| 160 |
+
|
| 161 |
+
if response.data and len(response.data) > 0:
|
| 162 |
+
logger.info(f"✅ Data found in working memory table: {len(response.data)} entries")
|
| 163 |
+
results["correct_table"] = True
|
| 164 |
+
|
| 165 |
+
entry_data = response.data[0]
|
| 166 |
+
stored_value = entry_data.get("value")
|
| 167 |
+
|
| 168 |
+
if isinstance(stored_value, str):
|
| 169 |
+
try:
|
| 170 |
+
stored_value = json.loads(stored_value)
|
| 171 |
+
except json.JSONDecodeError:
|
| 172 |
+
pass
|
| 173 |
+
|
| 174 |
+
if stored_value == test_value or stored_value == json.dumps(test_value):
|
| 175 |
+
logger.info("✅ Stored data matches expected value")
|
| 176 |
+
results["data_match"] = True
|
| 177 |
+
else:
|
| 178 |
+
logger.warning("❌ Stored data does not match expected value")
|
| 179 |
+
logger.warning(f"Expected: {test_value}")
|
| 180 |
+
logger.warning(f"Got: {stored_value}")
|
| 181 |
+
results["data_match"] = False
|
| 182 |
+
else:
|
| 183 |
+
logger.warning("❌ No data found in working memory table")
|
| 184 |
+
results["correct_table"] = False
|
| 185 |
+
|
| 186 |
+
response = self.base_memory.client.table(self.table_names["base"]).select("*").eq("key", working_key).execute()
|
| 187 |
+
|
| 188 |
+
if response.data and len(response.data) > 0:
|
| 189 |
+
logger.warning("⚠️ Data was stored in base memory table instead of working memory table")
|
| 190 |
+
results["stored_in_base"] = True
|
| 191 |
+
else:
|
| 192 |
+
logger.warning("❌ Data was not stored in any table")
|
| 193 |
+
results["stored_in_base"] = False
|
| 194 |
+
|
| 195 |
+
except Exception as e:
|
| 196 |
+
logger.error(f"Error verifying data storage: {str(e)}")
|
| 197 |
+
results["correct_table"] = False
|
| 198 |
+
|
| 199 |
+
logger.info("Cleaning up test data...")
|
| 200 |
+
self.working_memory.clear()
|
| 201 |
+
|
| 202 |
+
except Exception as e:
|
| 203 |
+
logger.error(f"Error testing working memory: {str(e)}")
|
| 204 |
+
results["error"] = str(e)
|
| 205 |
+
|
| 206 |
+
self.results["working_memory"] = results
|
| 207 |
+
return results
|
| 208 |
+
|
| 209 |
+
def run_all_tests(self) -> Dict[str, Any]:
|
| 210 |
+
"""Run all tests."""
|
| 211 |
+
logger.info("Running all tests...")
|
| 212 |
+
|
| 213 |
+
if not self.initialize_memory():
|
| 214 |
+
logger.error("Memory initialization failed, aborting tests")
|
| 215 |
+
return self.results
|
| 216 |
+
|
| 217 |
+
self.check_table_existence()
|
| 218 |
+
|
| 219 |
+
if self.results["table_existence"].get(self.table_names["working"], False):
|
| 220 |
+
logger.info("Working memory table exists, applying fix...")
|
| 221 |
+
apply_fix()
|
| 222 |
+
else:
|
| 223 |
+
logger.info("Working memory table does not exist, creating it...")
|
| 224 |
+
create_working_memory_table()
|
| 225 |
+
|
| 226 |
+
self.check_table_existence()
|
| 227 |
+
|
| 228 |
+
self.test_working_memory()
|
| 229 |
+
|
| 230 |
+
return self.results
|
| 231 |
+
|
| 232 |
+
def print_test_summary(self) -> None:
|
| 233 |
+
"""Print a summary of the test results."""
|
| 234 |
+
|
| 235 |
+
if self.results["initialization"]:
|
| 236 |
+
else:
|
| 237 |
+
|
| 238 |
+
for table_name, exists in self.results["table_existence"].items():
|
| 239 |
+
if exists:
|
| 240 |
+
else:
|
| 241 |
+
|
| 242 |
+
working_results = self.results["working_memory"]
|
| 243 |
+
|
| 244 |
+
if working_results.get("store", False):
|
| 245 |
+
else:
|
| 246 |
+
|
| 247 |
+
if working_results.get("retrieve", False):
|
| 248 |
+
else:
|
| 249 |
+
|
| 250 |
+
if working_results.get("correct_table", False):
|
| 251 |
+
else:
|
| 252 |
+
|
| 253 |
+
if working_results.get("stored_in_base", False):
|
| 254 |
+
|
| 255 |
+
if working_results.get("data_match", False):
|
| 256 |
+
else:
|
| 257 |
+
|
| 258 |
+
if (self.results["initialization"] and
|
| 259 |
+
all(self.results["table_existence"].values()) and
|
| 260 |
+
working_results.get("store", False) and
|
| 261 |
+
working_results.get("retrieve", False) and
|
| 262 |
+
working_results.get("correct_table", False) and
|
| 263 |
+
working_results.get("data_match", False)):
|
| 264 |
+
else:
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def main():
|
| 268 |
+
"""Main entry point for the test script."""
|
| 269 |
+
|
| 270 |
+
test = SupabaseTablesTest()
|
| 271 |
+
test.run_all_tests()
|
| 272 |
+
|
| 273 |
+
test.print_test_summary()
|
| 274 |
+
|
| 275 |
+
if __name__ == "__main__":
|
| 276 |
+
main()
|
backup_tests/test_supabase_tables_production.py
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Comprehensive Unit Tests for Supabase Tables
|
| 3 |
+
|
| 4 |
+
This script tests all Supabase tables used by the GAIA agent:
|
| 5 |
+
- gaia_memory: Main memory table
|
| 6 |
+
- gaia_memory_working: Working memory table
|
| 7 |
+
- gaia_memory_conversations: Conversation history table
|
| 8 |
+
- gaia_memory_cache: Result cache table
|
| 9 |
+
|
| 10 |
+
The tests verify:
|
| 11 |
+
1. Each table is created correctly
|
| 12 |
+
2. Each memory class uses its dedicated table
|
| 13 |
+
3. Data is properly isolated between tables
|
| 14 |
+
4. Performance metrics are captured
|
| 15 |
+
5. All test data is cleaned up after tests
|
| 16 |
+
|
| 17 |
+
Usage:
|
| 18 |
+
python tests/test_supabase_tables_production.py
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
import json
|
| 24 |
+
import time
|
| 25 |
+
import uuid
|
| 26 |
+
import logging
|
| 27 |
+
import unittest
|
| 28 |
+
from datetime import datetime, timedelta
|
| 29 |
+
from typing import Dict, Any, List, Optional, Union, Tuple
|
| 30 |
+
|
| 31 |
+
logging.basicConfig(
|
| 32 |
+
level=logging.INFO,
|
| 33 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
| 34 |
+
)
|
| 35 |
+
logger = logging.getLogger("test_supabase_tables_production")
|
| 36 |
+
|
| 37 |
+
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 38 |
+
sys.path.insert(0, parent_dir)
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
from supabase import create_client, Client
|
| 42 |
+
except ImportError as e:
|
| 43 |
+
logger.error(f"Error importing supabase: {str(e)}")
|
| 44 |
+
sys.exit(1)
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
from agent.config import (
|
| 48 |
+
SUPABASE_URL,
|
| 49 |
+
SUPABASE_KEY,
|
| 50 |
+
SUPABASE_PROJECT_ID,
|
| 51 |
+
SUPABASE_PROJECT_NAME
|
| 52 |
+
)
|
| 53 |
+
except ImportError as e:
|
| 54 |
+
logger.error(f"Error importing configuration: {str(e)}")
|
| 55 |
+
sys.exit(1)
|
| 56 |
+
|
| 57 |
+
def get_table_schema(client: Client, table_name: str) -> List[str]:
|
| 58 |
+
"""Get the schema of a table."""
|
| 59 |
+
try:
|
| 60 |
+
result = client.table(table_name).select("*").limit(1).execute()
|
| 61 |
+
|
| 62 |
+
if result.data and len(result.data) > 0:
|
| 63 |
+
return list(result.data[0].keys())
|
| 64 |
+
else:
|
| 65 |
+
schema_result = client.from_("information_schema.columns").select("column_name").eq("table_name", table_name).execute()
|
| 66 |
+
if schema_result.data:
|
| 67 |
+
return [col["column_name"] for col in schema_result.data]
|
| 68 |
+
else:
|
| 69 |
+
return []
|
| 70 |
+
except Exception as e:
|
| 71 |
+
logger.error(f"Error getting schema for table {table_name}: {str(e)}")
|
| 72 |
+
return []
|
| 73 |
+
|
| 74 |
+
def ensure_table_exists(client: Client, table_name: str) -> bool:
|
| 75 |
+
"""Ensure a table exists in Supabase."""
|
| 76 |
+
try:
|
| 77 |
+
client.table(table_name).select("*").limit(1).execute()
|
| 78 |
+
logger.info(f"Table {table_name} exists")
|
| 79 |
+
return True
|
| 80 |
+
except Exception as e:
|
| 81 |
+
logger.warning(f"Error checking table {table_name}: {str(e)}")
|
| 82 |
+
logger.info(f"Creating table {table_name}")
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
sql = f"""
|
| 86 |
+
CREATE TABLE IF NOT EXISTS {table_name} (
|
| 87 |
+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 88 |
+
key TEXT NOT NULL UNIQUE,
|
| 89 |
+
value TEXT NOT NULL,
|
| 90 |
+
metadata JSONB,
|
| 91 |
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
| 92 |
+
expires_at TIMESTAMPTZ
|
| 93 |
+
);
|
| 94 |
+
|
| 95 |
+
CREATE INDEX IF NOT EXISTS idx_{table_name}_key ON {table_name}(key);
|
| 96 |
+
CREATE INDEX IF NOT EXISTS idx_{table_name}_expires_at ON {table_name}(expires_at);
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
client.query(sql).execute()
|
| 100 |
+
|
| 101 |
+
client.table(table_name).select("*").limit(1).execute()
|
| 102 |
+
|
| 103 |
+
logger.info(f"Table {table_name} created successfully")
|
| 104 |
+
return True
|
| 105 |
+
except Exception as e:
|
| 106 |
+
logger.error(f"Error creating table {table_name}: {str(e)}")
|
| 107 |
+
return False
|
| 108 |
+
|
| 109 |
+
def store_value(client: Client, table_name: str, key: str, value: Any, metadata: Optional[Dict[str, Any]] = None, ttl: Optional[int] = None, session_id: Optional[str] = None) -> bool:
|
| 110 |
+
"""Store a value in a table."""
|
| 111 |
+
try:
|
| 112 |
+
entry = {
|
| 113 |
+
"key": key,
|
| 114 |
+
"value": json.dumps(value) if not isinstance(value, str) else value,
|
| 115 |
+
"metadata": metadata or {}
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
if ttl:
|
| 119 |
+
entry["expires_at"] = (datetime.now() + timedelta(seconds=ttl)).isoformat()
|
| 120 |
+
|
| 121 |
+
if session_id and table_name.endswith("_working"):
|
| 122 |
+
entry["session_id"] = session_id
|
| 123 |
+
|
| 124 |
+
client.table(table_name).upsert(entry).execute()
|
| 125 |
+
|
| 126 |
+
logger.info(f"Stored value in table {table_name}: {key}")
|
| 127 |
+
return True
|
| 128 |
+
except Exception as e:
|
| 129 |
+
logger.error(f"Error storing value in table {table_name}: {key} - {str(e)}")
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
+
def retrieve_value(client: Client, table_name: str, key: str, default: Any = None) -> Any:
|
| 133 |
+
"""Retrieve a value from a table."""
|
| 134 |
+
try:
|
| 135 |
+
result = client.table(table_name).select("*").eq("key", key).execute()
|
| 136 |
+
|
| 137 |
+
if result.data and len(result.data) > 0:
|
| 138 |
+
entry = result.data[0]
|
| 139 |
+
|
| 140 |
+
value = entry.get("value")
|
| 141 |
+
if isinstance(value, str):
|
| 142 |
+
try:
|
| 143 |
+
value = json.loads(value)
|
| 144 |
+
except json.JSONDecodeError:
|
| 145 |
+
pass
|
| 146 |
+
|
| 147 |
+
expires_at = entry.get("expires_at")
|
| 148 |
+
if expires_at:
|
| 149 |
+
try:
|
| 150 |
+
expiry = datetime.fromisoformat(expires_at)
|
| 151 |
+
if expiry < datetime.now():
|
| 152 |
+
delete_value(client, table_name, key)
|
| 153 |
+
return default
|
| 154 |
+
except (ValueError, TypeError):
|
| 155 |
+
pass
|
| 156 |
+
|
| 157 |
+
logger.info(f"Retrieved value from table {table_name}: {key}")
|
| 158 |
+
return value
|
| 159 |
+
except Exception as e:
|
| 160 |
+
logger.error(f"Error retrieving value from table {table_name}: {key} - {str(e)}")
|
| 161 |
+
|
| 162 |
+
return default
|
| 163 |
+
|
| 164 |
+
def delete_value(client: Client, table_name: str, key: str) -> bool:
|
| 165 |
+
"""Delete a value from a table."""
|
| 166 |
+
try:
|
| 167 |
+
client.table(table_name).delete().eq("key", key).execute()
|
| 168 |
+
|
| 169 |
+
logger.info(f"Deleted value from table {table_name}: {key}")
|
| 170 |
+
return True
|
| 171 |
+
except Exception as e:
|
| 172 |
+
logger.error(f"Error deleting value from table {table_name}: {key} - {str(e)}")
|
| 173 |
+
return False
|
| 174 |
+
|
| 175 |
+
def list_keys(client: Client, table_name: str, prefix: Optional[str] = None) -> List[str]:
|
| 176 |
+
"""List keys in a table."""
|
| 177 |
+
keys = []
|
| 178 |
+
|
| 179 |
+
try:
|
| 180 |
+
query = client.table(table_name).select("key")
|
| 181 |
+
|
| 182 |
+
if prefix:
|
| 183 |
+
query = query.like("key", f"{prefix}%")
|
| 184 |
+
|
| 185 |
+
result = query.execute()
|
| 186 |
+
|
| 187 |
+
if result.data:
|
| 188 |
+
for entry in result.data:
|
| 189 |
+
key = entry.get("key")
|
| 190 |
+
if key:
|
| 191 |
+
keys.append(key)
|
| 192 |
+
|
| 193 |
+
logger.info(f"Listed keys from table {table_name}: {len(keys)} keys")
|
| 194 |
+
except Exception as e:
|
| 195 |
+
logger.error(f"Error listing keys from table {table_name}: {str(e)}")
|
| 196 |
+
|
| 197 |
+
return keys
|
| 198 |
+
|
| 199 |
+
def clear_table(client: Client, table_name: str, prefix: Optional[str] = None) -> bool:
|
| 200 |
+
"""Clear a table."""
|
| 201 |
+
try:
|
| 202 |
+
if prefix:
|
| 203 |
+
keys = list_keys(client, table_name, prefix)
|
| 204 |
+
|
| 205 |
+
for key in keys:
|
| 206 |
+
delete_value(client, table_name, key)
|
| 207 |
+
else:
|
| 208 |
+
client.table(table_name).delete().execute()
|
| 209 |
+
|
| 210 |
+
logger.info(f"Cleared table {table_name}")
|
| 211 |
+
return True
|
| 212 |
+
except Exception as e:
|
| 213 |
+
logger.error(f"Error clearing table {table_name}: {str(e)}")
|
| 214 |
+
return False
|
| 215 |
+
|
| 216 |
+
def run_tests():
|
| 217 |
+
"""Run the tests."""
|
| 218 |
+
logger.info("Running Supabase tables tests...")
|
| 219 |
+
|
| 220 |
+
if not SUPABASE_URL or not SUPABASE_KEY:
|
| 221 |
+
logger.error("Supabase URL or key not provided")
|
| 222 |
+
logger.error("Please set SUPABASE_URL and SUPABASE_KEY environment variables")
|
| 223 |
+
return False
|
| 224 |
+
|
| 225 |
+
# Initialize Supabase client
|
| 226 |
+
client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 227 |
+
|
| 228 |
+
test_run_id = str(uuid.uuid4())
|
| 229 |
+
session_id = f"test-session-{test_run_id}"
|
| 230 |
+
conversation_id = f"test-conversation-{test_run_id}"
|
| 231 |
+
|
| 232 |
+
base_table = "gaia_memory"
|
| 233 |
+
tables = {
|
| 234 |
+
"base": base_table,
|
| 235 |
+
"working": f"{base_table}_working",
|
| 236 |
+
"conversations": f"{base_table}_conversations",
|
| 237 |
+
"cache": f"{base_table}_cache"
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
for table_type, table_name in tables.items():
|
| 241 |
+
if not ensure_table_exists(client, table_name):
|
| 242 |
+
logger.error(f"Failed to ensure table {table_name} exists")
|
| 243 |
+
return False
|
| 244 |
+
|
| 245 |
+
schema = get_table_schema(client, table_name)
|
| 246 |
+
logger.info(f"Table {table_name} schema: {schema}")
|
| 247 |
+
|
| 248 |
+
if table_type == "conversations":
|
| 249 |
+
if "conversation_id" in schema and "message_id" in schema and "content" in schema:
|
| 250 |
+
logger.info(f"Table {table_name} has a different schema for conversations")
|
| 251 |
+
|
| 252 |
+
logger.info("Testing base table operations...")
|
| 253 |
+
|
| 254 |
+
test_key = f"test-{test_run_id}-base"
|
| 255 |
+
test_value = {
|
| 256 |
+
"test_data": f"This is test data for {test_key}",
|
| 257 |
+
"timestamp": datetime.now().isoformat(),
|
| 258 |
+
"random_id": str(uuid.uuid4())
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
if not store_value(client, tables["base"], test_key, test_value):
|
| 262 |
+
logger.error("Failed to store test value in base table")
|
| 263 |
+
return False
|
| 264 |
+
|
| 265 |
+
retrieved_value = retrieve_value(client, tables["base"], test_key)
|
| 266 |
+
if retrieved_value != test_value:
|
| 267 |
+
logger.error("Retrieved value does not match test value")
|
| 268 |
+
logger.error(f"Expected: {test_value}")
|
| 269 |
+
logger.error(f"Got: {retrieved_value}")
|
| 270 |
+
return False
|
| 271 |
+
|
| 272 |
+
logger.info("[PASS] Base table operations successful")
|
| 273 |
+
|
| 274 |
+
logger.info("Testing working memory table operations...")
|
| 275 |
+
|
| 276 |
+
working_key = f"working:{session_id}:test-{test_run_id}-working"
|
| 277 |
+
working_value = {
|
| 278 |
+
"test_data": f"This is test data for {working_key}",
|
| 279 |
+
"timestamp": datetime.now().isoformat(),
|
| 280 |
+
"random_id": str(uuid.uuid4())
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
if not store_value(client, tables["working"], working_key, working_value, session_id=session_id):
|
| 284 |
+
logger.error("Failed to store test value in working table")
|
| 285 |
+
return False
|
| 286 |
+
|
| 287 |
+
retrieved_value = retrieve_value(client, tables["working"], working_key)
|
| 288 |
+
if retrieved_value != working_value:
|
| 289 |
+
logger.error("Retrieved value does not match test value")
|
| 290 |
+
logger.error(f"Expected: {working_value}")
|
| 291 |
+
logger.error(f"Got: {retrieved_value}")
|
| 292 |
+
return False
|
| 293 |
+
|
| 294 |
+
base_value = retrieve_value(client, tables["base"], working_key)
|
| 295 |
+
if base_value is not None:
|
| 296 |
+
logger.error("Working memory data was incorrectly stored in base table")
|
| 297 |
+
return False
|
| 298 |
+
|
| 299 |
+
logger.info("[PASS] Working memory table operations successful")
|
| 300 |
+
|
| 301 |
+
logger.info("Testing conversation memory table operations...")
|
| 302 |
+
|
| 303 |
+
schema = get_table_schema(client, tables["conversations"])
|
| 304 |
+
|
| 305 |
+
if "key" in schema and "value" in schema:
|
| 306 |
+
conversation_key = f"conversation:{conversation_id}:message:{datetime.now().isoformat()}"
|
| 307 |
+
conversation_value = {
|
| 308 |
+
"role": "user",
|
| 309 |
+
"content": "Hello, how are you?",
|
| 310 |
+
"timestamp": datetime.now().isoformat()
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
if not store_value(client, tables["conversations"], conversation_key, conversation_value):
|
| 314 |
+
logger.error("Failed to store test value in conversations table")
|
| 315 |
+
return False
|
| 316 |
+
|
| 317 |
+
retrieved_value = retrieve_value(client, tables["conversations"], conversation_key)
|
| 318 |
+
if retrieved_value != conversation_value:
|
| 319 |
+
logger.error("Retrieved value does not match test value")
|
| 320 |
+
logger.error(f"Expected: {conversation_value}")
|
| 321 |
+
logger.error(f"Got: {retrieved_value}")
|
| 322 |
+
return False
|
| 323 |
+
|
| 324 |
+
base_value = retrieve_value(client, tables["base"], conversation_key)
|
| 325 |
+
if base_value is not None:
|
| 326 |
+
logger.error("Conversation memory data was incorrectly stored in base table")
|
| 327 |
+
return False
|
| 328 |
+
else:
|
| 329 |
+
logger.info("Using different schema for conversations table")
|
| 330 |
+
|
| 331 |
+
try:
|
| 332 |
+
message_id = f"message-{datetime.now().isoformat()}"
|
| 333 |
+
entry = {
|
| 334 |
+
"conversation_id": conversation_id,
|
| 335 |
+
"message_id": message_id,
|
| 336 |
+
"role": "user",
|
| 337 |
+
"content": "Hello, how are you?",
|
| 338 |
+
"created_at": datetime.now().isoformat()
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
client.table(tables["conversations"]).insert(entry).execute()
|
| 342 |
+
logger.info(f"Inserted message in conversations table: {message_id}")
|
| 343 |
+
|
| 344 |
+
result = client.table(tables["conversations"]).select("*").eq("conversation_id", conversation_id).execute()
|
| 345 |
+
|
| 346 |
+
if not result.data or len(result.data) == 0:
|
| 347 |
+
logger.error("No messages found in conversations table")
|
| 348 |
+
return False
|
| 349 |
+
|
| 350 |
+
logger.info(f"Found {len(result.data)} messages in conversations table")
|
| 351 |
+
except Exception as e:
|
| 352 |
+
logger.error(f"Error testing conversations table: {str(e)}")
|
| 353 |
+
return False
|
| 354 |
+
|
| 355 |
+
logger.info("[PASS] Conversation memory table operations successful")
|
| 356 |
+
|
| 357 |
+
logger.info("Testing result cache table operations...")
|
| 358 |
+
|
| 359 |
+
cache_key = f"cache:test-{test_run_id}-cache"
|
| 360 |
+
cache_value = {
|
| 361 |
+
"test_data": f"This is test data for {cache_key}",
|
| 362 |
+
"timestamp": datetime.now().isoformat(),
|
| 363 |
+
"random_id": str(uuid.uuid4())
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
if not store_value(client, tables["cache"], cache_key, cache_value, ttl=3600):
|
| 367 |
+
logger.error("Failed to store test value in cache table")
|
| 368 |
+
return False
|
| 369 |
+
|
| 370 |
+
retrieved_value = retrieve_value(client, tables["cache"], cache_key)
|
| 371 |
+
if retrieved_value != cache_value:
|
| 372 |
+
logger.error("Retrieved value does not match test value")
|
| 373 |
+
logger.error(f"Expected: {cache_value}")
|
| 374 |
+
logger.error(f"Got: {retrieved_value}")
|
| 375 |
+
return False
|
| 376 |
+
|
| 377 |
+
base_value = retrieve_value(client, tables["base"], cache_key)
|
| 378 |
+
if base_value is not None:
|
| 379 |
+
logger.error("Result cache data was incorrectly stored in base table")
|
| 380 |
+
return False
|
| 381 |
+
|
| 382 |
+
logger.info("[PASS] Result cache table operations successful")
|
| 383 |
+
|
| 384 |
+
logger.info("Testing data isolation between tables...")
|
| 385 |
+
|
| 386 |
+
base_keys = list_keys(client, tables["base"])
|
| 387 |
+
working_keys = list_keys(client, tables["working"])
|
| 388 |
+
cache_keys = list_keys(client, tables["cache"])
|
| 389 |
+
|
| 390 |
+
schema = get_table_schema(client, tables["conversations"])
|
| 391 |
+
if "key" in schema:
|
| 392 |
+
conversation_keys = list_keys(client, tables["conversations"])
|
| 393 |
+
|
| 394 |
+
if conversation_key not in conversation_keys:
|
| 395 |
+
logger.error(f"Conversation key {conversation_key} not found in conversations table")
|
| 396 |
+
return False
|
| 397 |
+
else:
|
| 398 |
+
try:
|
| 399 |
+
result = client.table(tables["conversations"]).select("*").eq("conversation_id", conversation_id).execute()
|
| 400 |
+
if not result.data or len(result.data) == 0:
|
| 401 |
+
logger.error(f"No messages found for conversation ID {conversation_id}")
|
| 402 |
+
return False
|
| 403 |
+
logger.info(f"Found {len(result.data)} messages for conversation ID {conversation_id}")
|
| 404 |
+
except Exception as e:
|
| 405 |
+
logger.error(f"Error checking conversations table: {str(e)}")
|
| 406 |
+
return False
|
| 407 |
+
|
| 408 |
+
if test_key not in base_keys:
|
| 409 |
+
logger.error(f"Test key {test_key} not found in base table")
|
| 410 |
+
return False
|
| 411 |
+
|
| 412 |
+
if working_key not in working_keys:
|
| 413 |
+
logger.error(f"Working key {working_key} not found in working table")
|
| 414 |
+
return False
|
| 415 |
+
|
| 416 |
+
if cache_key not in cache_keys:
|
| 417 |
+
logger.error(f"Cache key {cache_key} not found in cache table")
|
| 418 |
+
return False
|
| 419 |
+
|
| 420 |
+
logger.info("[PASS] Data isolation between tables verified")
|
| 421 |
+
|
| 422 |
+
logger.info("Testing performance metrics...")
|
| 423 |
+
|
| 424 |
+
num_operations = 10
|
| 425 |
+
|
| 426 |
+
base_store_times = []
|
| 427 |
+
base_retrieve_times = []
|
| 428 |
+
|
| 429 |
+
for i in range(num_operations):
|
| 430 |
+
key = f"test-{test_run_id}-perf-base-{i}"
|
| 431 |
+
value = {"index": i, "data": f"Performance test data {i}"}
|
| 432 |
+
|
| 433 |
+
start_time = time.time()
|
| 434 |
+
store_value(client, tables["base"], key, value)
|
| 435 |
+
base_store_times.append(time.time() - start_time)
|
| 436 |
+
|
| 437 |
+
start_time = time.time()
|
| 438 |
+
retrieve_value(client, tables["base"], key)
|
| 439 |
+
base_retrieve_times.append(time.time() - start_time)
|
| 440 |
+
|
| 441 |
+
working_store_times = []
|
| 442 |
+
working_retrieve_times = []
|
| 443 |
+
|
| 444 |
+
for i in range(num_operations):
|
| 445 |
+
key = f"working:{session_id}:test-{test_run_id}-perf-working-{i}"
|
| 446 |
+
value = {"index": i, "data": f"Performance test data {i}"}
|
| 447 |
+
|
| 448 |
+
start_time = time.time()
|
| 449 |
+
store_value(client, tables["working"], key, value, session_id=session_id)
|
| 450 |
+
working_store_times.append(time.time() - start_time)
|
| 451 |
+
|
| 452 |
+
start_time = time.time()
|
| 453 |
+
retrieve_value(client, tables["working"], key)
|
| 454 |
+
working_retrieve_times.append(time.time() - start_time)
|
| 455 |
+
|
| 456 |
+
logger.info(f"Base table: avg store {sum(base_store_times)/num_operations:.4f}s, avg retrieve {sum(base_retrieve_times)/num_operations:.4f}s")
|
| 457 |
+
logger.info(f"Working table: avg store {sum(working_store_times)/num_operations:.4f}s, avg retrieve {sum(working_retrieve_times)/num_operations:.4f}s")
|
| 458 |
+
|
| 459 |
+
logger.info("[PASS] Performance metrics collected")
|
| 460 |
+
|
| 461 |
+
logger.info("Cleaning up test data...")
|
| 462 |
+
|
| 463 |
+
clear_table(client, tables["base"], f"test-{test_run_id}")
|
| 464 |
+
clear_table(client, tables["working"], f"working:{session_id}")
|
| 465 |
+
clear_table(client, tables["conversations"], f"conversation:{conversation_id}")
|
| 466 |
+
clear_table(client, tables["cache"], f"cache:test-{test_run_id}")
|
| 467 |
+
|
| 468 |
+
logger.info("[PASS] Test data cleaned up")
|
| 469 |
+
|
| 470 |
+
return True
|
| 471 |
+
|
| 472 |
+
def main():
|
| 473 |
+
"""Main entry point for the test script."""
|
| 474 |
+
|
| 475 |
+
if run_tests():
|
| 476 |
+
sys.exit(0)
|
| 477 |
+
else:
|
| 478 |
+
sys.exit(1)
|
| 479 |
+
|
| 480 |
+
if __name__ == "__main__":
|
| 481 |
+
main()
|
cleanup_results.txt
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
2025-04-30 22:18:05,446 - INFO - Finding temporary files to remove...
|
| 2 |
+
2025-04-30 22:18:05,563 - INFO - Found 39 temporary files to remove
|
| 3 |
+
2025-04-30 22:18:05,603 - INFO - Removed: gaia_assessment_results_20250430_205848.json
|
| 4 |
+
2025-04-30 22:18:05,615 - INFO - Removed: gaia_assessment_results_20250430_210047.json
|
| 5 |
+
2025-04-30 22:18:05,616 - INFO - Removed: gaia_assessment_results_20250430_210252.json
|
| 6 |
+
2025-04-30 22:18:05,619 - INFO - Removed: gaia_assessment_results_20250430_210521.json
|
| 7 |
+
2025-04-30 22:18:05,621 - INFO - Removed: gaia_assessment_results_20250430_211034.json
|
| 8 |
+
2025-04-30 22:18:05,622 - INFO - Removed: gaia_assessment_results_20250430_211508.json
|
| 9 |
+
2025-04-30 22:18:05,624 - INFO - Removed: gaia_assessment_results_20250430_213743.json
|
| 10 |
+
2025-04-30 22:18:05,627 - INFO - Removed: gaia_assessment_results_20250430_214034.json
|
| 11 |
+
2025-04-30 22:18:05,629 - INFO - Removed: gaia_assessment_results_20250430_214159.json
|
| 12 |
+
2025-04-30 22:18:05,631 - INFO - Removed: gaia_assessment_results_20250430_214711.json
|
| 13 |
+
2025-04-30 22:18:05,634 - INFO - Removed: gaia_assessment_results_20250430_220729.json
|
| 14 |
+
2025-04-30 22:18:05,636 - INFO - Removed: gaia_memory_test_results_20250430_185256.json
|
| 15 |
+
2025-04-30 22:18:05,639 - INFO - Removed: gaia_memory_test_results_20250430_185420.json
|
| 16 |
+
2025-04-30 22:18:05,641 - INFO - Removed: gaia_memory_test_results_20250430_185453.json
|
| 17 |
+
2025-04-30 22:18:05,644 - INFO - Removed: gaia_memory_test_results_20250430_185550.json
|
| 18 |
+
2025-04-30 22:18:05,648 - INFO - Removed: gaia_memory_test_results_20250430_185641.json
|
| 19 |
+
2025-04-30 22:18:05,671 - INFO - Removed: cleanup_script.bat
|
| 20 |
+
2025-04-30 22:18:05,672 - INFO - Removed: check_env_vars.py
|
| 21 |
+
2025-04-30 22:18:05,675 - INFO - Removed: check_imports.py
|
| 22 |
+
2025-04-30 22:18:05,678 - INFO - Removed: check_serper_config.py
|
| 23 |
+
2025-04-30 22:18:05,679 - INFO - Removed: check_supabase_env.py
|
| 24 |
+
2025-04-30 22:18:05,681 - INFO - Removed: direct_config_check.py
|
| 25 |
+
2025-04-30 22:18:05,683 - INFO - Removed: direct_serper_test.py
|
| 26 |
+
2025-04-30 22:18:05,685 - INFO - Removed: minimal_serper_test.py
|
| 27 |
+
2025-04-30 22:18:05,686 - INFO - Removed: simple_serper_test.py
|
| 28 |
+
2025-04-30 22:18:05,689 - INFO - Removed: simple_serper_test_final.py
|
| 29 |
+
2025-04-30 22:18:05,693 - INFO - Removed: supabase_direct_test.py
|
| 30 |
+
2025-04-30 22:18:05,695 - INFO - Removed: supabase_dotenv_test.py
|
| 31 |
+
2025-04-30 22:18:05,697 - INFO - Removed: supabase_import_test.py
|
| 32 |
+
2025-04-30 22:18:05,698 - INFO - Removed: supabase_init_test.py
|
| 33 |
+
2025-04-30 22:18:05,700 - INFO - Removed: supabase_minimal_test.py
|
| 34 |
+
2025-04-30 22:18:05,702 - INFO - Removed: test_serper_direct.py
|
| 35 |
+
2025-04-30 22:18:05,704 - INFO - Removed: verify_python.py
|
| 36 |
+
2025-04-30 22:18:05,706 - INFO - Removed: run_gaia_assessment.py
|
| 37 |
+
2025-04-30 22:18:05,707 - INFO - Removed: run_gaia_assessment_simple.py
|
| 38 |
+
2025-04-30 22:18:05,709 - INFO - Removed: run_gaia_fixed.py
|
| 39 |
+
2025-04-30 22:18:05,713 - INFO - Removed: run_gaia_minimal.py
|
| 40 |
+
2025-04-30 22:18:05,714 - INFO - Removed: run_gaia_with_fix.py
|
| 41 |
+
2025-04-30 22:18:05,717 - INFO - Removed: setup_serper_env.py
|
| 42 |
+
2025-04-30 22:18:05,717 - INFO - Finding duplicate test files...
|
| 43 |
+
2025-04-30 22:18:05,720 - INFO - Found 7 duplicate test files
|
| 44 |
+
2025-04-30 22:18:05,720 - INFO - Duplicate tests for test_config.py:
|
| 45 |
+
2025-04-30 22:18:05,720 - INFO - - tests\test_config.py
|
| 46 |
+
2025-04-30 22:18:05,720 - INFO - - tests\test_config_simple.py
|
| 47 |
+
2025-04-30 22:18:05,721 - INFO - Keeping: tests\test_config.py
|
| 48 |
+
2025-04-30 22:18:05,721 - INFO - Removing: tests\test_config_simple.py
|
| 49 |
+
2025-04-30 22:18:05,722 - INFO - Removed: tests\test_config_simple.py
|
| 50 |
+
2025-04-30 22:18:05,722 - INFO - Duplicate tests for test_serper_api.py:
|
| 51 |
+
2025-04-30 22:18:05,723 - INFO - - tests\test_serper_api.py
|
| 52 |
+
2025-04-30 22:18:05,723 - INFO - - tests\test_serper_api_final.py
|
| 53 |
+
2025-04-30 22:18:05,723 - INFO - Keeping: tests\test_serper_api_final.py
|
| 54 |
+
2025-04-30 22:18:05,723 - INFO - Removing: tests\test_serper_api.py
|
| 55 |
+
2025-04-30 22:18:05,724 - INFO - Removed: tests\test_serper_api.py
|
| 56 |
+
2025-04-30 22:18:05,726 - INFO - Duplicate tests for test_supabase_connection.py:
|
| 57 |
+
2025-04-30 22:18:05,726 - INFO - - tests\test_supabase_connection.py
|
| 58 |
+
2025-04-30 22:18:05,726 - INFO - - tests\test_supabase_connection_simple.py
|
| 59 |
+
2025-04-30 22:18:05,727 - INFO - Keeping: tests\test_supabase_connection.py
|
| 60 |
+
2025-04-30 22:18:05,727 - INFO - Removing: tests\test_supabase_connection_simple.py
|
| 61 |
+
2025-04-30 22:18:05,728 - INFO - Removed: tests\test_supabase_connection_simple.py
|
| 62 |
+
2025-04-30 22:18:05,729 - INFO - Duplicate tests for test_supabase_tables.py:
|
| 63 |
+
2025-04-30 22:18:05,729 - INFO - - tests\test_supabase_tables.py
|
| 64 |
+
2025-04-30 22:18:05,729 - INFO - - tests\test_supabase_tables_comprehensive.py
|
| 65 |
+
2025-04-30 22:18:05,729 - INFO - - tests\test_supabase_tables_final.py
|
| 66 |
+
2025-04-30 22:18:05,729 - INFO - - tests\test_supabase_tables_production.py
|
| 67 |
+
2025-04-30 22:18:05,729 - INFO - - tests\test_supabase_tables_simple.py
|
| 68 |
+
2025-04-30 22:18:05,730 - INFO - Keeping: tests\test_supabase_tables_comprehensive.py
|
| 69 |
+
2025-04-30 22:18:05,730 - INFO - Removing: tests\test_supabase_tables.py, tests\test_supabase_tables_simple.py
|
| 70 |
+
2025-04-30 22:18:05,731 - INFO - Removed: tests\test_supabase_tables.py
|
| 71 |
+
2025-04-30 22:18:05,733 - INFO - Removed: tests\test_supabase_tables_simple.py
|
| 72 |
+
2025-04-30 22:18:05,733 - INFO - Checking for debug statements and commented-out code...
|
| 73 |
+
2025-04-30 22:18:05,803 - INFO - Found 248 instances of debug statements or commented-out code
|
| 74 |
+
2025-04-30 22:18:05,803 - INFO - Issues in agent\agent.py:
|
| 75 |
+
2025-04-30 22:18:05,803 - INFO - Line 72 (Commented code): # Set up verbose logging if enabled
|
| 76 |
+
2025-04-30 22:18:05,803 - INFO - Line 75 (Commented code): # Add console handler if not already present
|
| 77 |
+
2025-04-30 22:18:05,803 - INFO - Line 92 (Debug statement): logger.debug("Initializing memory components")
|
| 78 |
+
2025-04-30 22:18:05,803 - INFO - Line 98 (Commented code): # Create a unique session ID for this agent instance
|
| 79 |
+
2025-04-30 22:18:05,803 - INFO - Line 106 (Debug statement): logger.debug("Memory components initialized successfully")
|
| 80 |
+
2025-04-30 22:18:05,804 - INFO - Line 161 (Commented code): # Record end time and return the answer
|
| 81 |
+
2025-04-30 22:18:05,804 - INFO - Line 207 (Debug statement): logger.debug(f"Processing question: {question}")
|
| 82 |
+
2025-04-30 22:18:05,804 - INFO - Line 209 (Commented code): # Check if we have a cached answer
|
| 83 |
+
2025-04-30 22:18:05,804 - INFO - Line 215 (Commented code): # Check if we have a cached answer
|
| 84 |
+
2025-04-30 22:18:05,804 - INFO - Line 221 (Commented code): # Create a config for the graph
|
| 85 |
+
2025-04-30 22:18:05,804 - INFO - Line 237 (Commented code): # Fallback answer if no answer or error is provided
|
| 86 |
+
2025-04-30 22:18:05,804 - INFO - Line 240 (Commented code): # Store the answer in the result cache if available
|
| 87 |
+
2025-04-30 22:18:05,804 - INFO - Line 244 (Commented code): # Store the intermediate results in working memory if available
|
| 88 |
+
2025-04-30 22:18:05,804 - INFO - Line 264 (Commented code): # Add the question and answer to conversation memory if available
|
| 89 |
+
2025-04-30 22:18:05,804 - INFO - Line 291 (Commented code): # Get conversation history if available
|
| 90 |
+
2025-04-30 22:18:05,804 - INFO - Line 295 (Commented code): # Get cached results if available
|
| 91 |
+
2025-04-30 22:18:05,805 - INFO - Line 308 (Commented code): # Get intermediate results if available
|
| 92 |
+
2025-04-30 22:18:05,805 - INFO - Line 323 (Commented code): # Clear conversation memory if available
|
| 93 |
+
2025-04-30 22:18:05,805 - INFO - Line 327 (Commented code): # Clear result cache if available
|
| 94 |
+
2025-04-30 22:18:05,805 - INFO - Line 331 (Commented code): # Clear working memory if available
|
| 95 |
+
2025-04-30 22:18:05,805 - INFO - Issues in agent\config.py:
|
| 96 |
+
2025-04-30 22:18:05,805 - INFO - Line 20 (Commented code): # Try to import dotenv, but don't fail if it's not available
|
| 97 |
+
2025-04-30 22:18:05,805 - INFO - Line 23 (Commented code): # Load environment variables from .env file if it exists
|
| 98 |
+
2025-04-30 22:18:05,805 - INFO - Line 28 (Debug statement): print("Warning: python-dotenv not installed. Environment variables will not be loaded from .env file.")
|
| 99 |
+
2025-04-30 22:18:05,806 - INFO - Line 30 (Commented code): # API Keys and Credentials (kept as environment variables)
|
| 100 |
+
2025-04-30 22:18:05,806 - INFO - Line 37 (Commented code): # Supabase Configuration (partially hardcoded)
|
| 101 |
+
2025-04-30 22:18:05,806 - INFO - Line 42 (Commented code): # API Endpoints (hardcoded)
|
| 102 |
+
2025-04-30 22:18:05,806 - INFO - Line 48 (Commented code): # Model Configuration (hardcoded with updated models)
|
| 103 |
+
2025-04-30 22:18:05,806 - INFO - Line 57 (Commented code): # Tool Parameters (hardcoded)
|
| 104 |
+
2025-04-30 22:18:05,806 - INFO - Line 69 (Commented code): # Memory Settings (hardcoded)
|
| 105 |
+
2025-04-30 22:18:05,806 - INFO - Line 77 (Commented code): # Agent Settings (hardcoded)
|
| 106 |
+
2025-04-30 22:18:05,806 - INFO - Line 85 (Commented code): # Logging Configuration (hardcoded)
|
| 107 |
+
2025-04-30 22:18:05,807 - INFO - Line 90 (Commented code): # Multimodal Settings (hardcoded)
|
| 108 |
+
2025-04-30 22:18:05,807 - INFO - Line 95 (Commented code): # Web Browsing Settings (hardcoded)
|
| 109 |
+
2025-04-30 22:18:05,807 - INFO - Line 101 (Commented code): # Helper functions for configuration
|
| 110 |
+
2025-04-30 22:18:05,807 - INFO - Issues in agent\graph.py:
|
| 111 |
+
2025-04-30 22:18:05,807 - INFO - Line 30 (Commented code): # Type definitions for state
|
| 112 |
+
2025-04-30 22:18:05,807 - INFO - Line 75 (Debug statement): logger.debug(f"Analyzing question: {state['question']}")
|
| 113 |
+
2025-04-30 22:18:05,807 - INFO - Line 117 (Commented code): # Parse the analysis (in a real implementation, use a proper JSON parser)
|
| 114 |
+
2025-04-30 22:18:05,807 - INFO - Line 118 (Commented code): # This is a simplified version for demonstration
|
| 115 |
+
2025-04-30 22:18:05,807 - INFO - Line 126 (Debug statement): logger.debug(f"Question analysis completed: {analysis}")
|
| 116 |
+
2025-04-30 22:18:05,807 - INFO - Line 148 (Debug statement): logger.debug("Creating plan based on question analysis")
|
| 117 |
+
2025-04-30 22:18:05,808 - INFO - Line 150 (Commented code): # If there's an error, return the state unchanged
|
| 118 |
+
2025-04-30 22:18:05,808 - INFO - Line 205 (Commented code): # Parse the plan (in a real implementation, use a proper JSON parser)
|
| 119 |
+
2025-04-30 22:18:05,808 - INFO - Line 222 (Debug statement): logger.debug(f"Plan created with {len(plan)} steps")
|
| 120 |
+
2025-04-30 22:18:05,809 - INFO - Line 244 (Debug statement): logger.debug(f"Selecting tool for step {state['current_step'] + 1}")
|
| 121 |
+
2025-04-30 22:18:05,809 - INFO - Line 246 (Commented code): # If there's an error, return END
|
| 122 |
+
2025-04-30 22:18:05,809 - INFO - Line 281 (Commented code): # If there's an error, return the state unchanged
|
| 123 |
+
2025-04-30 22:18:05,809 - INFO - Line 290 (Debug statement): logger.debug(f"Executing tool {tool_name} for step {current_step['step_number']}")
|
| 124 |
+
2025-04-30 22:18:05,809 - INFO - Line 315 (Debug statement): logger.debug(f"Tool {tool_name} executed successfully")
|
| 125 |
+
2025-04-30 22:18:05,810 - INFO - Line 350 (Debug statement): logger.debug("Formulating answer based on tool results")
|
| 126 |
+
2025-04-30 22:18:05,810 - INFO - Line 352 (Commented code): # If there's an error, return the state unchanged
|
| 127 |
+
2025-04-30 22:18:05,810 - INFO - Line 409 (Debug statement): logger.debug(f"Answer formulated: {answer.strip()}")
|
| 128 |
+
2025-04-30 22:18:05,810 - INFO - Line 431 (Commented code): # If there's an error, check if we should retry
|
| 129 |
+
2025-04-30 22:18:05,810 - INFO - Issues in agent\tool_registry.py:
|
| 130 |
+
2025-04-30 22:18:05,810 - INFO - Line 34 (Debug statement): logger.debug("Initialized empty tool registry")
|
| 131 |
+
2025-04-30 22:18:05,811 - INFO - Line 45 (Debug statement): logger.debug(f"Registered tool: {name}")
|
| 132 |
+
2025-04-30 22:18:05,811 - INFO - Line 89 (Debug statement): logger.debug(f"Executing tool: {name} with args: {kwargs}")
|
| 133 |
+
2025-04-30 22:18:05,811 - INFO - Line 147 (Commented code): # Register DuckDuckGo search tool (no API key required)
|
| 134 |
+
2025-04-30 22:18:05,811 - INFO - Line 154 (Commented code): # Register Serper search tool if API key is available
|
| 135 |
+
2025-04-30 22:18:05,811 - INFO - Line 165 (Commented code): # Register Perplexity tool if API key is available
|
| 136 |
+
2025-04-30 22:18:05,811 - INFO - Line 176 (Commented code): # Register arXiv tool (no API key required)
|
| 137 |
+
2025-04-30 22:18:05,812 - INFO - Line 180 (Commented code): # Register the same tool instance for different operations
|
| 138 |
+
2025-04-30 22:18:05,812 - INFO - Line 207 (Commented code): # Try DuckDuckGo first (no API key required)
|
| 139 |
+
2025-04-30 22:18:05,812 - INFO - Line 334 (Debug statement): print(f"Available tools: {registry.list_tools()}")
|
| 140 |
+
2025-04-30 22:18:05,812 - INFO - Line 340 (Debug statement): print(f"Robust search using {result['provider']} found {len(result['results'])} results")
|
| 141 |
+
2025-04-30 22:18:05,812 - INFO - Line 342 (Debug statement): print(f"Robust search failed: {str(e)}")
|
| 142 |
+
2025-04-30 22:18:05,812 - INFO - Line 348 (Debug statement): print(f"Merged search found {len(result['merged_results'])} results")
|
| 143 |
+
2025-04-30 22:18:05,813 - INFO - Line 350 (Debug statement): print(f"Perplexity context: {result['perplexity_context'][:100]}...")
|
| 144 |
+
2025-04-30 22:18:05,813 - INFO - Line 352 (Debug statement): print(f"arXiv papers: {len(result['arxiv_context'])}")
|
| 145 |
+
2025-04-30 22:18:05,813 - INFO - Line 354 (Debug statement): print(f"Merged search failed: {str(e)}")
|
| 146 |
+
2025-04-30 22:18:05,813 - INFO - Issues in memory\fix_supabase_tables.py:
|
| 147 |
+
2025-04-30 22:18:05,813 - INFO - Line 55 (Commented code): # Check if the client is initialized
|
| 148 |
+
2025-04-30 22:18:05,813 - INFO - Line 71 (Commented code): # Check if the table exists
|
| 149 |
+
2025-04-30 22:18:05,813 - INFO - Line 79 (Commented code): # SQL for creating the table
|
| 150 |
+
2025-04-30 22:18:05,814 - INFO - Line 130 (Commented code): # Trim cache if it's too large
|
| 151 |
+
2025-04-30 22:18:05,814 - INFO - Line 141 (Commented code): # Store in Supabase if initialized
|
| 152 |
+
2025-04-30 22:18:05,814 - INFO - Line 150 (Debug statement): logger.debug(f"Stored entry in table {current_table}: {key}")
|
| 153 |
+
2025-04-30 22:18:05,814 - INFO - Line 170 (Commented code): # Check if the entry has expired
|
| 154 |
+
2025-04-30 22:18:05,814 - INFO - Line 187 (Commented code): # Check if any entries were found
|
| 155 |
+
2025-04-30 22:18:05,814 - INFO - Line 196 (Commented code): # Check if the entry has expired
|
| 156 |
+
2025-04-30 22:18:05,814 - INFO - Line 208 (Debug statement): logger.debug(f"Retrieved entry from table {current_table}: {key}")
|
| 157 |
+
2025-04-30 22:18:05,814 - INFO - Line 227 (Commented code): # Remove from Supabase if initialized
|
| 158 |
+
2025-04-30 22:18:05,814 - INFO - Line 233 (Debug statement): logger.debug(f"Deleted entry from table {current_table}: {key}")
|
| 159 |
+
2025-04-30 22:18:05,814 - INFO - Line 256 (Commented code): # Get keys from Supabase if initialized
|
| 160 |
+
2025-04-30 22:18:05,815 - INFO - Line 262 (Commented code): # Filter by prefix if provided
|
| 161 |
+
2025-04-30 22:18:05,815 - INFO - Line 278 (Debug statement): logger.debug(f"Listed keys from table {current_table}: {len(keys)} keys")
|
| 162 |
+
2025-04-30 22:18:05,815 - INFO - Line 350 (Commented code): # Create a key for the message
|
| 163 |
+
2025-04-30 22:18:05,815 - INFO - Line 360 (Commented code): # Add metadata if provided
|
| 164 |
+
2025-04-30 22:18:05,816 - INFO - Line 384 (Commented code): # Filter by before/after if provided
|
| 165 |
+
2025-04-30 22:18:05,816 - INFO - Line 391 (Commented code): # Limit the number of messages if provided
|
| 166 |
+
2025-04-30 22:18:05,816 - INFO - Line 526 (Commented code): # Check if any entries were found
|
| 167 |
+
2025-04-30 22:18:05,816 - INFO - Line 546 (Debug statement): print("\nFixing Supabase Tables for GAIA Agent")
|
| 168 |
+
2025-04-30 22:18:05,816 - INFO - Line 547 (Debug statement): print("====================================\n")
|
| 169 |
+
2025-04-30 22:18:05,837 - INFO - Line 562 (Debug statement): print("All Supabase tables are now being used correctly.")
|
| 170 |
+
2025-04-30 22:18:05,839 - INFO - Line 566 (Debug statement): print("Please check the logs for more information")
|
| 171 |
+
2025-04-30 22:18:05,839 - INFO - Issues in memory\simplified_memory_fix.py:
|
| 172 |
+
2025-04-30 22:18:05,839 - INFO - Line 50 (Commented code): # Check if the client is initialized
|
| 173 |
+
2025-04-30 22:18:05,840 - INFO - Line 59 (Commented code): # Check if the table exists
|
| 174 |
+
2025-04-30 22:18:05,840 - INFO - Line 68 (Commented code): # SQL for creating the table
|
| 175 |
+
2025-04-30 22:18:05,840 - INFO - Line 118 (Commented code): # Trim cache if it's too large
|
| 176 |
+
2025-04-30 22:18:05,840 - INFO - Line 129 (Commented code): # Store in Supabase if initialized
|
| 177 |
+
2025-04-30 22:18:05,840 - INFO - Line 138 (Debug statement): logger.debug(f"Stored entry in table {current_table}: {key}")
|
| 178 |
+
2025-04-30 22:18:05,840 - INFO - Line 158 (Commented code): # Check if the entry has expired
|
| 179 |
+
2025-04-30 22:18:05,840 - INFO - Line 175 (Commented code): # Check if any entries were found
|
| 180 |
+
2025-04-30 22:18:05,840 - INFO - Line 184 (Commented code): # Check if the entry has expired
|
| 181 |
+
2025-04-30 22:18:05,841 - INFO - Line 196 (Debug statement): logger.debug(f"Retrieved entry from table {current_table}: {key}")
|
| 182 |
+
2025-04-30 22:18:05,841 - INFO - Line 215 (Commented code): # Remove from Supabase if initialized
|
| 183 |
+
2025-04-30 22:18:05,841 - INFO - Line 221 (Debug statement): logger.debug(f"Deleted entry from table {current_table}: {key}")
|
| 184 |
+
2025-04-30 22:18:05,841 - INFO - Line 244 (Commented code): # Get keys from Supabase if initialized
|
| 185 |
+
2025-04-30 22:18:05,841 - INFO - Line 250 (Commented code): # Filter by prefix if provided
|
| 186 |
+
2025-04-30 22:18:05,841 - INFO - Line 266 (Debug statement): logger.debug(f"Listed keys from table {current_table}: {len(keys)} keys")
|
| 187 |
+
2025-04-30 22:18:05,842 - INFO - Line 388 (Commented code): # Check if any entries were found
|
| 188 |
+
2025-04-30 22:18:05,842 - INFO - Line 408 (Debug statement): print("\nSimplified Fix for Supabase Tables in GAIA Agent")
|
| 189 |
+
2025-04-30 22:18:05,842 - INFO - Line 409 (Debug statement): print("==============================================\n")
|
| 190 |
+
2025-04-30 22:18:05,843 - INFO - Line 411 (Commented code): # Create the working memory table if it doesn't exist
|
| 191 |
+
2025-04-30 22:18:05,845 - INFO - Line 424 (Debug statement): print("The working memory table is now being used correctly.")
|
| 192 |
+
2025-04-30 22:18:05,846 - INFO - Line 425 (Debug statement): print("This should be sufficient for the GAIA benchmark test.")
|
| 193 |
+
2025-04-30 22:18:05,848 - INFO - Line 429 (Debug statement): print("Please check the logs for more information")
|
| 194 |
+
2025-04-30 22:18:05,848 - INFO - Issues in memory\supabase_memory.py:
|
| 195 |
+
2025-04-30 22:18:05,849 - INFO - Line 15 (Commented code): # Try to import supabase, but don't fail if it's not available
|
| 196 |
+
2025-04-30 22:18:05,849 - INFO - Line 19 (Commented code): # Define dummy types for type checking
|
| 197 |
+
2025-04-30 22:18:05,849 - INFO - Line 60 (Commented code): # Set expiration time if TTL is provided
|
| 198 |
+
2025-04-30 22:18:05,849 - INFO - Line 147 (Commented code): # Check if the main table exists
|
| 199 |
+
2025-04-30 22:18:05,849 - INFO - Line 181 (Commented code): # Check if the table exists by querying it
|
| 200 |
+
2025-04-30 22:18:05,850 - INFO - Line 183 (Debug statement): logger.debug(f"Table {actual_table} exists")
|
| 201 |
+
2025-04-30 22:18:05,850 - INFO - Line 249 (Commented code): # Trim cache if it's too large
|
| 202 |
+
2025-04-30 22:18:05,850 - INFO - Line 260 (Commented code): # Store in Supabase if initialized
|
| 203 |
+
2025-04-30 22:18:05,850 - INFO - Line 300 (Commented code): # Check if the entry has expired
|
| 204 |
+
2025-04-30 22:18:05,850 - INFO - Line 316 (Commented code): # Check if any entries were found
|
| 205 |
+
2025-04-30 22:18:05,850 - INFO - Line 324 (Commented code): # Check if the entry has expired
|
| 206 |
+
2025-04-30 22:18:05,851 - INFO - Line 359 (Commented code): # Remove from Supabase if initialized
|
| 207 |
+
2025-04-30 22:18:05,851 - INFO - Line 388 (Commented code): # Clear Supabase if initialized
|
| 208 |
+
2025-04-30 22:18:05,851 - INFO - Line 422 (Commented code): # Get keys from Supabase if initialized
|
| 209 |
+
2025-04-30 22:18:05,851 - INFO - Line 428 (Commented code): # Filter by prefix if provided
|
| 210 |
+
2025-04-30 22:18:05,851 - INFO - Line 484 (Commented code): # Create a key for the message
|
| 211 |
+
2025-04-30 22:18:05,851 - INFO - Line 494 (Commented code): # Add metadata if provided
|
| 212 |
+
2025-04-30 22:18:05,851 - INFO - Line 531 (Commented code): # Filter by before/after if provided
|
| 213 |
+
2025-04-30 22:18:05,851 - INFO - Line 538 (Commented code): # Limit the number of messages if provided
|
| 214 |
+
2025-04-30 22:18:05,852 - INFO - Issues in memory\supabase_memory_patch.py:
|
| 215 |
+
2025-04-30 22:18:05,852 - INFO - Line 60 (Commented code): # Check if the client is initialized
|
| 216 |
+
2025-04-30 22:18:05,852 - INFO - Line 73 (Commented code): # Check if the tables exist
|
| 217 |
+
2025-04-30 22:18:05,852 - INFO - Line 90 (Commented code): # SQL for creating the table
|
| 218 |
+
2025-04-30 22:18:05,853 - INFO - Line 151 (Debug statement): print("All tables are now properly utilized:")
|
| 219 |
+
2025-04-30 22:18:05,854 - INFO - Line 152 (Debug statement): print("- gaia_memory: Main memory table")
|
| 220 |
+
2025-04-30 22:18:05,854 - INFO - Line 153 (Debug statement): print("- gaia_memory_conversations: Conversation history table")
|
| 221 |
+
2025-04-30 22:18:05,854 - INFO - Line 154 (Debug statement): print("- gaia_memory_cache: Result cache table")
|
| 222 |
+
2025-04-30 22:18:05,854 - INFO - Line 155 (Debug statement): print("- gaia_memory_working: Working memory table")
|
| 223 |
+
2025-04-30 22:18:05,856 - INFO - Line 159 (Debug statement): print("Please check the logs for more information")
|
| 224 |
+
2025-04-30 22:18:05,856 - INFO - Issues in tools\arxiv_tool.py:
|
| 225 |
+
2025-04-30 22:18:05,856 - INFO - Line 60 (Debug statement): logger.debug(f"Searching arXiv for: {query}")
|
| 226 |
+
2025-04-30 22:18:05,856 - INFO - Line 82 (Debug statement): logger.debug(f"Found {len(results)} results from arXiv")
|
| 227 |
+
2025-04-30 22:18:05,856 - INFO - Line 134 (Debug statement): logger.debug(f"Getting arXiv paper with ID: {paper_id}")
|
| 228 |
+
2025-04-30 22:18:05,856 - INFO - Line 143 (Commented code): # Create a search for the specific paper
|
| 229 |
+
2025-04-30 22:18:05,856 - INFO - Line 201 (Debug statement): logger.debug(f"Searching arXiv for papers in category: {category}")
|
| 230 |
+
2025-04-30 22:18:05,856 - INFO - Line 203 (Commented code): # Create a query for the category
|
| 231 |
+
2025-04-30 22:18:05,856 - INFO - Line 222 (Commented code): # Search for papers
|
| 232 |
+
2025-04-30 22:18:05,857 - INFO - Line 225 (Debug statement): print(f"Found {len(results)} papers")
|
| 233 |
+
2025-04-30 22:18:05,857 - INFO - Line 227 (Debug statement): print(f"\nPaper {i+1}:")
|
| 234 |
+
2025-04-30 22:18:05,857 - INFO - Line 228 (Debug statement): print(f"Title: {paper['title']}")
|
| 235 |
+
2025-04-30 22:18:05,857 - INFO - Line 229 (Debug statement): print(f"Authors: {paper['authors']}")
|
| 236 |
+
2025-04-30 22:18:05,857 - INFO - Line 230 (Debug statement): print(f"Published: {paper['published']}")
|
| 237 |
+
2025-04-30 22:18:05,857 - INFO - Line 231 (Debug statement): print(f"URL: {paper['url']}")
|
| 238 |
+
2025-04-30 22:18:05,857 - INFO - Line 232 (Debug statement): print(f"Summary: {paper['summary'][:200]}...")
|
| 239 |
+
2025-04-30 22:18:05,857 - INFO - Line 234 (Debug statement): print(f"Error: {str(e)}")
|
| 240 |
+
2025-04-30 22:18:05,857 - INFO - Issues in tools\multimodal_tools.py:
|
| 241 |
+
2025-04-30 22:18:05,858 - INFO - Line 81 (Debug statement): logger.debug(f"Analyzing image: {image_path}")
|
| 242 |
+
2025-04-30 22:18:05,858 - INFO - Line 126 (Debug statement): logger.debug("Image analysis completed successfully")
|
| 243 |
+
2025-04-30 22:18:05,858 - INFO - Line 129 (Commented code): # If the result is not valid JSON, return it as plain text
|
| 244 |
+
2025-04-30 22:18:05,858 - INFO - Line 157 (Debug statement): logger.debug(f"Detecting objects in image: {image_path}")
|
| 245 |
+
2025-04-30 22:18:05,858 - INFO - Line 206 (Debug statement): logger.debug(f"Object detection completed, found {parsed_result.get('object_count', 0)} objects")
|
| 246 |
+
2025-04-30 22:18:05,859 - INFO - Line 255 (Debug statement): logger.debug(f"Interpreting chart: {chart_path}")
|
| 247 |
+
2025-04-30 22:18:05,859 - INFO - Line 306 (Debug statement): logger.debug(f"Chart interpretation completed: {parsed_result.get('chart_type', 'unknown')} chart")
|
| 248 |
+
2025-04-30 22:18:05,859 - INFO - Line 338 (Debug statement): logger.debug(f"Extracting data from chart: {chart_path}")
|
| 249 |
+
2025-04-30 22:18:05,859 - INFO - Line 386 (Debug statement): logger.debug(f"Chart data extraction completed with {len(parsed_result.get('data', []))} data points")
|
| 250 |
+
2025-04-30 22:18:05,859 - INFO - Line 422 (Commented code): # Check for required dependencies
|
| 251 |
+
2025-04-30 22:18:05,860 - INFO - Line 443 (Debug statement): logger.debug(f"Parsing document: {document_path}")
|
| 252 |
+
2025-04-30 22:18:05,860 - INFO - Line 468 (Commented code): # Truncate if too long
|
| 253 |
+
2025-04-30 22:18:05,860 - INFO - Line 504 (Debug statement): logger.debug(f"Extracting structured data from document: {document_path}")
|
| 254 |
+
2025-04-30 22:18:05,860 - INFO - Line 536 (Debug statement): logger.debug("Structured data extraction completed successfully")
|
| 255 |
+
2025-04-30 22:18:05,860 - INFO - Issues in tools\perplexity_tool.py:
|
| 256 |
+
2025-04-30 22:18:05,860 - INFO - Line 20 (Commented code): # Set up basic logging if not already configured
|
| 257 |
+
2025-04-30 22:18:05,860 - INFO - Line 40 (Commented code): # Get API key from config or environment (only configuration from environment)
|
| 258 |
+
2025-04-30 22:18:05,860 - INFO - Line 45 (Commented code): # Hardcoded values for API URL and model
|
| 259 |
+
2025-04-30 22:18:05,860 - INFO - Line 50 (Commented code): # Endpoint for chat completions
|
| 260 |
+
2025-04-30 22:18:05,861 - INFO - Line 53 (Debug statement): logger.debug(f"Initialized Perplexity tool with model {self.model}")
|
| 261 |
+
2025-04-30 22:18:05,861 - INFO - Line 73 (Debug statement): logger.debug(f"Querying Perplexity API: {question[:50]}...")
|
| 262 |
+
2025-04-30 22:18:05,861 - INFO - Line 82 (Commented code): # Add system prompt if provided
|
| 263 |
+
2025-04-30 22:18:05,861 - INFO - Line 134 (Debug statement): logger.debug(f"Perplexity API query successful, received {len(content) if content else 0} characters")
|
| 264 |
+
2025-04-30 22:18:05,862 - INFO - Line 169 (Debug statement): logger.debug(f"Searching with Perplexity API: {query[:50]}...")
|
| 265 |
+
2025-04-30 22:18:05,862 - INFO - Issues in tools\reasoning_tools.py:
|
| 266 |
+
2025-04-30 22:18:05,862 - INFO - Line 65 (Debug statement): logger.debug(f"Performing step-by-step reasoning on: {question}")
|
| 267 |
+
2025-04-30 22:18:05,862 - INFO - Line 93 (Commented code): # Add context if provided
|
| 268 |
+
2025-04-30 22:18:05,862 - INFO - Line 111 (Debug statement): logger.debug(f"Reasoning completed with {len(parsed_result.get('steps', []))} steps")
|
| 269 |
+
2025-04-30 22:18:05,862 - INFO - Line 134 (Debug statement): logger.debug(f"Performing chain-of-thought reasoning on: {question}")
|
| 270 |
+
2025-04-30 22:18:05,862 - INFO - Line 148 (Commented code): # Add context if provided
|
| 271 |
+
2025-04-30 22:18:05,862 - INFO - Line 163 (Debug statement): logger.debug("Chain-of-thought reasoning completed")
|
| 272 |
+
2025-04-30 22:18:05,862 - INFO - Line 203 (Debug statement): logger.debug(f"Calculating expression: {expression}")
|
| 273 |
+
2025-04-30 22:18:05,863 - INFO - Line 209 (Commented code): # Evaluate using sympy for symbolic math
|
| 274 |
+
2025-04-30 22:18:05,863 - INFO - Line 241 (Debug statement): logger.debug(f"Solving equation: {equation} for {variable}")
|
| 275 |
+
2025-04-30 22:18:05,863 - INFO - Line 262 (Commented code): # Convert to float or int if possible
|
| 276 |
+
2025-04-30 22:18:05,863 - INFO - Line 317 (Commented code): # Only replace if it's a whole word (not part of another word)
|
| 277 |
+
2025-04-30 22:18:05,863 - INFO - Line 354 (Debug statement): logger.debug(f"Verifying claim: {claim}")
|
| 278 |
+
2025-04-30 22:18:05,863 - INFO - Line 395 (Debug statement): logger.debug(f"Verification completed: {parsed_result.get('verification_result', 'unknown')}")
|
| 279 |
+
2025-04-30 22:18:05,863 - INFO - Line 418 (Debug statement): logger.debug(f"Comparing claims: '{claim1}' and '{claim2}'")
|
| 280 |
+
2025-04-30 22:18:05,863 - INFO - Line 455 (Debug statement): logger.debug(f"Comparison completed: {parsed_result.get('relationship', 'unknown')}")
|
| 281 |
+
2025-04-30 22:18:05,863 - INFO - Issues in tools\web_tools.py:
|
| 282 |
+
2025-04-30 22:18:05,864 - INFO - Line 124 (Debug statement): logger.debug(f"Searching DuckDuckGo for: {query}")
|
| 283 |
+
2025-04-30 22:18:05,864 - INFO - Line 137 (Debug statement): logger.debug(f"Found {len(results)} results from DuckDuckGo")
|
| 284 |
+
2025-04-30 22:18:05,864 - INFO - Line 187 (Debug statement): logger.debug(f"Searching Serper for: {query}")
|
| 285 |
+
2025-04-30 22:18:05,864 - INFO - Line 217 (Debug statement): logger.debug(f"Found {len(organic_results)} results from Serper")
|
| 286 |
+
2025-04-30 22:18:05,864 - INFO - Line 270 (Debug statement): logger.debug(f"Extracting content from: {url}")
|
| 287 |
+
2025-04-30 22:18:05,864 - INFO - Line 306 (Commented code): # Truncate if too long
|
| 288 |
+
2025-04-30 22:18:05,864 - INFO - Line 392 (Debug statement): logger.debug(f"Following links from: {url}")
|
| 289 |
+
2025-04-30 22:18:05,864 - INFO - Line 401 (Commented code): # Filter links by pattern if provided
|
| 290 |
+
2025-04-30 22:18:05,864 - INFO - Issues in tools\__init__.py:
|
| 291 |
+
2025-04-30 22:18:05,865 - INFO - Line 129 (Debug statement): logger.debug(f"Registered tool: {metadata.name} in category {metadata.category}")
|
| 292 |
+
2025-04-30 22:18:05,865 - INFO - Line 189 (Commented code): # Check for direct tool name match
|
| 293 |
+
2025-04-30 22:18:05,865 - INFO - Line 194 (Commented code): # Check for keyword matches
|
| 294 |
+
2025-04-30 22:18:05,865 - INFO - Line 659 (Commented code): # Convenience functions for accessing tools
|
| 295 |
+
2025-04-30 22:18:05,865 - INFO - Issues in utils\formatting.py:
|
| 296 |
+
2025-04-30 22:18:05,865 - INFO - Line 38 (Debug statement): logger.debug(f"Extracting answer from response (expected format: {expected_format})")
|
| 297 |
+
2025-04-30 22:18:05,865 - INFO - Line 40 (Commented code): # If the response is already concise, return it directly
|
| 298 |
+
2025-04-30 22:18:05,865 - INFO - Line 44 (Commented code): # Look for explicit answer indicators
|
| 299 |
+
2025-04-30 22:18:05,865 - INFO - Line 75 (Commented code): # Default: return the last sentence as the answer
|
| 300 |
+
2025-04-30 22:18:05,866 - INFO - Line 92 (Commented code): # Look for numbers with optional decimal points and commas
|
| 301 |
+
2025-04-30 22:18:05,866 - INFO - Line 108 (Commented code): # If no answer-indicating phrase, find all numbers and return the last one
|
| 302 |
+
2025-04-30 22:18:05,866 - INFO - Line 147 (Commented code): # If no answer-indicating phrase, find all dates and return the first one
|
| 303 |
+
2025-04-30 22:18:05,866 - INFO - Line 167 (Commented code): # Check for yes/no indicators at the beginning of the text or after answer indicators
|
| 304 |
+
2025-04-30 22:18:05,866 - INFO - Line 198 (Commented code): # If no clear yes/no, look for sentiment
|
| 305 |
+
2025-04-30 22:18:05,866 - INFO - Line 213 (Commented code): # Default to "Unknown" if can't determine
|
| 306 |
+
2025-04-30 22:18:05,866 - INFO - Line 226 (Commented code): # Look for explicit list indicators
|
| 307 |
+
2025-04-30 22:18:05,866 - INFO - Line 244 (Commented code): # Look for bullet points or numbered lists
|
| 308 |
+
2025-04-30 22:18:05,866 - INFO - Line 250 (Commented code): # Look for any comma-separated sequence
|
| 309 |
+
2025-04-30 22:18:05,866 - INFO - Line 268 (Commented code): # Look for entity indicators
|
| 310 |
+
2025-04-30 22:18:05,866 - INFO - Line 281 (Commented code): # Look for capitalized proper nouns
|
| 311 |
+
2025-04-30 22:18:05,867 - INFO - Line 306 (Commented code): # Look for JSON blocks
|
| 312 |
+
2025-04-30 22:18:05,867 - INFO - Line 318 (Commented code): # Look for JSON without code blocks
|
| 313 |
+
2025-04-30 22:18:05,867 - INFO - Line 341 (Debug statement): logger.debug(f"Formatting answer to {format_type} format")
|
| 314 |
+
2025-04-30 22:18:05,867 - INFO - Line 401 (Commented code): # Default: return as is
|
| 315 |
+
2025-04-30 22:18:05,867 - INFO - Line 415 (Debug statement): logger.debug(f"Validating answer format (expected: {expected_format})")
|
| 316 |
+
2025-04-30 22:18:05,867 - INFO - Line 435 (Commented code): # Validate date format (simple check)
|
| 317 |
+
2025-04-30 22:18:05,867 - INFO - Line 469 (Commented code): # Validate entity format (simple check for proper noun)
|
| 318 |
+
2025-04-30 22:18:05,867 - INFO - Line 502 (Debug statement): logger.debug(f"Processing answer (expected format: {expected_format})")
|
| 319 |
+
2025-04-30 22:18:05,867 - INFO - Line 504 (Commented code): # Default to text format if none specified
|
| 320 |
+
2025-04-30 22:18:05,867 - INFO - Issues in utils\parsing.py:
|
| 321 |
+
2025-04-30 22:18:05,868 - INFO - Line 34 (Debug statement): logger.debug(f"Extracting key information from question: {question}")
|
| 322 |
+
2025-04-30 22:18:05,868 - INFO - Line 47 (Commented code): # Extract entities (proper nouns, potentially)
|
| 323 |
+
2025-04-30 22:18:05,868 - INFO - Line 52 (Commented code): # Extract keywords (important nouns, verbs, adjectives)
|
| 324 |
+
2025-04-30 22:18:05,868 - INFO - Line 143 (Debug statement): logger.debug(f"Identifying required tools for question: {question}")
|
| 325 |
+
2025-04-30 22:18:05,868 - INFO - Line 197 (Debug statement): logger.debug(f"Determining complexity for question: {question}")
|
| 326 |
+
2025-04-30 22:18:05,868 - INFO - Line 293 (Debug statement): logger.debug(f"Parsing question: {question}")
|
| 327 |
+
2025-04-30 22:18:05,868 - INFO - Issues in utils\__init__.py:
|
| 328 |
+
2025-04-30 22:18:05,868 - INFO - Line 96 (Commented code): # Check for number format
|
| 329 |
+
2025-04-30 22:18:05,868 - INFO - Line 100 (Commented code): # Check for date format
|
| 330 |
+
2025-04-30 22:18:05,868 - INFO - Line 104 (Commented code): # Check for boolean format
|
| 331 |
+
2025-04-30 22:18:05,869 - INFO - Line 109 (Commented code): # Check for list format
|
| 332 |
+
2025-04-30 22:18:05,869 - INFO - Line 113 (Commented code): # Check for entity format
|
| 333 |
+
2025-04-30 22:18:05,869 - INFO - Checking for potential hardcoded credentials...
|
| 334 |
+
2025-04-30 22:18:05,990 - INFO - No potential hardcoded credentials found
|
| 335 |
+
2025-04-30 22:18:05,990 - INFO -
|
| 336 |
+
Cleanup Summary:
|
| 337 |
+
2025-04-30 22:18:05,991 - INFO - - Temporary files to remove: 39
|
| 338 |
+
2025-04-30 22:18:05,991 - INFO - - Duplicate test files to remove: 7
|
| 339 |
+
2025-04-30 22:18:05,991 - INFO - - Files with debug statements or commented code: 17
|
| 340 |
+
2025-04-30 22:18:05,992 - INFO - - Files with potential hardcoded credentials: 0
|
create_env_and_test.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Create .env File and Test Supabase Connection
|
| 3 |
+
|
| 4 |
+
This script creates a .env file with hardcoded values and then tests the connection to Supabase.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
def create_env_file(api_key):
|
| 12 |
+
"""
|
| 13 |
+
Create a .env file with the provided API key.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
api_key: The Supabase API key
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
env_content = f"""
|
| 20 |
+
# Supabase Configuration
|
| 21 |
+
SUPABASE_URL=https://tjamxhvvtnypbadvrkjq.supabase.co
|
| 22 |
+
SUPABASE_KEY={api_key}
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
with open(".env", "w") as f:
|
| 26 |
+
f.write(env_content)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_supabase():
|
| 30 |
+
"""Test the connection to Supabase."""
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
from supabase import create_client
|
| 34 |
+
from dotenv import load_dotenv
|
| 35 |
+
|
| 36 |
+
load_dotenv(override=True)
|
| 37 |
+
|
| 38 |
+
# Get Supabase URL and key
|
| 39 |
+
supabase_url = os.getenv("SUPABASE_URL")
|
| 40 |
+
supabase_key = os.getenv("SUPABASE_KEY")
|
| 41 |
+
|
| 42 |
+
if supabase_key:
|
| 43 |
+
masked_key = supabase_key[:4] + "*" * (len(supabase_key) - 8) + supabase_key[-4:] if len(supabase_key) > 8 else "****"
|
| 44 |
+
else:
|
| 45 |
+
return False
|
| 46 |
+
|
| 47 |
+
client = create_client(supabase_url, supabase_key)
|
| 48 |
+
|
| 49 |
+
result = client.table("test_connection").select("*").limit(1).execute()
|
| 50 |
+
|
| 51 |
+
return True
|
| 52 |
+
except Exception as e:
|
| 53 |
+
import traceback
|
| 54 |
+
traceback.print_exc()
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
def main():
|
| 58 |
+
"""Main function."""
|
| 59 |
+
|
| 60 |
+
api_key = input("> ").strip()
|
| 61 |
+
|
| 62 |
+
if not api_key:
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
create_env_file(api_key)
|
| 66 |
+
|
| 67 |
+
time.sleep(1)
|
| 68 |
+
|
| 69 |
+
# Test Supabase connection
|
| 70 |
+
success = test_supabase()
|
| 71 |
+
|
| 72 |
+
if success:
|
| 73 |
+
else:
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
deploy_to_hf.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Simplified Git Deployment Script for Hugging Face Spaces
|
| 3 |
+
|
| 4 |
+
This script handles the git operations required to deploy to a Hugging Face Space.
|
| 5 |
+
It assumes you have Git installed and have already configured git authentication.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
python deploy_to_hf.py
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
# Hugging Face Space details
|
| 16 |
+
SPACE_ID = "JoachimVC/Final_Assignment_Template"
|
| 17 |
+
REPO_URL = f"https://huggingface.co/spaces/{SPACE_ID}"
|
| 18 |
+
|
| 19 |
+
def run_command(cmd, silent=False):
|
| 20 |
+
"""Run a shell command and return output"""
|
| 21 |
+
if not silent:
|
| 22 |
+
print(f"Running: {cmd}")
|
| 23 |
+
try:
|
| 24 |
+
process = subprocess.Popen(
|
| 25 |
+
cmd,
|
| 26 |
+
shell=True,
|
| 27 |
+
stdout=subprocess.PIPE,
|
| 28 |
+
stderr=subprocess.PIPE,
|
| 29 |
+
text=True
|
| 30 |
+
)
|
| 31 |
+
stdout, stderr = process.communicate()
|
| 32 |
+
|
| 33 |
+
if process.returncode != 0:
|
| 34 |
+
print(f"Command failed with error code {process.returncode}")
|
| 35 |
+
print(f"Error: {stderr.strip()}")
|
| 36 |
+
return False
|
| 37 |
+
|
| 38 |
+
if not silent and stdout.strip():
|
| 39 |
+
print(stdout.strip())
|
| 40 |
+
|
| 41 |
+
return True
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"Failed to execute command: {str(e)}")
|
| 44 |
+
return False
|
| 45 |
+
|
| 46 |
+
def check_git_installed():
|
| 47 |
+
"""Check if git is installed"""
|
| 48 |
+
print("Checking if git is installed...")
|
| 49 |
+
return run_command("git --version", silent=True)
|
| 50 |
+
|
| 51 |
+
def setup_git():
|
| 52 |
+
"""Initialize git if needed and configure remote"""
|
| 53 |
+
# Check if git is already initialized
|
| 54 |
+
if not os.path.exists(".git"):
|
| 55 |
+
print("Initializing git repository...")
|
| 56 |
+
if not run_command("git init"):
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
# Configure git user if not set
|
| 60 |
+
result = subprocess.run("git config user.name", shell=True, capture_output=True, text=True)
|
| 61 |
+
if not result.stdout.strip():
|
| 62 |
+
print("Setting up git user name...")
|
| 63 |
+
run_command('git config user.name "GAIA Deployment"')
|
| 64 |
+
|
| 65 |
+
result = subprocess.run("git config user.email", shell=True, capture_output=True, text=True)
|
| 66 |
+
if not result.stdout.strip():
|
| 67 |
+
print("Setting up git user email...")
|
| 68 |
+
run_command('git config user.email "gaia-deployment@example.com"')
|
| 69 |
+
|
| 70 |
+
# Set up the Hugging Face remote
|
| 71 |
+
print("Setting up git remote for Hugging Face...")
|
| 72 |
+
|
| 73 |
+
# Check if remote exists
|
| 74 |
+
result = subprocess.run("git remote -v", shell=True, capture_output=True, text=True)
|
| 75 |
+
remote_output = result.stdout
|
| 76 |
+
|
| 77 |
+
if "huggingface" in remote_output:
|
| 78 |
+
run_command("git remote remove huggingface")
|
| 79 |
+
|
| 80 |
+
# Add the HF remote
|
| 81 |
+
return run_command(f"git remote add huggingface https://huggingface.co/spaces/{SPACE_ID}")
|
| 82 |
+
|
| 83 |
+
def create_gitignore():
|
| 84 |
+
"""Create .gitignore file with common patterns"""
|
| 85 |
+
patterns = [
|
| 86 |
+
".env",
|
| 87 |
+
"__pycache__/",
|
| 88 |
+
"*.py[cod]",
|
| 89 |
+
"*$py.class",
|
| 90 |
+
".Python",
|
| 91 |
+
"env/",
|
| 92 |
+
"venv/",
|
| 93 |
+
".venv",
|
| 94 |
+
".coverage",
|
| 95 |
+
"*.log"
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
print("Creating .gitignore file...")
|
| 99 |
+
with open(".gitignore", "w") as f:
|
| 100 |
+
for pattern in patterns:
|
| 101 |
+
f.write(f"{pattern}\n")
|
| 102 |
+
|
| 103 |
+
return True
|
| 104 |
+
|
| 105 |
+
def commit_changes():
|
| 106 |
+
"""Stage and commit all changes"""
|
| 107 |
+
print("Staging files for commit...")
|
| 108 |
+
if not run_command("git add -A"):
|
| 109 |
+
return False
|
| 110 |
+
|
| 111 |
+
print("Committing changes...")
|
| 112 |
+
return run_command('git commit -m "Deploy GAIA to Hugging Face Space"')
|
| 113 |
+
|
| 114 |
+
def push_to_huggingface():
|
| 115 |
+
"""Push to Hugging Face Space"""
|
| 116 |
+
print("Pushing to Hugging Face Space...")
|
| 117 |
+
|
| 118 |
+
# Try regular push first
|
| 119 |
+
if run_command("git push huggingface main"):
|
| 120 |
+
return True
|
| 121 |
+
|
| 122 |
+
# If regular push fails, try force push
|
| 123 |
+
print("Regular push failed, attempting force push...")
|
| 124 |
+
if run_command("git push huggingface main --force"):
|
| 125 |
+
return True
|
| 126 |
+
|
| 127 |
+
print("Force push failed. You may need to manually push:")
|
| 128 |
+
print("1. Ensure you have the correct permissions")
|
| 129 |
+
print("2. Try: git push huggingface main --force")
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
+
def main():
|
| 133 |
+
"""Run deployment process"""
|
| 134 |
+
print("\n===== DEPLOYING TO HUGGING FACE SPACE =====")
|
| 135 |
+
print(f"Target Space: {REPO_URL}")
|
| 136 |
+
|
| 137 |
+
# Ensure Git is installed
|
| 138 |
+
if not check_git_installed():
|
| 139 |
+
print("Git is not installed. Please install Git and try again.")
|
| 140 |
+
sys.exit(1)
|
| 141 |
+
|
| 142 |
+
# Setup steps
|
| 143 |
+
steps = [
|
| 144 |
+
("Setting up git", setup_git),
|
| 145 |
+
("Creating .gitignore", create_gitignore),
|
| 146 |
+
("Committing changes", commit_changes),
|
| 147 |
+
("Pushing to Hugging Face", push_to_huggingface)
|
| 148 |
+
]
|
| 149 |
+
|
| 150 |
+
for name, func in steps:
|
| 151 |
+
print(f"\n>> {name}...")
|
| 152 |
+
if not func():
|
| 153 |
+
print(f"Step '{name}' failed. Deployment process halted.")
|
| 154 |
+
sys.exit(1)
|
| 155 |
+
|
| 156 |
+
print("\n===== DEPLOYMENT COMPLETED SUCCESSFULLY =====")
|
| 157 |
+
print(f"Your project has been deployed to: {REPO_URL}")
|
| 158 |
+
print("Note: It may take a few minutes for the changes to be visible.")
|
| 159 |
+
|
| 160 |
+
if __name__ == "__main__":
|
| 161 |
+
main()
|
deploy_to_huggingface.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""
|
| 3 |
+
Hugging Face Space Deployment Script
|
| 4 |
+
|
| 5 |
+
This script deploys the GAIA project to Hugging Face Spaces using git.
|
| 6 |
+
It handles authentication, remote setup, and deployment.
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
python deploy_to_huggingface.py [--space-id SPACE_ID]
|
| 10 |
+
|
| 11 |
+
Author: DevOps Team
|
| 12 |
+
Date: April 30, 2025
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import argparse
|
| 18 |
+
import subprocess
|
| 19 |
+
import logging
|
| 20 |
+
import json
|
| 21 |
+
import time
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
# Configure logging
|
| 25 |
+
logging.basicConfig(
|
| 26 |
+
level=logging.INFO,
|
| 27 |
+
format="%(asctime)s - %(levelname)s - %(message)s"
|
| 28 |
+
)
|
| 29 |
+
logger = logging.getLogger("hf_deploy")
|
| 30 |
+
|
| 31 |
+
def parse_arguments():
|
| 32 |
+
"""Parse command line arguments"""
|
| 33 |
+
parser = argparse.ArgumentParser(description="Deploy GAIA to Hugging Face Space")
|
| 34 |
+
parser.add_argument("--space-id",
|
| 35 |
+
help="Hugging Face Space ID (username/space-name)",
|
| 36 |
+
default="JoachimVC/GAIA-Assistant")
|
| 37 |
+
parser.add_argument("--check-only", action="store_true",
|
| 38 |
+
help="Only check prerequisites without deploying")
|
| 39 |
+
return parser.parse_args()
|
| 40 |
+
|
| 41 |
+
def run_command(command, shell=False):
|
| 42 |
+
"""Run a shell command and return the result"""
|
| 43 |
+
try:
|
| 44 |
+
logger.info(f"Running command: {command}")
|
| 45 |
+
result = subprocess.run(
|
| 46 |
+
command,
|
| 47 |
+
shell=shell,
|
| 48 |
+
check=True,
|
| 49 |
+
text=True,
|
| 50 |
+
capture_output=True
|
| 51 |
+
)
|
| 52 |
+
return result.stdout.strip()
|
| 53 |
+
except subprocess.CalledProcessError as e:
|
| 54 |
+
logger.error(f"Command failed with error: {e}")
|
| 55 |
+
logger.error(f"Error output: {e.stderr}")
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
def check_prerequisites():
|
| 59 |
+
"""Check if all prerequisites are met"""
|
| 60 |
+
# Check if git is installed
|
| 61 |
+
git_version = run_command(["git", "--version"])
|
| 62 |
+
if not git_version:
|
| 63 |
+
logger.error("Git is not installed or not in PATH")
|
| 64 |
+
return False
|
| 65 |
+
logger.info(f"Git version: {git_version}")
|
| 66 |
+
|
| 67 |
+
# Check if huggingface_hub is installed
|
| 68 |
+
try:
|
| 69 |
+
import huggingface_hub
|
| 70 |
+
logger.info(f"huggingface_hub version: {huggingface_hub.__version__}")
|
| 71 |
+
except ImportError:
|
| 72 |
+
logger.error("huggingface_hub is not installed")
|
| 73 |
+
logger.info("Installing huggingface_hub...")
|
| 74 |
+
if run_command(["pip", "install", "huggingface_hub"]) is None:
|
| 75 |
+
return False
|
| 76 |
+
|
| 77 |
+
# Check if user is logged in to Hugging Face
|
| 78 |
+
hf_token_exists = os.path.exists(os.path.expanduser("~/.huggingface/token"))
|
| 79 |
+
if not hf_token_exists:
|
| 80 |
+
logger.error("Not logged in to Hugging Face")
|
| 81 |
+
logger.info("Please run 'huggingface-cli login' to log in")
|
| 82 |
+
return False
|
| 83 |
+
|
| 84 |
+
# Check if the project has necessary files
|
| 85 |
+
required_files = ["app.py", "requirements.txt", "space_config.json", "HF_README.md"]
|
| 86 |
+
missing_files = [f for f in required_files if not os.path.exists(f)]
|
| 87 |
+
if missing_files:
|
| 88 |
+
logger.error(f"Missing required files: {', '.join(missing_files)}")
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
+
logger.info("All prerequisites met")
|
| 92 |
+
return True
|
| 93 |
+
|
| 94 |
+
def setup_git_repo(space_id):
|
| 95 |
+
"""Set up git repository for deployment"""
|
| 96 |
+
# Check if .git exists
|
| 97 |
+
if not os.path.exists(".git"):
|
| 98 |
+
logger.info("Initializing git repository...")
|
| 99 |
+
if run_command(["git", "init"]) is None:
|
| 100 |
+
return False
|
| 101 |
+
|
| 102 |
+
# Check if the Hugging Face remote exists
|
| 103 |
+
remotes = run_command(["git", "remote"])
|
| 104 |
+
if remotes is None:
|
| 105 |
+
return False
|
| 106 |
+
|
| 107 |
+
if "huggingface" in remotes.split():
|
| 108 |
+
logger.info("Updating Hugging Face remote...")
|
| 109 |
+
if run_command(["git", "remote", "set-url", "huggingface", f"https://huggingface.co/spaces/{space_id}"]) is None:
|
| 110 |
+
return False
|
| 111 |
+
else:
|
| 112 |
+
logger.info("Adding Hugging Face remote...")
|
| 113 |
+
if run_command(["git", "remote", "add", "huggingface", f"https://huggingface.co/spaces/{space_id}"]) is None:
|
| 114 |
+
return False
|
| 115 |
+
|
| 116 |
+
logger.info("Git repository set up successfully")
|
| 117 |
+
return True
|
| 118 |
+
|
| 119 |
+
def validate_space_id(space_id):
|
| 120 |
+
"""Validate the Hugging Face Space ID format"""
|
| 121 |
+
if "/" not in space_id:
|
| 122 |
+
logger.error(f"Invalid Space ID format: {space_id}")
|
| 123 |
+
logger.error("Space ID should be in format 'username/space-name'")
|
| 124 |
+
return False
|
| 125 |
+
|
| 126 |
+
username, space_name = space_id.split("/", 1)
|
| 127 |
+
if not username or not space_name:
|
| 128 |
+
logger.error(f"Invalid Space ID components: {space_id}")
|
| 129 |
+
return False
|
| 130 |
+
|
| 131 |
+
return True
|
| 132 |
+
|
| 133 |
+
def rename_files_for_hf():
|
| 134 |
+
"""Rename files for Hugging Face Space"""
|
| 135 |
+
if os.path.exists("HF_README.md"):
|
| 136 |
+
if os.path.exists("README.md"):
|
| 137 |
+
if not os.path.exists("README_original.md"):
|
| 138 |
+
logger.info("Backing up README.md to README_original.md...")
|
| 139 |
+
os.rename("README.md", "README_original.md")
|
| 140 |
+
else:
|
| 141 |
+
logger.info("README_original.md already exists, keeping it")
|
| 142 |
+
# Remove README.md to avoid confusion
|
| 143 |
+
if os.path.exists("README.md"):
|
| 144 |
+
os.remove("README.md")
|
| 145 |
+
|
| 146 |
+
logger.info("Renaming HF_README.md to README.md...")
|
| 147 |
+
os.rename("HF_README.md", "README.md")
|
| 148 |
+
|
| 149 |
+
return True
|
| 150 |
+
|
| 151 |
+
def update_git_ignore():
|
| 152 |
+
"""Update .gitignore file for Hugging Face Space"""
|
| 153 |
+
gitignore_entries = [
|
| 154 |
+
".env",
|
| 155 |
+
"__pycache__/",
|
| 156 |
+
"*.py[cod]",
|
| 157 |
+
"*$py.class",
|
| 158 |
+
"*.so",
|
| 159 |
+
".Python",
|
| 160 |
+
"env/",
|
| 161 |
+
"build/",
|
| 162 |
+
"develop-eggs/",
|
| 163 |
+
"dist/",
|
| 164 |
+
"downloads/",
|
| 165 |
+
"eggs/",
|
| 166 |
+
".eggs/",
|
| 167 |
+
"lib/",
|
| 168 |
+
"lib64/",
|
| 169 |
+
"parts/",
|
| 170 |
+
"sdist/",
|
| 171 |
+
"var/",
|
| 172 |
+
"*.egg-info/",
|
| 173 |
+
".installed.cfg",
|
| 174 |
+
"*.egg",
|
| 175 |
+
".env",
|
| 176 |
+
".venv",
|
| 177 |
+
"venv/",
|
| 178 |
+
"ENV/",
|
| 179 |
+
".idea/",
|
| 180 |
+
".vscode/",
|
| 181 |
+
"*.log",
|
| 182 |
+
"deploy_to_huggingface.py",
|
| 183 |
+
"test_components.py",
|
| 184 |
+
"verify_production.py",
|
| 185 |
+
"production_verification_report.md",
|
| 186 |
+
"deployment_readiness_report.md",
|
| 187 |
+
"final_verification_summary.md",
|
| 188 |
+
"prepare_for_hf_deployment.py"
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
# Read existing .gitignore if it exists
|
| 192 |
+
existing_entries = []
|
| 193 |
+
if os.path.exists(".gitignore"):
|
| 194 |
+
with open(".gitignore", "r") as f:
|
| 195 |
+
existing_entries = [line.strip() for line in f.readlines()]
|
| 196 |
+
|
| 197 |
+
# Combine entries, removing duplicates
|
| 198 |
+
combined_entries = list(set(existing_entries + gitignore_entries))
|
| 199 |
+
combined_entries.sort()
|
| 200 |
+
|
| 201 |
+
# Write updated .gitignore
|
| 202 |
+
with open(".gitignore", "w") as f:
|
| 203 |
+
f.write("\n".join(combined_entries) + "\n")
|
| 204 |
+
|
| 205 |
+
logger.info("Updated .gitignore file")
|
| 206 |
+
return True
|
| 207 |
+
|
| 208 |
+
def commit_and_push(space_id):
|
| 209 |
+
"""Commit changes and push to Hugging Face Space"""
|
| 210 |
+
# Stage all files
|
| 211 |
+
if run_command(["git", "add", "."]) is None:
|
| 212 |
+
return False
|
| 213 |
+
|
| 214 |
+
# Commit changes
|
| 215 |
+
commit_message = f"Deploy GAIA to Hugging Face Space {space_id}"
|
| 216 |
+
if run_command(["git", "commit", "-m", commit_message]) is None:
|
| 217 |
+
logger.warning("No changes to commit or commit failed")
|
| 218 |
+
# Continue anyway, as there might be no changes
|
| 219 |
+
|
| 220 |
+
# Push to Hugging Face
|
| 221 |
+
logger.info(f"Pushing to Hugging Face Space {space_id}...")
|
| 222 |
+
if run_command(["git", "push", "huggingface", "main"]) is None:
|
| 223 |
+
# Try pushing to master branch if main fails
|
| 224 |
+
logger.info("Pushing to master branch instead...")
|
| 225 |
+
if run_command(["git", "push", "huggingface", "master"]) is None:
|
| 226 |
+
# Try force pushing to main as last resort
|
| 227 |
+
logger.info("Force pushing to main branch...")
|
| 228 |
+
if run_command(["git", "push", "-f", "huggingface", "main"]) is None:
|
| 229 |
+
return False
|
| 230 |
+
|
| 231 |
+
logger.info(f"Successfully pushed to Hugging Face Space {space_id}")
|
| 232 |
+
return True
|
| 233 |
+
|
| 234 |
+
def create_space_if_needed(space_id):
|
| 235 |
+
"""Create Hugging Face Space if it doesn't exist"""
|
| 236 |
+
try:
|
| 237 |
+
from huggingface_hub import HfApi, SpaceHardware, SpaceSdk
|
| 238 |
+
|
| 239 |
+
api = HfApi()
|
| 240 |
+
username, space_name = space_id.split("/", 1)
|
| 241 |
+
|
| 242 |
+
# Check if space exists
|
| 243 |
+
try:
|
| 244 |
+
api.get_space_info(space_id)
|
| 245 |
+
logger.info(f"Space {space_id} already exists")
|
| 246 |
+
return True
|
| 247 |
+
except Exception:
|
| 248 |
+
logger.info(f"Space {space_id} doesn't exist, creating it...")
|
| 249 |
+
|
| 250 |
+
# Create space
|
| 251 |
+
api.create_space(
|
| 252 |
+
space_id=space_name,
|
| 253 |
+
token=None, # Use token from ~/.huggingface/token
|
| 254 |
+
sdk=SpaceSdk.GRADIO,
|
| 255 |
+
hardware=SpaceHardware.CPU_BASIC,
|
| 256 |
+
private=False
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
logger.info(f"Created Hugging Face Space {space_id}")
|
| 260 |
+
return True
|
| 261 |
+
|
| 262 |
+
except ImportError:
|
| 263 |
+
logger.warning("huggingface_hub not installed properly, skipping space creation check")
|
| 264 |
+
return True
|
| 265 |
+
except Exception as e:
|
| 266 |
+
logger.error(f"Error creating space: {e}")
|
| 267 |
+
return False
|
| 268 |
+
|
| 269 |
+
def wait_for_deployment(space_id):
|
| 270 |
+
"""Wait for deployment to complete and provide status link"""
|
| 271 |
+
logger.info(f"Deployment initiated to {space_id}")
|
| 272 |
+
logger.info(f"You can check the deployment status at: https://huggingface.co/spaces/{space_id}")
|
| 273 |
+
logger.info(f"Once deployment is complete, your app will be available at: https://huggingface.co/spaces/{space_id}")
|
| 274 |
+
|
| 275 |
+
logger.info("Waiting for 60 seconds to allow deployment to start...")
|
| 276 |
+
for i in range(12):
|
| 277 |
+
time.sleep(5)
|
| 278 |
+
logger.info(f"Elapsed time: {(i+1)*5} seconds")
|
| 279 |
+
|
| 280 |
+
return True
|
| 281 |
+
|
| 282 |
+
def main():
|
| 283 |
+
"""Main function to deploy to Hugging Face Space"""
|
| 284 |
+
args = parse_arguments()
|
| 285 |
+
space_id = args.space_id
|
| 286 |
+
|
| 287 |
+
logger.info(f"Starting deployment to Hugging Face Space: {space_id}")
|
| 288 |
+
|
| 289 |
+
# Validate Space ID
|
| 290 |
+
if not validate_space_id(space_id):
|
| 291 |
+
return False
|
| 292 |
+
|
| 293 |
+
# Check prerequisites
|
| 294 |
+
if not check_prerequisites():
|
| 295 |
+
return False
|
| 296 |
+
|
| 297 |
+
if args.check_only:
|
| 298 |
+
logger.info("Check-only mode: prerequisites satisfied, stopping before deployment")
|
| 299 |
+
return True
|
| 300 |
+
|
| 301 |
+
# Rename files for Hugging Face
|
| 302 |
+
if not rename_files_for_hf():
|
| 303 |
+
return False
|
| 304 |
+
|
| 305 |
+
# Update .gitignore
|
| 306 |
+
if not update_git_ignore():
|
| 307 |
+
return False
|
| 308 |
+
|
| 309 |
+
# Create Space if needed
|
| 310 |
+
if not create_space_if_needed(space_id):
|
| 311 |
+
logger.warning("Failed to create space, but continuing with deployment")
|
| 312 |
+
|
| 313 |
+
# Set up git repository
|
| 314 |
+
if not setup_git_repo(space_id):
|
| 315 |
+
return False
|
| 316 |
+
|
| 317 |
+
# Commit and push changes
|
| 318 |
+
if not commit_and_push(space_id):
|
| 319 |
+
return False
|
| 320 |
+
|
| 321 |
+
# Wait for deployment and show status
|
| 322 |
+
if not wait_for_deployment(space_id):
|
| 323 |
+
return False
|
| 324 |
+
|
| 325 |
+
logger.info("Deployment process completed successfully!")
|
| 326 |
+
logger.info(f"Your GAIA application will be available at: https://huggingface.co/spaces/{space_id}")
|
| 327 |
+
logger.info("Note: It may take a few minutes for the deployment to complete on Hugging Face")
|
| 328 |
+
|
| 329 |
+
return True
|
| 330 |
+
|
| 331 |
+
if __name__ == "__main__":
|
| 332 |
+
success = main()
|
| 333 |
+
sys.exit(0 if success else 1)
|
deploy_to_huggingface_credential.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Git Credential-based Deployment Script for Hugging Face Spaces
|
| 3 |
+
|
| 4 |
+
This script handles the git operations required to deploy to a Hugging Face Space
|
| 5 |
+
using credential helper for token-based authentication.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
python deploy_to_huggingface_credential.py [--space SPACE_ID]
|
| 9 |
+
|
| 10 |
+
Environment variables (from .env file):
|
| 11 |
+
HF_TOKEN - Your Hugging Face API token
|
| 12 |
+
"""
|
| 13 |
+
import os
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
import argparse
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
def parse_args():
|
| 20 |
+
parser = argparse.ArgumentParser(description="Deploy to Hugging Face Space using git credential helper")
|
| 21 |
+
parser.add_argument("--space", help="Space ID (username/space-name)",
|
| 22 |
+
default="JoachimVC/Final_Assignment_Template")
|
| 23 |
+
return parser.parse_args()
|
| 24 |
+
|
| 25 |
+
def load_dotenv():
|
| 26 |
+
"""Load environment variables from .env file"""
|
| 27 |
+
env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
|
| 28 |
+
if not os.path.exists(env_path):
|
| 29 |
+
print(f"ERROR: .env file not found at {env_path}")
|
| 30 |
+
return False
|
| 31 |
+
|
| 32 |
+
print(f"Loading environment variables from {env_path}")
|
| 33 |
+
with open(env_path, 'r') as file:
|
| 34 |
+
for line in file:
|
| 35 |
+
line = line.strip()
|
| 36 |
+
if not line or line.startswith('#'):
|
| 37 |
+
continue
|
| 38 |
+
|
| 39 |
+
key, value = line.split('=', 1)
|
| 40 |
+
os.environ[key] = value
|
| 41 |
+
|
| 42 |
+
return True
|
| 43 |
+
|
| 44 |
+
def run_command(cmd, silent=False):
|
| 45 |
+
"""Run a shell command and return output"""
|
| 46 |
+
if not silent:
|
| 47 |
+
print(f"Running: {cmd}")
|
| 48 |
+
try:
|
| 49 |
+
process = subprocess.Popen(
|
| 50 |
+
cmd,
|
| 51 |
+
shell=True,
|
| 52 |
+
stdout=subprocess.PIPE,
|
| 53 |
+
stderr=subprocess.PIPE,
|
| 54 |
+
text=True
|
| 55 |
+
)
|
| 56 |
+
stdout, stderr = process.communicate()
|
| 57 |
+
|
| 58 |
+
if process.returncode != 0:
|
| 59 |
+
print(f"Command failed with error code {process.returncode}")
|
| 60 |
+
print(f"Error: {stderr.strip()}")
|
| 61 |
+
return False
|
| 62 |
+
|
| 63 |
+
if not silent and stdout.strip():
|
| 64 |
+
print(stdout.strip())
|
| 65 |
+
|
| 66 |
+
return True
|
| 67 |
+
except Exception as e:
|
| 68 |
+
print(f"Failed to execute command: {str(e)}")
|
| 69 |
+
return False
|
| 70 |
+
|
| 71 |
+
def check_git_installed():
|
| 72 |
+
"""Check if git is installed"""
|
| 73 |
+
print("Checking if git is installed...")
|
| 74 |
+
return run_command("git --version", silent=True)
|
| 75 |
+
|
| 76 |
+
def get_token_from_env():
|
| 77 |
+
"""Get Hugging Face token from environment variables"""
|
| 78 |
+
# Try various environment variable names that might contain the token
|
| 79 |
+
token_vars = ["HF_TOKEN", "HUGGINGFACE_TOKEN", "HUGGING_FACE_TOKEN",
|
| 80 |
+
"HF_API_TOKEN", "HUGGINGFACE_API_TOKEN"]
|
| 81 |
+
|
| 82 |
+
for var_name in token_vars:
|
| 83 |
+
token = os.environ.get(var_name)
|
| 84 |
+
if token:
|
| 85 |
+
print(f"Found token in environment variable: {var_name}")
|
| 86 |
+
return token
|
| 87 |
+
|
| 88 |
+
return None
|
| 89 |
+
|
| 90 |
+
def create_deploy_token_file(token):
|
| 91 |
+
"""Create a temporary token file for deployment"""
|
| 92 |
+
token_dir = Path.home() / ".huggingface"
|
| 93 |
+
token_dir.mkdir(exist_ok=True)
|
| 94 |
+
|
| 95 |
+
token_file = token_dir / "token"
|
| 96 |
+
with open(token_file, "w") as f:
|
| 97 |
+
f.write(token)
|
| 98 |
+
|
| 99 |
+
print(f"Created HF token file at {token_file}")
|
| 100 |
+
return token_file
|
| 101 |
+
|
| 102 |
+
def setup_git_credential_helper(token):
|
| 103 |
+
"""Set up git credential helper to use the token"""
|
| 104 |
+
# Store the token in the git credential helper
|
| 105 |
+
credential_input = f"protocol=https\nhost=huggingface.co\nusername=hf_token\npassword={token}\n"
|
| 106 |
+
|
| 107 |
+
# Use git credential-store to save the token
|
| 108 |
+
print("Setting up git credential helper...")
|
| 109 |
+
process = subprocess.Popen(
|
| 110 |
+
["git", "credential-store", "store"],
|
| 111 |
+
stdin=subprocess.PIPE,
|
| 112 |
+
stdout=subprocess.PIPE,
|
| 113 |
+
stderr=subprocess.PIPE,
|
| 114 |
+
text=True
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
process.communicate(input=credential_input)
|
| 118 |
+
|
| 119 |
+
# Configure git to use the credential helper
|
| 120 |
+
return run_command("git config --global credential.helper store")
|
| 121 |
+
|
| 122 |
+
def setup_git(space_id):
|
| 123 |
+
"""Initialize git if needed and configure remote"""
|
| 124 |
+
# Check if git is already initialized
|
| 125 |
+
if not os.path.exists(".git"):
|
| 126 |
+
print("Initializing git repository...")
|
| 127 |
+
if not run_command("git init"):
|
| 128 |
+
return False
|
| 129 |
+
|
| 130 |
+
# Configure git user if not set
|
| 131 |
+
result = subprocess.run("git config user.name", shell=True, capture_output=True, text=True)
|
| 132 |
+
if not result.stdout.strip():
|
| 133 |
+
print("Setting up git user name...")
|
| 134 |
+
run_command('git config user.name "GAIA Deployment"')
|
| 135 |
+
|
| 136 |
+
result = subprocess.run("git config user.email", shell=True, capture_output=True, text=True)
|
| 137 |
+
if not result.stdout.strip():
|
| 138 |
+
print("Setting up git user email...")
|
| 139 |
+
run_command('git config user.email "gaia-deployment@example.com"')
|
| 140 |
+
|
| 141 |
+
# Set up the Hugging Face remote without token in URL
|
| 142 |
+
print("Setting up git remote for Hugging Face...")
|
| 143 |
+
|
| 144 |
+
# Check if remote exists
|
| 145 |
+
result = subprocess.run("git remote -v", shell=True, capture_output=True, text=True)
|
| 146 |
+
remote_output = result.stdout
|
| 147 |
+
|
| 148 |
+
if "huggingface" in remote_output:
|
| 149 |
+
run_command("git remote remove huggingface")
|
| 150 |
+
|
| 151 |
+
# Add the HF remote without token (will use credential helper)
|
| 152 |
+
repo_url = f"https://huggingface.co/spaces/{space_id}"
|
| 153 |
+
return run_command(f"git remote add huggingface {repo_url}")
|
| 154 |
+
|
| 155 |
+
def create_gitignore():
|
| 156 |
+
"""Create .gitignore file with common patterns"""
|
| 157 |
+
patterns = [
|
| 158 |
+
".env",
|
| 159 |
+
"__pycache__/",
|
| 160 |
+
"*.py[cod]",
|
| 161 |
+
"*$py.class",
|
| 162 |
+
".Python",
|
| 163 |
+
"env/",
|
| 164 |
+
"venv/",
|
| 165 |
+
".venv",
|
| 166 |
+
".coverage",
|
| 167 |
+
"*.log",
|
| 168 |
+
"deploy_with_token.py",
|
| 169 |
+
"deploy_to_huggingface_env.py",
|
| 170 |
+
"deploy_to_huggingface_dotenv.py",
|
| 171 |
+
"deploy_to_huggingface_credential.py" # Don't include this file with token handling
|
| 172 |
+
]
|
| 173 |
+
|
| 174 |
+
print("Creating .gitignore file...")
|
| 175 |
+
with open(".gitignore", "w") as f:
|
| 176 |
+
for pattern in patterns:
|
| 177 |
+
f.write(f"{pattern}\n")
|
| 178 |
+
|
| 179 |
+
return True
|
| 180 |
+
|
| 181 |
+
def commit_changes():
|
| 182 |
+
"""Stage and commit all changes"""
|
| 183 |
+
print("Staging files for commit...")
|
| 184 |
+
if not run_command("git add -A"):
|
| 185 |
+
return False
|
| 186 |
+
|
| 187 |
+
print("Committing changes...")
|
| 188 |
+
return run_command('git commit -m "Deploy GAIA to Hugging Face Space"')
|
| 189 |
+
|
| 190 |
+
def push_to_huggingface():
|
| 191 |
+
"""Push to Hugging Face Space"""
|
| 192 |
+
print("Pushing to Hugging Face Space...")
|
| 193 |
+
|
| 194 |
+
# Try direct push with git credential store
|
| 195 |
+
cmd = "git push huggingface main"
|
| 196 |
+
|
| 197 |
+
# Execute the push command
|
| 198 |
+
if run_command(cmd):
|
| 199 |
+
return True
|
| 200 |
+
|
| 201 |
+
# If regular push fails, try force push
|
| 202 |
+
print("Regular push failed, attempting force push...")
|
| 203 |
+
if run_command("git push huggingface main --force"):
|
| 204 |
+
return True
|
| 205 |
+
|
| 206 |
+
print("Force push failed. You may need to manually push:")
|
| 207 |
+
print("1. Ensure your token has write permissions")
|
| 208 |
+
print("2. Try: git push huggingface main --force")
|
| 209 |
+
return False
|
| 210 |
+
|
| 211 |
+
def setup_cli_auth_file(token):
|
| 212 |
+
"""Set up CLI authentication file for Hugging Face"""
|
| 213 |
+
# Create .huggingface directory in home if it doesn't exist
|
| 214 |
+
hf_dir = os.path.expanduser("~/.huggingface")
|
| 215 |
+
os.makedirs(hf_dir, exist_ok=True)
|
| 216 |
+
|
| 217 |
+
# Create or update token file
|
| 218 |
+
token_file = os.path.join(hf_dir, "token")
|
| 219 |
+
with open(token_file, "w") as f:
|
| 220 |
+
f.write(token)
|
| 221 |
+
|
| 222 |
+
print(f"Created HF token file at {token_file}")
|
| 223 |
+
return True
|
| 224 |
+
|
| 225 |
+
def setup_git_with_netrc(token):
|
| 226 |
+
"""Set up .netrc file for git authentication"""
|
| 227 |
+
netrc_path = os.path.expanduser("~/.netrc")
|
| 228 |
+
|
| 229 |
+
# Check if file exists and has huggingface.co entry
|
| 230 |
+
netrc_content = ""
|
| 231 |
+
if os.path.exists(netrc_path):
|
| 232 |
+
with open(netrc_path, "r") as f:
|
| 233 |
+
netrc_content = f.read()
|
| 234 |
+
|
| 235 |
+
# Add or update huggingface.co entry
|
| 236 |
+
if "machine huggingface.co" not in netrc_content:
|
| 237 |
+
with open(netrc_path, "a") as f:
|
| 238 |
+
f.write(f"\nmachine huggingface.co\nlogin hf_token\npassword {token}\n")
|
| 239 |
+
else:
|
| 240 |
+
# Replace existing entry
|
| 241 |
+
import re
|
| 242 |
+
pattern = r"machine huggingface\.co\s+login.*\s+password.*\s+"
|
| 243 |
+
replacement = f"machine huggingface.co\nlogin hf_token\npassword {token}\n"
|
| 244 |
+
netrc_content = re.sub(pattern, replacement, netrc_content)
|
| 245 |
+
with open(netrc_path, "w") as f:
|
| 246 |
+
f.write(netrc_content)
|
| 247 |
+
|
| 248 |
+
# Set permissions for .netrc file (Unix only)
|
| 249 |
+
if os.name != "nt": # not Windows
|
| 250 |
+
os.chmod(netrc_path, 0o600)
|
| 251 |
+
|
| 252 |
+
print(f"Updated .netrc file at {netrc_path}")
|
| 253 |
+
return True
|
| 254 |
+
|
| 255 |
+
def main():
|
| 256 |
+
"""Run deployment process"""
|
| 257 |
+
args = parse_args()
|
| 258 |
+
space_id = args.space
|
| 259 |
+
|
| 260 |
+
# Load .env file
|
| 261 |
+
if not load_dotenv():
|
| 262 |
+
print("WARNING: Failed to load .env file, continuing with existing environment variables")
|
| 263 |
+
|
| 264 |
+
# Get token from environment
|
| 265 |
+
token = get_token_from_env()
|
| 266 |
+
if not token:
|
| 267 |
+
print("ERROR: No Hugging Face token found in environment variables.")
|
| 268 |
+
print("Please ensure your .env file contains one of the following variables:")
|
| 269 |
+
print(" - HF_TOKEN")
|
| 270 |
+
print(" - HUGGINGFACE_TOKEN")
|
| 271 |
+
print(" - HUGGING_FACE_TOKEN")
|
| 272 |
+
print(" - HF_API_TOKEN")
|
| 273 |
+
print(" - HUGGINGFACE_API_TOKEN")
|
| 274 |
+
sys.exit(1)
|
| 275 |
+
|
| 276 |
+
repo_url = f"https://huggingface.co/spaces/{space_id}"
|
| 277 |
+
|
| 278 |
+
print("\n===== DEPLOYING TO HUGGING FACE SPACE =====")
|
| 279 |
+
print(f"Target Space: {repo_url}")
|
| 280 |
+
|
| 281 |
+
# Ensure Git is installed
|
| 282 |
+
if not check_git_installed():
|
| 283 |
+
print("Git is not installed. Please install Git and try again.")
|
| 284 |
+
sys.exit(1)
|
| 285 |
+
|
| 286 |
+
# Set up token file in ~/.huggingface/token
|
| 287 |
+
if not setup_cli_auth_file(token):
|
| 288 |
+
print("Failed to set up CLI authentication file")
|
| 289 |
+
sys.exit(1)
|
| 290 |
+
|
| 291 |
+
# Set up .netrc file with token
|
| 292 |
+
if not setup_git_with_netrc(token):
|
| 293 |
+
print("Failed to set up .netrc file")
|
| 294 |
+
sys.exit(1)
|
| 295 |
+
|
| 296 |
+
# Set up git credential helper
|
| 297 |
+
if not setup_git_credential_helper(token):
|
| 298 |
+
print("Failed to set up git credential helper")
|
| 299 |
+
sys.exit(1)
|
| 300 |
+
|
| 301 |
+
# Setup steps
|
| 302 |
+
steps = [
|
| 303 |
+
("Setting up git", lambda: setup_git(space_id)),
|
| 304 |
+
("Creating .gitignore", create_gitignore),
|
| 305 |
+
("Committing changes", commit_changes),
|
| 306 |
+
("Pushing to Hugging Face", push_to_huggingface)
|
| 307 |
+
]
|
| 308 |
+
|
| 309 |
+
for name, func in steps:
|
| 310 |
+
print(f"\n>> {name}...")
|
| 311 |
+
if not func():
|
| 312 |
+
print(f"Step '{name}' failed. Deployment process halted.")
|
| 313 |
+
sys.exit(1)
|
| 314 |
+
|
| 315 |
+
print("\n===== DEPLOYMENT COMPLETED SUCCESSFULLY =====")
|
| 316 |
+
print(f"Your project has been deployed to: {repo_url}")
|
| 317 |
+
print("Note: It may take a few minutes for the changes to be visible.")
|
| 318 |
+
|
| 319 |
+
if __name__ == "__main__":
|
| 320 |
+
main()
|
deploy_to_huggingface_dotenv.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dotenv-based Git Deployment Script for Hugging Face Spaces
|
| 3 |
+
|
| 4 |
+
This script handles the git operations required to deploy to a Hugging Face Space
|
| 5 |
+
using token-based authentication, with the token loaded from a .env file.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
python deploy_to_huggingface_dotenv.py [--space SPACE_ID]
|
| 9 |
+
|
| 10 |
+
Environment variables (from .env file):
|
| 11 |
+
HF_TOKEN - Your Hugging Face API token
|
| 12 |
+
"""
|
| 13 |
+
import os
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
import argparse
|
| 17 |
+
|
| 18 |
+
def parse_args():
|
| 19 |
+
parser = argparse.ArgumentParser(description="Deploy to Hugging Face Space using .env file")
|
| 20 |
+
parser.add_argument("--space", help="Space ID (username/space-name)",
|
| 21 |
+
default="JoachimVC/Final_Assignment_Template")
|
| 22 |
+
return parser.parse_args()
|
| 23 |
+
|
| 24 |
+
def load_dotenv():
|
| 25 |
+
"""Load environment variables from .env file"""
|
| 26 |
+
env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
|
| 27 |
+
if not os.path.exists(env_path):
|
| 28 |
+
print(f"ERROR: .env file not found at {env_path}")
|
| 29 |
+
return False
|
| 30 |
+
|
| 31 |
+
print(f"Loading environment variables from {env_path}")
|
| 32 |
+
with open(env_path, 'r') as file:
|
| 33 |
+
for line in file:
|
| 34 |
+
line = line.strip()
|
| 35 |
+
if not line or line.startswith('#'):
|
| 36 |
+
continue
|
| 37 |
+
|
| 38 |
+
key, value = line.split('=', 1)
|
| 39 |
+
os.environ[key] = value
|
| 40 |
+
|
| 41 |
+
return True
|
| 42 |
+
|
| 43 |
+
def run_command(cmd, silent=False):
|
| 44 |
+
"""Run a shell command and return output"""
|
| 45 |
+
if not silent:
|
| 46 |
+
print(f"Running: {cmd}")
|
| 47 |
+
try:
|
| 48 |
+
process = subprocess.Popen(
|
| 49 |
+
cmd,
|
| 50 |
+
shell=True,
|
| 51 |
+
stdout=subprocess.PIPE,
|
| 52 |
+
stderr=subprocess.PIPE,
|
| 53 |
+
text=True
|
| 54 |
+
)
|
| 55 |
+
stdout, stderr = process.communicate()
|
| 56 |
+
|
| 57 |
+
if process.returncode != 0:
|
| 58 |
+
print(f"Command failed with error code {process.returncode}")
|
| 59 |
+
print(f"Error: {stderr.strip()}")
|
| 60 |
+
return False
|
| 61 |
+
|
| 62 |
+
if not silent and stdout.strip():
|
| 63 |
+
print(stdout.strip())
|
| 64 |
+
|
| 65 |
+
return True
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"Failed to execute command: {str(e)}")
|
| 68 |
+
return False
|
| 69 |
+
|
| 70 |
+
def check_git_installed():
|
| 71 |
+
"""Check if git is installed"""
|
| 72 |
+
print("Checking if git is installed...")
|
| 73 |
+
return run_command("git --version", silent=True)
|
| 74 |
+
|
| 75 |
+
def get_token_from_env():
|
| 76 |
+
"""Get Hugging Face token from environment variables"""
|
| 77 |
+
# Try various environment variable names that might contain the token
|
| 78 |
+
token_vars = ["HF_TOKEN", "HUGGINGFACE_TOKEN", "HUGGING_FACE_TOKEN",
|
| 79 |
+
"HF_API_TOKEN", "HUGGINGFACE_API_TOKEN"]
|
| 80 |
+
|
| 81 |
+
for var_name in token_vars:
|
| 82 |
+
token = os.environ.get(var_name)
|
| 83 |
+
if token:
|
| 84 |
+
print(f"Found token in environment variable: {var_name}")
|
| 85 |
+
return token
|
| 86 |
+
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
def setup_git(space_id, token):
|
| 90 |
+
"""Initialize git if needed and configure remote with token"""
|
| 91 |
+
# Check if git is already initialized
|
| 92 |
+
if not os.path.exists(".git"):
|
| 93 |
+
print("Initializing git repository...")
|
| 94 |
+
if not run_command("git init"):
|
| 95 |
+
return False
|
| 96 |
+
|
| 97 |
+
# Configure git user if not set
|
| 98 |
+
result = subprocess.run("git config user.name", shell=True, capture_output=True, text=True)
|
| 99 |
+
if not result.stdout.strip():
|
| 100 |
+
print("Setting up git user name...")
|
| 101 |
+
run_command('git config user.name "GAIA Deployment"')
|
| 102 |
+
|
| 103 |
+
result = subprocess.run("git config user.email", shell=True, capture_output=True, text=True)
|
| 104 |
+
if not result.stdout.strip():
|
| 105 |
+
print("Setting up git user email...")
|
| 106 |
+
run_command('git config user.email "gaia-deployment@example.com"')
|
| 107 |
+
|
| 108 |
+
# Set up the Hugging Face remote with token
|
| 109 |
+
print("Setting up git remote for Hugging Face...")
|
| 110 |
+
|
| 111 |
+
# Check if remote exists
|
| 112 |
+
result = subprocess.run("git remote -v", shell=True, capture_output=True, text=True)
|
| 113 |
+
remote_output = result.stdout
|
| 114 |
+
|
| 115 |
+
if "huggingface" in remote_output:
|
| 116 |
+
run_command("git remote remove huggingface")
|
| 117 |
+
|
| 118 |
+
# Add the HF remote with token authentication
|
| 119 |
+
token_url = f"https://{token}@huggingface.co/spaces/{space_id}"
|
| 120 |
+
|
| 121 |
+
# Don't print the token in the console output
|
| 122 |
+
print(f"Adding remote: huggingface -> https://****@huggingface.co/spaces/{space_id}")
|
| 123 |
+
return run_command(f"git remote add huggingface {token_url}")
|
| 124 |
+
|
| 125 |
+
def create_gitignore():
|
| 126 |
+
"""Create .gitignore file with common patterns"""
|
| 127 |
+
patterns = [
|
| 128 |
+
".env",
|
| 129 |
+
"__pycache__/",
|
| 130 |
+
"*.py[cod]",
|
| 131 |
+
"*$py.class",
|
| 132 |
+
".Python",
|
| 133 |
+
"env/",
|
| 134 |
+
"venv/",
|
| 135 |
+
".venv",
|
| 136 |
+
".coverage",
|
| 137 |
+
"*.log",
|
| 138 |
+
"deploy_with_token.py",
|
| 139 |
+
"deploy_to_huggingface_env.py",
|
| 140 |
+
"deploy_to_huggingface_dotenv.py" # Don't include this file with token handling
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
print("Creating .gitignore file...")
|
| 144 |
+
with open(".gitignore", "w") as f:
|
| 145 |
+
for pattern in patterns:
|
| 146 |
+
f.write(f"{pattern}\n")
|
| 147 |
+
|
| 148 |
+
return True
|
| 149 |
+
|
| 150 |
+
def commit_changes():
|
| 151 |
+
"""Stage and commit all changes"""
|
| 152 |
+
print("Staging files for commit...")
|
| 153 |
+
if not run_command("git add -A"):
|
| 154 |
+
return False
|
| 155 |
+
|
| 156 |
+
print("Committing changes...")
|
| 157 |
+
return run_command('git commit -m "Deploy GAIA to Hugging Face Space"')
|
| 158 |
+
|
| 159 |
+
def push_to_huggingface():
|
| 160 |
+
"""Push to Hugging Face Space"""
|
| 161 |
+
print("Pushing to Hugging Face Space...")
|
| 162 |
+
|
| 163 |
+
# Try regular push first
|
| 164 |
+
if run_command("git push huggingface main"):
|
| 165 |
+
return True
|
| 166 |
+
|
| 167 |
+
# If regular push fails, try force push
|
| 168 |
+
print("Regular push failed, attempting force push...")
|
| 169 |
+
if run_command("git push huggingface main --force"):
|
| 170 |
+
return True
|
| 171 |
+
|
| 172 |
+
print("Force push failed. You may need to manually push:")
|
| 173 |
+
print("1. Ensure your token has write permissions")
|
| 174 |
+
print("2. Try: git push huggingface main --force")
|
| 175 |
+
return False
|
| 176 |
+
|
| 177 |
+
def main():
|
| 178 |
+
"""Run deployment process"""
|
| 179 |
+
args = parse_args()
|
| 180 |
+
space_id = args.space
|
| 181 |
+
|
| 182 |
+
# Load .env file
|
| 183 |
+
if not load_dotenv():
|
| 184 |
+
print("WARNING: Failed to load .env file, continuing with existing environment variables")
|
| 185 |
+
|
| 186 |
+
# Get token from environment
|
| 187 |
+
token = get_token_from_env()
|
| 188 |
+
if not token:
|
| 189 |
+
print("ERROR: No Hugging Face token found in environment variables.")
|
| 190 |
+
print("Please ensure your .env file contains one of the following variables:")
|
| 191 |
+
print(" - HF_TOKEN")
|
| 192 |
+
print(" - HUGGINGFACE_TOKEN")
|
| 193 |
+
print(" - HUGGING_FACE_TOKEN")
|
| 194 |
+
print(" - HF_API_TOKEN")
|
| 195 |
+
print(" - HUGGINGFACE_API_TOKEN")
|
| 196 |
+
sys.exit(1)
|
| 197 |
+
|
| 198 |
+
repo_url = f"https://huggingface.co/spaces/{space_id}"
|
| 199 |
+
|
| 200 |
+
print("\n===== DEPLOYING TO HUGGING FACE SPACE =====")
|
| 201 |
+
print(f"Target Space: {repo_url}")
|
| 202 |
+
|
| 203 |
+
# Ensure Git is installed
|
| 204 |
+
if not check_git_installed():
|
| 205 |
+
print("Git is not installed. Please install Git and try again.")
|
| 206 |
+
sys.exit(1)
|
| 207 |
+
|
| 208 |
+
# Setup steps
|
| 209 |
+
steps = [
|
| 210 |
+
("Setting up git", lambda: setup_git(space_id, token)),
|
| 211 |
+
("Creating .gitignore", create_gitignore),
|
| 212 |
+
("Committing changes", commit_changes),
|
| 213 |
+
("Pushing to Hugging Face", push_to_huggingface)
|
| 214 |
+
]
|
| 215 |
+
|
| 216 |
+
for name, func in steps:
|
| 217 |
+
print(f"\n>> {name}...")
|
| 218 |
+
if not func():
|
| 219 |
+
print(f"Step '{name}' failed. Deployment process halted.")
|
| 220 |
+
sys.exit(1)
|
| 221 |
+
|
| 222 |
+
print("\n===== DEPLOYMENT COMPLETED SUCCESSFULLY =====")
|
| 223 |
+
print(f"Your project has been deployed to: {repo_url}")
|
| 224 |
+
print("Note: It may take a few minutes for the changes to be visible.")
|
| 225 |
+
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
main()
|
deploy_to_huggingface_env.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Environment-based Git Deployment Script for Hugging Face Spaces
|
| 3 |
+
|
| 4 |
+
This script handles the git operations required to deploy to a Hugging Face Space
|
| 5 |
+
using token-based authentication, with the token taken from environment variables.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
python deploy_to_huggingface_env.py [--space SPACE_ID]
|
| 9 |
+
|
| 10 |
+
Environment variables:
|
| 11 |
+
HUGGINGFACE_TOKEN - Your Hugging Face API token
|
| 12 |
+
"""
|
| 13 |
+
import os
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
import argparse
|
| 17 |
+
|
| 18 |
+
def parse_args():
|
| 19 |
+
parser = argparse.ArgumentParser(description="Deploy to Hugging Face Space using environment token")
|
| 20 |
+
parser.add_argument("--space", help="Space ID (username/space-name)",
|
| 21 |
+
default="JoachimVC/Final_Assignment_Template")
|
| 22 |
+
return parser.parse_args()
|
| 23 |
+
|
| 24 |
+
def run_command(cmd, silent=False):
|
| 25 |
+
"""Run a shell command and return output"""
|
| 26 |
+
if not silent:
|
| 27 |
+
print(f"Running: {cmd}")
|
| 28 |
+
try:
|
| 29 |
+
process = subprocess.Popen(
|
| 30 |
+
cmd,
|
| 31 |
+
shell=True,
|
| 32 |
+
stdout=subprocess.PIPE,
|
| 33 |
+
stderr=subprocess.PIPE,
|
| 34 |
+
text=True
|
| 35 |
+
)
|
| 36 |
+
stdout, stderr = process.communicate()
|
| 37 |
+
|
| 38 |
+
if process.returncode != 0:
|
| 39 |
+
print(f"Command failed with error code {process.returncode}")
|
| 40 |
+
print(f"Error: {stderr.strip()}")
|
| 41 |
+
return False
|
| 42 |
+
|
| 43 |
+
if not silent and stdout.strip():
|
| 44 |
+
print(stdout.strip())
|
| 45 |
+
|
| 46 |
+
return True
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"Failed to execute command: {str(e)}")
|
| 49 |
+
return False
|
| 50 |
+
|
| 51 |
+
def check_git_installed():
|
| 52 |
+
"""Check if git is installed"""
|
| 53 |
+
print("Checking if git is installed...")
|
| 54 |
+
return run_command("git --version", silent=True)
|
| 55 |
+
|
| 56 |
+
def get_token_from_env():
|
| 57 |
+
"""Get Hugging Face token from environment variables"""
|
| 58 |
+
# Try various environment variable names that might contain the token
|
| 59 |
+
token_vars = ["HUGGINGFACE_TOKEN", "HF_TOKEN", "HUGGING_FACE_TOKEN",
|
| 60 |
+
"HF_API_TOKEN", "HUGGINGFACE_API_TOKEN"]
|
| 61 |
+
|
| 62 |
+
for var_name in token_vars:
|
| 63 |
+
token = os.environ.get(var_name)
|
| 64 |
+
if token:
|
| 65 |
+
print(f"Found token in environment variable: {var_name}")
|
| 66 |
+
return token
|
| 67 |
+
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
def setup_git(space_id, token):
|
| 71 |
+
"""Initialize git if needed and configure remote with token"""
|
| 72 |
+
# Check if git is already initialized
|
| 73 |
+
if not os.path.exists(".git"):
|
| 74 |
+
print("Initializing git repository...")
|
| 75 |
+
if not run_command("git init"):
|
| 76 |
+
return False
|
| 77 |
+
|
| 78 |
+
# Configure git user if not set
|
| 79 |
+
result = subprocess.run("git config user.name", shell=True, capture_output=True, text=True)
|
| 80 |
+
if not result.stdout.strip():
|
| 81 |
+
print("Setting up git user name...")
|
| 82 |
+
run_command('git config user.name "GAIA Deployment"')
|
| 83 |
+
|
| 84 |
+
result = subprocess.run("git config user.email", shell=True, capture_output=True, text=True)
|
| 85 |
+
if not result.stdout.strip():
|
| 86 |
+
print("Setting up git user email...")
|
| 87 |
+
run_command('git config user.email "gaia-deployment@example.com"')
|
| 88 |
+
|
| 89 |
+
# Set up the Hugging Face remote with token
|
| 90 |
+
print("Setting up git remote for Hugging Face...")
|
| 91 |
+
|
| 92 |
+
# Check if remote exists
|
| 93 |
+
result = subprocess.run("git remote -v", shell=True, capture_output=True, text=True)
|
| 94 |
+
remote_output = result.stdout
|
| 95 |
+
|
| 96 |
+
if "huggingface" in remote_output:
|
| 97 |
+
run_command("git remote remove huggingface")
|
| 98 |
+
|
| 99 |
+
# Add the HF remote with token authentication
|
| 100 |
+
token_url = f"https://{token}@huggingface.co/spaces/{space_id}"
|
| 101 |
+
|
| 102 |
+
# Don't print the token in the console output
|
| 103 |
+
print(f"Adding remote: huggingface -> https://****@huggingface.co/spaces/{space_id}")
|
| 104 |
+
return run_command(f"git remote add huggingface {token_url}")
|
| 105 |
+
|
| 106 |
+
def create_gitignore():
|
| 107 |
+
"""Create .gitignore file with common patterns"""
|
| 108 |
+
patterns = [
|
| 109 |
+
".env",
|
| 110 |
+
"__pycache__/",
|
| 111 |
+
"*.py[cod]",
|
| 112 |
+
"*$py.class",
|
| 113 |
+
".Python",
|
| 114 |
+
"env/",
|
| 115 |
+
"venv/",
|
| 116 |
+
".venv",
|
| 117 |
+
".coverage",
|
| 118 |
+
"*.log",
|
| 119 |
+
"deploy_with_token.py",
|
| 120 |
+
"deploy_to_huggingface_env.py" # Don't include this file with token handling
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
print("Creating .gitignore file...")
|
| 124 |
+
with open(".gitignore", "w") as f:
|
| 125 |
+
for pattern in patterns:
|
| 126 |
+
f.write(f"{pattern}\n")
|
| 127 |
+
|
| 128 |
+
return True
|
| 129 |
+
|
| 130 |
+
def commit_changes():
|
| 131 |
+
"""Stage and commit all changes"""
|
| 132 |
+
print("Staging files for commit...")
|
| 133 |
+
if not run_command("git add -A"):
|
| 134 |
+
return False
|
| 135 |
+
|
| 136 |
+
print("Committing changes...")
|
| 137 |
+
return run_command('git commit -m "Deploy GAIA to Hugging Face Space"')
|
| 138 |
+
|
| 139 |
+
def push_to_huggingface():
|
| 140 |
+
"""Push to Hugging Face Space"""
|
| 141 |
+
print("Pushing to Hugging Face Space...")
|
| 142 |
+
|
| 143 |
+
# Try regular push first
|
| 144 |
+
if run_command("git push huggingface main"):
|
| 145 |
+
return True
|
| 146 |
+
|
| 147 |
+
# If regular push fails, try force push
|
| 148 |
+
print("Regular push failed, attempting force push...")
|
| 149 |
+
if run_command("git push huggingface main --force"):
|
| 150 |
+
return True
|
| 151 |
+
|
| 152 |
+
print("Force push failed. You may need to manually push:")
|
| 153 |
+
print("1. Ensure your token has write permissions")
|
| 154 |
+
print("2. Try: git push huggingface main --force")
|
| 155 |
+
return False
|
| 156 |
+
|
| 157 |
+
def main():
|
| 158 |
+
"""Run deployment process"""
|
| 159 |
+
args = parse_args()
|
| 160 |
+
space_id = args.space
|
| 161 |
+
|
| 162 |
+
# Get token from environment
|
| 163 |
+
token = get_token_from_env()
|
| 164 |
+
if not token:
|
| 165 |
+
print("ERROR: No Hugging Face token found in environment variables.")
|
| 166 |
+
print("Please set one of the following environment variables:")
|
| 167 |
+
print(" - HUGGINGFACE_TOKEN")
|
| 168 |
+
print(" - HF_TOKEN")
|
| 169 |
+
print(" - HUGGING_FACE_TOKEN")
|
| 170 |
+
print(" - HF_API_TOKEN")
|
| 171 |
+
print(" - HUGGINGFACE_API_TOKEN")
|
| 172 |
+
sys.exit(1)
|
| 173 |
+
|
| 174 |
+
repo_url = f"https://huggingface.co/spaces/{space_id}"
|
| 175 |
+
|
| 176 |
+
print("\n===== DEPLOYING TO HUGGING FACE SPACE =====")
|
| 177 |
+
print(f"Target Space: {repo_url}")
|
| 178 |
+
|
| 179 |
+
# Ensure Git is installed
|
| 180 |
+
if not check_git_installed():
|
| 181 |
+
print("Git is not installed. Please install Git and try again.")
|
| 182 |
+
sys.exit(1)
|
| 183 |
+
|
| 184 |
+
# Setup steps
|
| 185 |
+
steps = [
|
| 186 |
+
("Setting up git", lambda: setup_git(space_id, token)),
|
| 187 |
+
("Creating .gitignore", create_gitignore),
|
| 188 |
+
("Committing changes", commit_changes),
|
| 189 |
+
("Pushing to Hugging Face", push_to_huggingface)
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
for name, func in steps:
|
| 193 |
+
print(f"\n>> {name}...")
|
| 194 |
+
if not func():
|
| 195 |
+
print(f"Step '{name}' failed. Deployment process halted.")
|
| 196 |
+
sys.exit(1)
|
| 197 |
+
|
| 198 |
+
print("\n===== DEPLOYMENT COMPLETED SUCCESSFULLY =====")
|
| 199 |
+
print(f"Your project has been deployed to: {repo_url}")
|
| 200 |
+
print("Note: It may take a few minutes for the changes to be visible.")
|
| 201 |
+
|
| 202 |
+
if __name__ == "__main__":
|
| 203 |
+
main()
|
deploy_with_token.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Token-Based Git Deployment Script for Hugging Face Spaces
|
| 3 |
+
|
| 4 |
+
This script handles the git operations required to deploy to a Hugging Face Space
|
| 5 |
+
using token-based authentication.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
python deploy_with_token.py --token YOUR_HF_TOKEN
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import argparse
|
| 15 |
+
|
| 16 |
+
def parse_args():
|
| 17 |
+
parser = argparse.ArgumentParser(description="Deploy to Hugging Face Space with token")
|
| 18 |
+
parser.add_argument("--token", help="Hugging Face API token", required=True)
|
| 19 |
+
parser.add_argument("--space", help="Space ID (username/space-name)",
|
| 20 |
+
default="JoachimVC/Final_Assignment_Template")
|
| 21 |
+
return parser.parse_args()
|
| 22 |
+
|
| 23 |
+
def run_command(cmd, silent=False):
|
| 24 |
+
"""Run a shell command and return output"""
|
| 25 |
+
if not silent:
|
| 26 |
+
print(f"Running: {cmd}")
|
| 27 |
+
try:
|
| 28 |
+
process = subprocess.Popen(
|
| 29 |
+
cmd,
|
| 30 |
+
shell=True,
|
| 31 |
+
stdout=subprocess.PIPE,
|
| 32 |
+
stderr=subprocess.PIPE,
|
| 33 |
+
text=True
|
| 34 |
+
)
|
| 35 |
+
stdout, stderr = process.communicate()
|
| 36 |
+
|
| 37 |
+
if process.returncode != 0:
|
| 38 |
+
print(f"Command failed with error code {process.returncode}")
|
| 39 |
+
print(f"Error: {stderr.strip()}")
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
+
if not silent and stdout.strip():
|
| 43 |
+
print(stdout.strip())
|
| 44 |
+
|
| 45 |
+
return True
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"Failed to execute command: {str(e)}")
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
def check_git_installed():
|
| 51 |
+
"""Check if git is installed"""
|
| 52 |
+
print("Checking if git is installed...")
|
| 53 |
+
return run_command("git --version", silent=True)
|
| 54 |
+
|
| 55 |
+
def setup_git(space_id, token):
|
| 56 |
+
"""Initialize git if needed and configure remote with token"""
|
| 57 |
+
# Check if git is already initialized
|
| 58 |
+
if not os.path.exists(".git"):
|
| 59 |
+
print("Initializing git repository...")
|
| 60 |
+
if not run_command("git init"):
|
| 61 |
+
return False
|
| 62 |
+
|
| 63 |
+
# Configure git user if not set
|
| 64 |
+
result = subprocess.run("git config user.name", shell=True, capture_output=True, text=True)
|
| 65 |
+
if not result.stdout.strip():
|
| 66 |
+
print("Setting up git user name...")
|
| 67 |
+
run_command('git config user.name "GAIA Deployment"')
|
| 68 |
+
|
| 69 |
+
result = subprocess.run("git config user.email", shell=True, capture_output=True, text=True)
|
| 70 |
+
if not result.stdout.strip():
|
| 71 |
+
print("Setting up git user email...")
|
| 72 |
+
run_command('git config user.email "gaia-deployment@example.com"')
|
| 73 |
+
|
| 74 |
+
# Set up the Hugging Face remote with token
|
| 75 |
+
print("Setting up git remote for Hugging Face...")
|
| 76 |
+
|
| 77 |
+
# Check if remote exists
|
| 78 |
+
result = subprocess.run("git remote -v", shell=True, capture_output=True, text=True)
|
| 79 |
+
remote_output = result.stdout
|
| 80 |
+
|
| 81 |
+
if "huggingface" in remote_output:
|
| 82 |
+
run_command("git remote remove huggingface")
|
| 83 |
+
|
| 84 |
+
# Add the HF remote with token authentication
|
| 85 |
+
token_url = f"https://{token}@huggingface.co/spaces/{space_id}"
|
| 86 |
+
|
| 87 |
+
# Don't print the token in the console output
|
| 88 |
+
print(f"Adding remote: huggingface -> https://****@huggingface.co/spaces/{space_id}")
|
| 89 |
+
return run_command(f"git remote add huggingface {token_url}")
|
| 90 |
+
|
| 91 |
+
def create_gitignore():
|
| 92 |
+
"""Create .gitignore file with common patterns"""
|
| 93 |
+
patterns = [
|
| 94 |
+
".env",
|
| 95 |
+
"__pycache__/",
|
| 96 |
+
"*.py[cod]",
|
| 97 |
+
"*$py.class",
|
| 98 |
+
".Python",
|
| 99 |
+
"env/",
|
| 100 |
+
"venv/",
|
| 101 |
+
".venv",
|
| 102 |
+
".coverage",
|
| 103 |
+
"*.log",
|
| 104 |
+
"deploy_with_token.py" # Don't include this file with token handling
|
| 105 |
+
]
|
| 106 |
+
|
| 107 |
+
print("Creating .gitignore file...")
|
| 108 |
+
with open(".gitignore", "w") as f:
|
| 109 |
+
for pattern in patterns:
|
| 110 |
+
f.write(f"{pattern}\n")
|
| 111 |
+
|
| 112 |
+
return True
|
| 113 |
+
|
| 114 |
+
def commit_changes():
|
| 115 |
+
"""Stage and commit all changes"""
|
| 116 |
+
print("Staging files for commit...")
|
| 117 |
+
if not run_command("git add -A"):
|
| 118 |
+
return False
|
| 119 |
+
|
| 120 |
+
print("Committing changes...")
|
| 121 |
+
return run_command('git commit -m "Deploy GAIA to Hugging Face Space"')
|
| 122 |
+
|
| 123 |
+
def push_to_huggingface():
|
| 124 |
+
"""Push to Hugging Face Space"""
|
| 125 |
+
print("Pushing to Hugging Face Space...")
|
| 126 |
+
|
| 127 |
+
# Try regular push first
|
| 128 |
+
if run_command("git push huggingface main"):
|
| 129 |
+
return True
|
| 130 |
+
|
| 131 |
+
# If regular push fails, try force push
|
| 132 |
+
print("Regular push failed, attempting force push...")
|
| 133 |
+
if run_command("git push huggingface main --force"):
|
| 134 |
+
return True
|
| 135 |
+
|
| 136 |
+
print("Force push failed. You may need to manually push:")
|
| 137 |
+
print("1. Ensure your token has write permissions")
|
| 138 |
+
print("2. Try: git push huggingface main --force")
|
| 139 |
+
return False
|
| 140 |
+
|
| 141 |
+
def main():
|
| 142 |
+
"""Run deployment process"""
|
| 143 |
+
args = parse_args()
|
| 144 |
+
token = args.token
|
| 145 |
+
space_id = args.space
|
| 146 |
+
|
| 147 |
+
repo_url = f"https://huggingface.co/spaces/{space_id}"
|
| 148 |
+
|
| 149 |
+
print("\n===== DEPLOYING TO HUGGING FACE SPACE =====")
|
| 150 |
+
print(f"Target Space: {repo_url}")
|
| 151 |
+
|
| 152 |
+
# Ensure Git is installed
|
| 153 |
+
if not check_git_installed():
|
| 154 |
+
print("Git is not installed. Please install Git and try again.")
|
| 155 |
+
sys.exit(1)
|
| 156 |
+
|
| 157 |
+
# Setup steps
|
| 158 |
+
steps = [
|
| 159 |
+
("Setting up git", lambda: setup_git(space_id, token)),
|
| 160 |
+
("Creating .gitignore", create_gitignore),
|
| 161 |
+
("Committing changes", commit_changes),
|
| 162 |
+
("Pushing to Hugging Face", push_to_huggingface)
|
| 163 |
+
]
|
| 164 |
+
|
| 165 |
+
for name, func in steps:
|
| 166 |
+
print(f"\n>> {name}...")
|
| 167 |
+
if not func():
|
| 168 |
+
print(f"Step '{name}' failed. Deployment process halted.")
|
| 169 |
+
sys.exit(1)
|
| 170 |
+
|
| 171 |
+
print("\n===== DEPLOYMENT COMPLETED SUCCESSFULLY =====")
|
| 172 |
+
print(f"Your project has been deployed to: {repo_url}")
|
| 173 |
+
print("Note: It may take a few minutes for the changes to be visible.")
|
| 174 |
+
|
| 175 |
+
if __name__ == "__main__":
|
| 176 |
+
main()
|
deployment_readiness_report.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA Deployment Readiness Report
|
| 2 |
+
|
| 3 |
+
## 1. Deployment Status: ✅ SUCCESSFUL
|
| 4 |
+
|
| 5 |
+
The GAIA agent system has been successfully deployed to Hugging Face Space at:
|
| 6 |
+
`https://huggingface.co/spaces/JoachimVC/Final_Assignment_Template`
|
| 7 |
+
|
| 8 |
+
**Deployment Timestamp:** April 30, 2025
|
| 9 |
+
|
| 10 |
+
## 2. Environment Configuration
|
| 11 |
+
|
| 12 |
+
| Category | Status | Details |
|
| 13 |
+
|----------|--------|---------|
|
| 14 |
+
| Code Files | ✅ Complete | All necessary code files have been uploaded |
|
| 15 |
+
| Environment Variables | ✅ Configured | All required API keys and configuration variables set |
|
| 16 |
+
| Secret Management | ✅ Secure | Using Hugging Face Secrets for sensitive credentials |
|
| 17 |
+
|
| 18 |
+
### Environment Variables Configured:
|
| 19 |
+
- `OPENAI_API_KEY` ✅
|
| 20 |
+
- `SERPER_API_KEY` ✅
|
| 21 |
+
- `PERPLEXITY_API_KEY` ✅
|
| 22 |
+
- `SUPABASE_URL` ✅
|
| 23 |
+
- `SUPABASE_KEY` ✅
|
| 24 |
+
- `HF_TOKEN` ✅
|
| 25 |
+
|
| 26 |
+
## 3. Component Integration Status
|
| 27 |
+
|
| 28 |
+
| Component | Status | Verification |
|
| 29 |
+
|-----------|--------|-------------|
|
| 30 |
+
| OpenAI API | ✅ Working | Successfully connected to API and retrieved model list |
|
| 31 |
+
| Serper Search | ✅ Working | Successfully performed search query with expected results |
|
| 32 |
+
| Supabase Memory | ⚠️ Needs Verification | Environment variables set, but actual integration needs testing |
|
| 33 |
+
| DuckDuckGo Search | ⚠️ Needs Verification | Functionality available but needs end-to-end testing |
|
| 34 |
+
| Perplexity | ⚠️ Needs Verification | API key configured, but integration needs testing |
|
| 35 |
+
| Agent Graph Workflow | ⚠️ Needs Verification | Core functionality needs verification in the deployed environment |
|
| 36 |
+
|
| 37 |
+
## 4. Cleanup Recommendations
|
| 38 |
+
|
| 39 |
+
Several files and directories in the deployed space are not required for runtime operation and can be safely removed to optimize the environment. Refer to `huggingface_space_cleanup.md` for a detailed list of files that can be removed, including:
|
| 40 |
+
|
| 41 |
+
- Test directories (`tests/`, `backup_tests/`)
|
| 42 |
+
- Development configuration (`.roo/`, `.roomodes/`, etc.)
|
| 43 |
+
- Deployment and cleaning scripts
|
| 44 |
+
- Non-essential documentation
|
| 45 |
+
|
| 46 |
+
## 5. Verification Steps
|
| 47 |
+
|
| 48 |
+
The following steps are recommended to complete verification of the deployed system:
|
| 49 |
+
|
| 50 |
+
1. **Run Production Verification Script**
|
| 51 |
+
- Execute `verify_production.py` on the Hugging Face Space to test all components
|
| 52 |
+
- This script will generate a detailed report on component status
|
| 53 |
+
|
| 54 |
+
2. **Test Conversation Memory**
|
| 55 |
+
- Initiate a multi-turn conversation that relies on memory
|
| 56 |
+
- Verify that the agent can recall information from previous interactions
|
| 57 |
+
|
| 58 |
+
3. **Test Search Tool Integration**
|
| 59 |
+
- Ask a question requiring web search
|
| 60 |
+
- Verify that search results are properly integrated into responses
|
| 61 |
+
|
| 62 |
+
4. **Performance Monitoring**
|
| 63 |
+
- Monitor response times for different query types
|
| 64 |
+
- Check for any memory leaks or increasing latency over time
|
| 65 |
+
|
| 66 |
+
## 6. Recommendations
|
| 67 |
+
|
| 68 |
+
1. **Memory Persistence**
|
| 69 |
+
- Verify Supabase table structure matches the required schema
|
| 70 |
+
- Check that memory persistence works across session restarts
|
| 71 |
+
|
| 72 |
+
2. **Error Handling**
|
| 73 |
+
- Implement robust error handling for API failures
|
| 74 |
+
- Add automatic fallback to alternative models if primary model is unavailable
|
| 75 |
+
|
| 76 |
+
3. **Monitoring**
|
| 77 |
+
- Set up periodic health checks to verify all integrations remain functional
|
| 78 |
+
- Implement usage tracking to monitor API consumption and costs
|
| 79 |
+
|
| 80 |
+
4. **Documentation**
|
| 81 |
+
- Update user-facing documentation with examples of supported capabilities
|
| 82 |
+
- Provide clear guidance on limitations and expected behaviors
|
| 83 |
+
|
| 84 |
+
## 7. Rollback Plan
|
| 85 |
+
|
| 86 |
+
In case issues are discovered in the deployed system:
|
| 87 |
+
|
| 88 |
+
1. Identify the specific component causing the issue
|
| 89 |
+
2. If possible, fix directly in the Hugging Face interface
|
| 90 |
+
3. For more complex issues, fix locally and redeploy
|
| 91 |
+
4. If critical failure occurs, consider reverting to previous stable version
|
| 92 |
+
|
| 93 |
+
## Conclusion
|
| 94 |
+
|
| 95 |
+
The GAIA system has been successfully deployed to Hugging Face Space with all required environment variables configured. Initial component testing shows successful integration with OpenAI and Serper APIs. Comprehensive testing of the Supabase memory integration and other components is recommended to ensure full functionality in the production environment.
|
| 96 |
+
|
| 97 |
+
The deployment is currently in a good state for final verification and production use, with minor cleanup recommended to optimize the space.
|
docs/all_apis_integration_testing.md
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# All APIs Integration Testing
|
| 2 |
+
|
| 3 |
+
This document provides information about the comprehensive integration test for all APIs in the GAIA agent.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
The integration test verifies that all APIs work together seamlessly in the GAIA agent. It tests:
|
| 8 |
+
|
| 9 |
+
1. **OpenAI** - For language model capabilities
|
| 10 |
+
2. **Perplexity** - For enhanced search and reasoning
|
| 11 |
+
3. **Serper** - For Google search results
|
| 12 |
+
4. **DuckDuckGo** - For web search without API key requirements
|
| 13 |
+
5. **arXiv** - For academic and scientific paper search
|
| 14 |
+
|
| 15 |
+
The test ensures that the agent can switch between different tools based on the task and maintain memory across different tool executions.
|
| 16 |
+
|
| 17 |
+
## Prerequisites
|
| 18 |
+
|
| 19 |
+
Before running the integration test, ensure you have the following environment variables set:
|
| 20 |
+
|
| 21 |
+
- `OPENAI_API_KEY` (required) - Your OpenAI API key
|
| 22 |
+
- `SERPER_API_KEY` (optional) - Your Serper API key for Google search
|
| 23 |
+
- `PERPLEXITY_API_KEY` (optional) - Your Perplexity API key
|
| 24 |
+
|
| 25 |
+
If optional API keys are not provided, the corresponding tests will be skipped.
|
| 26 |
+
|
| 27 |
+
## Running the Test
|
| 28 |
+
|
| 29 |
+
You can run the integration test using the provided runner script:
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
python tests/run_all_apis_integration_test.py
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
### Command-line Options
|
| 36 |
+
|
| 37 |
+
- `--verbose` or `-v`: Enable verbose logging for detailed output
|
| 38 |
+
- `--report-file` or `-r`: Specify a custom output file for the test report (default: `gaia_all_apis_integration_report.json`)
|
| 39 |
+
|
| 40 |
+
Example with options:
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
python tests/run_all_apis_integration_test.py --verbose --report-file my_report.json
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
## Test Components
|
| 47 |
+
|
| 48 |
+
The integration test consists of several components:
|
| 49 |
+
|
| 50 |
+
### 1. API Connection Tests
|
| 51 |
+
|
| 52 |
+
Verifies that the agent can connect to each API service. For each API, it:
|
| 53 |
+
- Checks if the required API key is available
|
| 54 |
+
- Attempts to establish a connection
|
| 55 |
+
- Verifies that the connection is successful
|
| 56 |
+
|
| 57 |
+
### 2. Individual Tool Execution Tests
|
| 58 |
+
|
| 59 |
+
Tests each tool individually with simple queries to ensure they work correctly:
|
| 60 |
+
- DuckDuckGo search
|
| 61 |
+
- Serper search
|
| 62 |
+
- Perplexity search
|
| 63 |
+
- arXiv search
|
| 64 |
+
- Robust search (fallback mechanism)
|
| 65 |
+
- Merged search (combining results from multiple providers)
|
| 66 |
+
|
| 67 |
+
### 3. Tool Switching Tests
|
| 68 |
+
|
| 69 |
+
Verifies that the agent can switch between different tools based on the task:
|
| 70 |
+
- Scientific questions (should use arXiv and Perplexity)
|
| 71 |
+
- Factual questions (should use DuckDuckGo and Serper)
|
| 72 |
+
- Explanatory questions (should use Perplexity)
|
| 73 |
+
|
| 74 |
+
### 4. Memory Integration Tests
|
| 75 |
+
|
| 76 |
+
Tests the agent's ability to maintain memory across different tool executions:
|
| 77 |
+
- Processes a sequence of related questions
|
| 78 |
+
- Verifies that the conversation history is maintained
|
| 79 |
+
- Checks for cached results and intermediate results
|
| 80 |
+
|
| 81 |
+
## Test Report
|
| 82 |
+
|
| 83 |
+
After running the test, a comprehensive report is generated in JSON format. The report includes:
|
| 84 |
+
|
| 85 |
+
- API connection results
|
| 86 |
+
- Tool execution results
|
| 87 |
+
- Complex query results
|
| 88 |
+
- Memory integration results
|
| 89 |
+
- Summary statistics
|
| 90 |
+
|
| 91 |
+
The report is displayed in the console and saved to the specified file.
|
| 92 |
+
|
| 93 |
+
## Interpreting Results
|
| 94 |
+
|
| 95 |
+
The test results are displayed with the following indicators:
|
| 96 |
+
|
| 97 |
+
- ✅ **PASS**: The test was successful
|
| 98 |
+
- ❌ **FAIL**: The test failed
|
| 99 |
+
- ⚠️ **SKIP**: The test was skipped (usually due to missing API keys)
|
| 100 |
+
|
| 101 |
+
### Example Output
|
| 102 |
+
|
| 103 |
+
```
|
| 104 |
+
================================================================================
|
| 105 |
+
GAIA ALL APIs INTEGRATION TEST REPORT
|
| 106 |
+
================================================================================
|
| 107 |
+
|
| 108 |
+
--------------------------------------------------------------------------------
|
| 109 |
+
SUMMARY
|
| 110 |
+
--------------------------------------------------------------------------------
|
| 111 |
+
Timestamp: 2025-04-30 18:00:00
|
| 112 |
+
Total APIs Tested: 5
|
| 113 |
+
Successful Connections: 4
|
| 114 |
+
Successful Tool Executions: 6
|
| 115 |
+
Successful Complex Queries: 3
|
| 116 |
+
Memory Integration Success: True
|
| 117 |
+
|
| 118 |
+
--------------------------------------------------------------------------------
|
| 119 |
+
API CONNECTIONS
|
| 120 |
+
--------------------------------------------------------------------------------
|
| 121 |
+
✅ PASS | openai: Successfully connected to OpenAI API
|
| 122 |
+
✅ PASS | perplexity: Successfully connected to Perplexity API
|
| 123 |
+
⚠️ SKIP | serper: Serper API key not available
|
| 124 |
+
✅ PASS | duckduckgo: Successfully connected to DuckDuckGo
|
| 125 |
+
✅ PASS | arxiv: Successfully connected to arXiv
|
| 126 |
+
|
| 127 |
+
...
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
## Troubleshooting
|
| 131 |
+
|
| 132 |
+
### Missing API Keys
|
| 133 |
+
|
| 134 |
+
If you see warnings about missing API keys, ensure that the environment variables are properly set:
|
| 135 |
+
|
| 136 |
+
```bash
|
| 137 |
+
export OPENAI_API_KEY=your_openai_api_key
|
| 138 |
+
export SERPER_API_KEY=your_serper_api_key
|
| 139 |
+
export PERPLEXITY_API_KEY=your_perplexity_api_key
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
### Connection Issues
|
| 143 |
+
|
| 144 |
+
If API connection tests fail:
|
| 145 |
+
1. Check your internet connection
|
| 146 |
+
2. Verify that your API keys are valid and not expired
|
| 147 |
+
3. Check if the API service is experiencing downtime
|
| 148 |
+
|
| 149 |
+
### Test Failures
|
| 150 |
+
|
| 151 |
+
If specific tests fail:
|
| 152 |
+
1. Check the error message in the report
|
| 153 |
+
2. Look for detailed error logs if running with `--verbose`
|
| 154 |
+
3. Verify that the required dependencies are installed
|
| 155 |
+
4. Check if there are any rate limits or quotas on the APIs
|
| 156 |
+
|
| 157 |
+
## Extending the Test
|
| 158 |
+
|
| 159 |
+
To add more test cases or test additional APIs:
|
| 160 |
+
|
| 161 |
+
1. Add new test methods to the `TestGAIAAllAPIsIntegration` class in `tests/test_gaia_all_apis_integration.py`
|
| 162 |
+
2. Update the report generation to include the new test results
|
| 163 |
+
3. Update this documentation to reflect the changes
|
| 164 |
+
|
| 165 |
+
## Related Documentation
|
| 166 |
+
|
| 167 |
+
- [OpenAI Integration Testing](openai_integration_testing.md)
|
| 168 |
+
- [Serper Integration](serper_integration.md)
|
| 169 |
+
- [DuckDuckGo Integration](duckduckgo_integration.md)
|
| 170 |
+
- [Multi-Search Integration](multi_search_integration.md)
|
docs/configuration.md
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA Agent Configuration Guide
|
| 2 |
+
|
| 3 |
+
This document provides detailed information about the configuration options available for the GAIA agent. Understanding these options will help you customize the agent's behavior to suit your specific needs.
|
| 4 |
+
|
| 5 |
+
## Configuration Overview
|
| 6 |
+
|
| 7 |
+
The GAIA agent uses a hierarchical configuration structure with the following main sections:
|
| 8 |
+
|
| 9 |
+
1. **Model Configuration**: Settings related to the language models used by the agent
|
| 10 |
+
2. **Tools Configuration**: Settings for the various tools used by the agent
|
| 11 |
+
3. **Memory Configuration**: Settings for the agent's memory components
|
| 12 |
+
4. **Agent Configuration**: General settings for the agent's behavior
|
| 13 |
+
|
| 14 |
+
## Configuration Methods
|
| 15 |
+
|
| 16 |
+
There are several ways to configure the GAIA agent:
|
| 17 |
+
|
| 18 |
+
1. **Environment Variables**: Set configuration values using environment variables
|
| 19 |
+
2. **Configuration Files**: Use a `.env` file or JSON configuration files
|
| 20 |
+
3. **Direct Configuration**: Pass a configuration dictionary when initializing the agent
|
| 21 |
+
|
| 22 |
+
## Model Configuration
|
| 23 |
+
|
| 24 |
+
The model configuration controls which language models are used by the agent and how they behave.
|
| 25 |
+
|
| 26 |
+
```python
|
| 27 |
+
model_config = {
|
| 28 |
+
"reasoning_model": "gpt-4o", # Model used for reasoning tasks (updated from gpt-4-turbo)
|
| 29 |
+
"tool_model": "gpt-3.5-turbo", # Model used for tool execution
|
| 30 |
+
"vision_model": "gpt-4o", # Model used for image analysis (updated from gpt-4-vision-preview)
|
| 31 |
+
"embedding_model": "text-embedding-3-large", # Model used for embeddings (updated from text-embedding-ada-002)
|
| 32 |
+
"temperature": 0.1, # Controls randomness (0.0 to 1.0)
|
| 33 |
+
"max_tokens": 4096, # Maximum number of tokens to generate
|
| 34 |
+
"top_p": 0.95, # Controls diversity via nucleus sampling
|
| 35 |
+
"frequency_penalty": 0.0, # Penalizes repeated tokens
|
| 36 |
+
"presence_penalty": 0.0 # Penalizes repeated topics
|
| 37 |
+
}
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
### Environment Variables
|
| 41 |
+
|
| 42 |
+
```
|
| 43 |
+
OPENAI_API_KEY=your-api-key
|
| 44 |
+
REASONING_MODEL=gpt-4o
|
| 45 |
+
TOOL_MODEL=gpt-3.5-turbo
|
| 46 |
+
VISION_MODEL=gpt-4o
|
| 47 |
+
EMBEDDING_MODEL=text-embedding-3-large
|
| 48 |
+
MODEL_TEMPERATURE=0.1
|
| 49 |
+
MODEL_MAX_TOKENS=4096
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
## Tools Configuration
|
| 53 |
+
|
| 54 |
+
The tools configuration controls which tools are available to the agent and how they behave.
|
| 55 |
+
|
| 56 |
+
```python
|
| 57 |
+
tools_config = {
|
| 58 |
+
"web_search": {
|
| 59 |
+
"enabled": True,
|
| 60 |
+
"providers": ["duckduckgo", "serper"],
|
| 61 |
+
"result_count": 5,
|
| 62 |
+
"timeout": 10
|
| 63 |
+
},
|
| 64 |
+
"web_content": {
|
| 65 |
+
"enabled": True,
|
| 66 |
+
"max_content_length": 10000,
|
| 67 |
+
"timeout": 15
|
| 68 |
+
},
|
| 69 |
+
"reasoning": {
|
| 70 |
+
"enabled": True,
|
| 71 |
+
"step_by_step": True,
|
| 72 |
+
"verification": True
|
| 73 |
+
},
|
| 74 |
+
"multimodal": {
|
| 75 |
+
"enabled": True,
|
| 76 |
+
"image_analysis": True,
|
| 77 |
+
"chart_interpretation": True,
|
| 78 |
+
"document_parsing": True
|
| 79 |
+
},
|
| 80 |
+
"arxiv": {
|
| 81 |
+
"enabled": True,
|
| 82 |
+
"max_results": 5,
|
| 83 |
+
"timeout": 10
|
| 84 |
+
},
|
| 85 |
+
"perplexity": {
|
| 86 |
+
"enabled": True,
|
| 87 |
+
"model": "sonar-medium-online",
|
| 88 |
+
"timeout": 15
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
### Environment Variables
|
| 94 |
+
|
| 95 |
+
```
|
| 96 |
+
ENABLE_WEB_SEARCH=true
|
| 97 |
+
SEARCH_PROVIDERS=duckduckgo,serper
|
| 98 |
+
SEARCH_RESULT_COUNT=5
|
| 99 |
+
SEARCH_TIMEOUT=10
|
| 100 |
+
ENABLE_WEB_CONTENT=true
|
| 101 |
+
MAX_CONTENT_LENGTH=10000
|
| 102 |
+
ENABLE_REASONING=true
|
| 103 |
+
ENABLE_MULTIMODAL=true
|
| 104 |
+
ENABLE_ARXIV=true
|
| 105 |
+
ARXIV_MAX_RESULTS=5
|
| 106 |
+
ENABLE_PERPLEXITY=true
|
| 107 |
+
PERPLEXITY_MODEL=sonar-medium-online
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
## Memory Configuration
|
| 111 |
+
|
| 112 |
+
The memory configuration controls how the agent stores and retrieves information.
|
| 113 |
+
|
| 114 |
+
```python
|
| 115 |
+
memory_config = {
|
| 116 |
+
"supabase": {
|
| 117 |
+
"url": "https://tjamxhvvtnypbadvrkjq.supabase.co",
|
| 118 |
+
"key": "your-api-key",
|
| 119 |
+
"project_id": "tjamxhvvtnypbadvrkjq",
|
| 120 |
+
"project_name": "HF_GAIA_Assessment_AGT",
|
| 121 |
+
"table": "gaia_memory"
|
| 122 |
+
},
|
| 123 |
+
"conversation_memory": {
|
| 124 |
+
"enabled": True,
|
| 125 |
+
"max_messages": 100,
|
| 126 |
+
"table": "gaia_memory_conversations"
|
| 127 |
+
},
|
| 128 |
+
"result_cache": {
|
| 129 |
+
"enabled": True,
|
| 130 |
+
"ttl": 3600, # Time-to-live in seconds
|
| 131 |
+
"table": "gaia_memory_cache"
|
| 132 |
+
},
|
| 133 |
+
"working_memory": {
|
| 134 |
+
"enabled": True,
|
| 135 |
+
"max_items": 50,
|
| 136 |
+
"table": "gaia_memory_working"
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
### Environment Variables
|
| 142 |
+
|
| 143 |
+
```
|
| 144 |
+
# Supabase Configuration
|
| 145 |
+
SUPABASE_URL=https://tjamxhvvtnypbadvrkjq.supabase.co
|
| 146 |
+
SUPABASE_KEY=your-api-key
|
| 147 |
+
SUPABASE_PROJECT_ID=tjamxhvvtnypbadvrkjq
|
| 148 |
+
SUPABASE_PROJECT_NAME=HF_GAIA_Assessment_AGT
|
| 149 |
+
MEMORY_TABLE_NAME=gaia_memory
|
| 150 |
+
|
| 151 |
+
# Memory Settings
|
| 152 |
+
MEMORY_ENABLED=true
|
| 153 |
+
MEMORY_TTL=86400
|
| 154 |
+
MEMORY_CACHE_SIZE=100
|
| 155 |
+
MEMORY_SIMILARITY_THRESHOLD=0.85
|
| 156 |
+
MEMORY_MAX_ENTRIES=1000
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
## Agent Configuration
|
| 160 |
+
|
| 161 |
+
The agent configuration controls the general behavior of the agent.
|
| 162 |
+
|
| 163 |
+
```python
|
| 164 |
+
agent_config = {
|
| 165 |
+
"max_retries": 3, # Maximum number of retries for failed operations
|
| 166 |
+
"retry_delay": 1.0, # Delay between retries in seconds
|
| 167 |
+
"timeout": 300, # Overall timeout for processing a question
|
| 168 |
+
"max_iterations": 10, # Maximum number of iterations in the workflow
|
| 169 |
+
"return_error_message": False, # Whether to return error messages or raise exceptions
|
| 170 |
+
"verbose": False # Whether to enable verbose logging
|
| 171 |
+
}
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
### Environment Variables
|
| 175 |
+
|
| 176 |
+
```
|
| 177 |
+
AGENT_MAX_RETRIES=3
|
| 178 |
+
AGENT_RETRY_DELAY=1.0
|
| 179 |
+
AGENT_TIMEOUT=300
|
| 180 |
+
AGENT_MAX_ITERATIONS=10
|
| 181 |
+
RETURN_ERROR_MESSAGE=false
|
| 182 |
+
VERBOSE=false
|
| 183 |
+
```
|
| 184 |
+
|
| 185 |
+
## Complete Configuration Example
|
| 186 |
+
|
| 187 |
+
Here's a complete example of a configuration dictionary that you can pass when initializing the agent:
|
| 188 |
+
|
| 189 |
+
```python
|
| 190 |
+
config = {
|
| 191 |
+
"model": {
|
| 192 |
+
"reasoning_model": "gpt-4o",
|
| 193 |
+
"tool_model": "gpt-3.5-turbo",
|
| 194 |
+
"vision_model": "gpt-4o",
|
| 195 |
+
"embedding_model": "text-embedding-3-large",
|
| 196 |
+
"temperature": 0.1,
|
| 197 |
+
"max_tokens": 4096
|
| 198 |
+
},
|
| 199 |
+
"tools": {
|
| 200 |
+
"web_search": {
|
| 201 |
+
"enabled": True,
|
| 202 |
+
"providers": ["duckduckgo", "serper"],
|
| 203 |
+
"result_count": 5,
|
| 204 |
+
"timeout": 10
|
| 205 |
+
},
|
| 206 |
+
"web_content": {
|
| 207 |
+
"enabled": True,
|
| 208 |
+
"max_content_length": 10000,
|
| 209 |
+
"timeout": 15
|
| 210 |
+
},
|
| 211 |
+
"reasoning": {
|
| 212 |
+
"enabled": True,
|
| 213 |
+
"step_by_step": True,
|
| 214 |
+
"verification": True
|
| 215 |
+
},
|
| 216 |
+
"multimodal": {
|
| 217 |
+
"enabled": True,
|
| 218 |
+
"image_analysis": True,
|
| 219 |
+
"chart_interpretation": True,
|
| 220 |
+
"document_parsing": True
|
| 221 |
+
},
|
| 222 |
+
"arxiv": {
|
| 223 |
+
"enabled": True,
|
| 224 |
+
"max_results": 5,
|
| 225 |
+
"timeout": 10
|
| 226 |
+
},
|
| 227 |
+
"perplexity": {
|
| 228 |
+
"enabled": True,
|
| 229 |
+
"model": "sonar-medium-online",
|
| 230 |
+
"timeout": 15
|
| 231 |
+
}
|
| 232 |
+
},
|
| 233 |
+
"memory": {
|
| 234 |
+
"supabase": {
|
| 235 |
+
"url": "https://tjamxhvvtnypbadvrkjq.supabase.co",
|
| 236 |
+
"key": "your-api-key",
|
| 237 |
+
"project_id": "tjamxhvvtnypbadvrkjq",
|
| 238 |
+
"project_name": "HF_GAIA_Assessment_AGT",
|
| 239 |
+
"table": "gaia_memory"
|
| 240 |
+
},
|
| 241 |
+
"conversation_memory": {
|
| 242 |
+
"enabled": True,
|
| 243 |
+
"max_messages": 100,
|
| 244 |
+
"table": "gaia_memory_conversations"
|
| 245 |
+
},
|
| 246 |
+
"result_cache": {
|
| 247 |
+
"enabled": True,
|
| 248 |
+
"ttl": 3600,
|
| 249 |
+
"table": "gaia_memory_cache"
|
| 250 |
+
},
|
| 251 |
+
"working_memory": {
|
| 252 |
+
"enabled": True,
|
| 253 |
+
"max_items": 50,
|
| 254 |
+
"table": "gaia_memory_working"
|
| 255 |
+
}
|
| 256 |
+
},
|
| 257 |
+
"agent": {
|
| 258 |
+
"max_retries": 3,
|
| 259 |
+
"retry_delay": 1.0,
|
| 260 |
+
"timeout": 300,
|
| 261 |
+
"max_iterations": 10,
|
| 262 |
+
"return_error_message": False,
|
| 263 |
+
"verbose": False
|
| 264 |
+
}
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
from agent import GAIAAgent
|
| 268 |
+
agent = GAIAAgent(config)
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
## Environment Variables File (.env)
|
| 272 |
+
|
| 273 |
+
You can also use a `.env` file to configure the agent. Here's an example:
|
| 274 |
+
|
| 275 |
+
```
|
| 276 |
+
# API Keys and Endpoints
|
| 277 |
+
OPENAI_API_KEY=your-openai-api-key
|
| 278 |
+
SERPER_API_KEY=your-serper-api-key
|
| 279 |
+
PERPLEXITY_API_KEY=your-perplexity-api-key
|
| 280 |
+
|
| 281 |
+
# Supabase Configuration
|
| 282 |
+
SUPABASE_URL=https://tjamxhvvtnypbadvrkjq.supabase.co
|
| 283 |
+
SUPABASE_KEY=your-supabase-api-key
|
| 284 |
+
SUPABASE_PROJECT_ID=tjamxhvvtnypbadvrkjq
|
| 285 |
+
SUPABASE_PROJECT_NAME=HF_GAIA_Assessment_AGT
|
| 286 |
+
|
| 287 |
+
# Hugging Face Configuration
|
| 288 |
+
HF_TOKEN=your-huggingface-token
|
| 289 |
+
|
| 290 |
+
# Model Configuration
|
| 291 |
+
REASONING_MODEL=gpt-4o
|
| 292 |
+
TOOL_MODEL=gpt-3.5-turbo
|
| 293 |
+
VISION_MODEL=gpt-4o
|
| 294 |
+
EMBEDDING_MODEL=text-embedding-3-large
|
| 295 |
+
MODEL_TEMPERATURE=0.1
|
| 296 |
+
MODEL_MAX_TOKENS=4096
|
| 297 |
+
|
| 298 |
+
# Tools Configuration
|
| 299 |
+
ENABLE_WEB_SEARCH=true
|
| 300 |
+
SEARCH_PROVIDERS=duckduckgo,serper
|
| 301 |
+
SEARCH_RESULT_COUNT=5
|
| 302 |
+
ENABLE_WEB_CONTENT=true
|
| 303 |
+
ENABLE_REASONING=true
|
| 304 |
+
ENABLE_MULTIMODAL=true
|
| 305 |
+
ENABLE_ARXIV=true
|
| 306 |
+
ENABLE_PERPLEXITY=true
|
| 307 |
+
|
| 308 |
+
# Memory Configuration
|
| 309 |
+
ENABLE_CONVERSATION_MEMORY=true
|
| 310 |
+
ENABLE_RESULT_CACHE=true
|
| 311 |
+
ENABLE_WORKING_MEMORY=true
|
| 312 |
+
|
| 313 |
+
# Agent Configuration
|
| 314 |
+
AGENT_MAX_RETRIES=3
|
| 315 |
+
AGENT_TIMEOUT=300
|
| 316 |
+
VERBOSE=false
|
| 317 |
+
```
|
| 318 |
+
|
| 319 |
+
## Dependencies
|
| 320 |
+
|
| 321 |
+
The GAIA agent relies on several key dependencies:
|
| 322 |
+
|
| 323 |
+
1. **langchain**: Core framework for building language model applications
|
| 324 |
+
2. **langchain_openai**: OpenAI integration for LangChain (separate package)
|
| 325 |
+
3. **langgraph**: Framework for building complex agent workflows
|
| 326 |
+
4. **supabase**: Python client for Supabase
|
| 327 |
+
5. **duckduckgo-search**: Client for DuckDuckGo search
|
| 328 |
+
6. **perplexity-python**: Client for Perplexity AI
|
| 329 |
+
7. **arxiv**: Client for arXiv search
|
| 330 |
+
|
| 331 |
+
Make sure these dependencies are installed and up-to-date:
|
| 332 |
+
|
| 333 |
+
```bash
|
| 334 |
+
pip install --upgrade langchain langchain_openai langgraph supabase duckduckgo-search perplexity-python arxiv
|
| 335 |
+
```
|
| 336 |
+
|
| 337 |
+
> **Note**: The `langchain_openai` package is now separate from the core `langchain` package. If you encounter import errors, make sure you have the latest version installed.
|
| 338 |
+
|
| 339 |
+
## Configuration Precedence
|
| 340 |
+
|
| 341 |
+
The agent uses the following precedence order when determining configuration values:
|
| 342 |
+
|
| 343 |
+
1. Direct configuration passed to the constructor
|
| 344 |
+
2. Environment variables
|
| 345 |
+
3. Default values defined in the code
|
| 346 |
+
|
| 347 |
+
This means that values passed directly to the constructor will override environment variables, which in turn override the default values.
|
| 348 |
+
|
| 349 |
+
## Troubleshooting
|
| 350 |
+
|
| 351 |
+
If you encounter configuration issues, check the [Troubleshooting Guide](troubleshooting.md) for common problems and solutions.
|
| 352 |
+
|
| 353 |
+
## Next Steps
|
| 354 |
+
|
| 355 |
+
For usage examples, see [Usage Examples](examples.md).
|
| 356 |
+
|
| 357 |
+
For deployment instructions, see [Deployment Guide](deployment.md).
|
docs/connection_verification.md
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Connection Verification Guide
|
| 2 |
+
|
| 3 |
+
This guide explains how to verify connections to external services used by the GAIA agent.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
The GAIA agent relies on several external services:
|
| 8 |
+
|
| 9 |
+
1. **OpenAI API** - For language model access
|
| 10 |
+
2. **Perplexity API** - For web search and reasoning
|
| 11 |
+
3. **Supabase** - For memory storage
|
| 12 |
+
4. **Serper API** - For web search
|
| 13 |
+
|
| 14 |
+
Proper connection to these services is essential for the agent to function correctly.
|
| 15 |
+
|
| 16 |
+
## Verification Tools
|
| 17 |
+
|
| 18 |
+
The project includes several tools to verify connections:
|
| 19 |
+
|
| 20 |
+
1. `tests/verify_connections.py` - A comprehensive test script that verifies all connections
|
| 21 |
+
2. `direct_config_check.py` - A simple script to verify configuration values
|
| 22 |
+
|
| 23 |
+
## Verifying All Connections
|
| 24 |
+
|
| 25 |
+
To verify all connections at once, run:
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
python -m tests.verify_connections
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
This script will:
|
| 32 |
+
- Check if all required API keys are set
|
| 33 |
+
- Test connections to each service
|
| 34 |
+
- Report success or failure for each connection
|
| 35 |
+
|
| 36 |
+
## Verifying Individual Connections
|
| 37 |
+
|
| 38 |
+
### OpenAI API
|
| 39 |
+
|
| 40 |
+
To verify the OpenAI API connection:
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
python -m tests.verify_connections --service openai
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
### Perplexity API
|
| 47 |
+
|
| 48 |
+
To verify the Perplexity API connection:
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
python -m tests.verify_connections --service perplexity
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
You can also use the dedicated Perplexity test:
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
python -m tests.test_perplexity_sonar
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
### Supabase
|
| 61 |
+
|
| 62 |
+
To verify the Supabase connection:
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
python -m tests.verify_connections --service supabase
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
### Serper API
|
| 69 |
+
|
| 70 |
+
To verify the Serper API connection:
|
| 71 |
+
|
| 72 |
+
```bash
|
| 73 |
+
python -m tests.verify_connections --service serper
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
## Troubleshooting Connection Issues
|
| 77 |
+
|
| 78 |
+
### API Key Issues
|
| 79 |
+
|
| 80 |
+
If you encounter API key issues:
|
| 81 |
+
|
| 82 |
+
1. Check that the key is correctly set in your `.env` file
|
| 83 |
+
2. Verify the key format (no extra spaces or characters)
|
| 84 |
+
3. Ensure the key has not expired
|
| 85 |
+
4. Check if the service has usage limits that you've exceeded
|
| 86 |
+
|
| 87 |
+
### Network Issues
|
| 88 |
+
|
| 89 |
+
If you encounter network issues:
|
| 90 |
+
|
| 91 |
+
1. Check your internet connection
|
| 92 |
+
2. Verify that your firewall or network settings allow connections to the service
|
| 93 |
+
3. Check if the service is experiencing downtime
|
| 94 |
+
|
| 95 |
+
### Configuration Issues
|
| 96 |
+
|
| 97 |
+
If you encounter configuration issues:
|
| 98 |
+
|
| 99 |
+
1. Run `python direct_config_check.py` to verify configuration values
|
| 100 |
+
2. Check that the configuration in `agent/config.py` is correct
|
| 101 |
+
3. Ensure environment variables are properly loaded
|
| 102 |
+
|
| 103 |
+
## Setting Up API Keys
|
| 104 |
+
|
| 105 |
+
All API keys should be stored in a `.env` file in the project root:
|
| 106 |
+
|
| 107 |
+
```
|
| 108 |
+
OPENAI_API_KEY=your_openai_key
|
| 109 |
+
PERPLEXITY_API_KEY=your_perplexity_key
|
| 110 |
+
SERPER_API_KEY=your_serper_key
|
| 111 |
+
SUPABASE_KEY=your_supabase_key
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
Never commit this file to version control.
|
docs/deployment.md
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA Agent Deployment Guide
|
| 2 |
+
|
| 3 |
+
This document provides instructions for deploying the GAIA agent in various environments, from local development to production settings.
|
| 4 |
+
|
| 5 |
+
## Prerequisites
|
| 6 |
+
|
| 7 |
+
Before deploying the GAIA agent, ensure you have:
|
| 8 |
+
|
| 9 |
+
1. Python 3.8 or higher installed
|
| 10 |
+
2. All required dependencies installed
|
| 11 |
+
3. API keys for any external services (OpenAI, Serper, Supabase, etc.)
|
| 12 |
+
4. Sufficient resources for your expected workload
|
| 13 |
+
|
| 14 |
+
## Local Deployment
|
| 15 |
+
|
| 16 |
+
### Installation
|
| 17 |
+
|
| 18 |
+
1. Clone the repository:
|
| 19 |
+
```bash
|
| 20 |
+
git clone https://github.com/yourusername/gaia-agent.git
|
| 21 |
+
cd gaia-agent
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
2. Create a virtual environment:
|
| 25 |
+
```bash
|
| 26 |
+
python -m venv venv
|
| 27 |
+
source venv/bin/activate # On Windows: venv\Scripts\activate
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
3. Install dependencies:
|
| 31 |
+
```bash
|
| 32 |
+
pip install -r requirements.txt
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
4. Create a `.env` file with your configuration:
|
| 36 |
+
```
|
| 37 |
+
OPENAI_API_KEY=your-openai-api-key
|
| 38 |
+
SERPER_API_KEY=your-serper-api-key
|
| 39 |
+
SUPABASE_URL=https://your-project-url.supabase.co
|
| 40 |
+
SUPABASE_KEY=your-supabase-api-key
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
5. Run the application:
|
| 44 |
+
```bash
|
| 45 |
+
python app.py
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
### Testing
|
| 49 |
+
|
| 50 |
+
Before deploying to production, run the test suite to ensure everything is working correctly:
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
# Run all tests
|
| 54 |
+
python -m unittest discover tests
|
| 55 |
+
|
| 56 |
+
# Run benchmark tests
|
| 57 |
+
python -m tests.benchmark --output benchmark_results.json
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
## Deployment Options
|
| 61 |
+
|
| 62 |
+
### Hugging Face Spaces
|
| 63 |
+
|
| 64 |
+
The GAIA agent is designed to be easily deployed to Hugging Face Spaces:
|
| 65 |
+
|
| 66 |
+
1. Create a new Space on Hugging Face:
|
| 67 |
+
- Go to https://huggingface.co/spaces
|
| 68 |
+
- Click "Create new Space"
|
| 69 |
+
- Select "Gradio" as the SDK
|
| 70 |
+
- Choose a name for your Space
|
| 71 |
+
|
| 72 |
+
2. Configure your Space:
|
| 73 |
+
- Add your API keys as secrets in the Space settings
|
| 74 |
+
- Set the Python version to 3.8 or higher
|
| 75 |
+
|
| 76 |
+
3. Push your code to the Space:
|
| 77 |
+
```bash
|
| 78 |
+
git remote add space https://huggingface.co/spaces/yourusername/your-space-name
|
| 79 |
+
git push space main
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
4. Your agent will be automatically deployed and available at `https://huggingface.co/spaces/yourusername/your-space-name`
|
| 83 |
+
|
| 84 |
+
### Docker Deployment
|
| 85 |
+
|
| 86 |
+
For containerized deployment, you can use Docker:
|
| 87 |
+
|
| 88 |
+
1. Create a Dockerfile:
|
| 89 |
+
```dockerfile
|
| 90 |
+
FROM python:3.9-slim
|
| 91 |
+
|
| 92 |
+
WORKDIR /app
|
| 93 |
+
|
| 94 |
+
COPY requirements.txt .
|
| 95 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 96 |
+
|
| 97 |
+
COPY . .
|
| 98 |
+
|
| 99 |
+
CMD ["python", "app.py"]
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
2. Build the Docker image:
|
| 103 |
+
```bash
|
| 104 |
+
docker build -t gaia-agent .
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
3. Run the container:
|
| 108 |
+
```bash
|
| 109 |
+
docker run -p 7860:7860 --env-file .env gaia-agent
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
### Cloud Deployment
|
| 113 |
+
|
| 114 |
+
#### AWS Elastic Beanstalk
|
| 115 |
+
|
| 116 |
+
1. Install the EB CLI:
|
| 117 |
+
```bash
|
| 118 |
+
pip install awsebcli
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
2. Initialize your EB application:
|
| 122 |
+
```bash
|
| 123 |
+
eb init -p python-3.8 gaia-agent
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
3. Create an environment:
|
| 127 |
+
```bash
|
| 128 |
+
eb create gaia-agent-env
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
4. Configure environment variables:
|
| 132 |
+
```bash
|
| 133 |
+
eb setenv OPENAI_API_KEY=your-openai-api-key SERPER_API_KEY=your-serper-api-key
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
5. Deploy your application:
|
| 137 |
+
```bash
|
| 138 |
+
eb deploy
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
#### Google Cloud Run
|
| 142 |
+
|
| 143 |
+
1. Build and push your Docker image to Google Container Registry:
|
| 144 |
+
```bash
|
| 145 |
+
gcloud builds submit --tag gcr.io/your-project-id/gaia-agent
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
2. Deploy to Cloud Run:
|
| 149 |
+
```bash
|
| 150 |
+
gcloud run deploy gaia-agent \
|
| 151 |
+
--image gcr.io/your-project-id/gaia-agent \
|
| 152 |
+
--platform managed \
|
| 153 |
+
--set-env-vars OPENAI_API_KEY=your-openai-api-key,SERPER_API_KEY=your-serper-api-key
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
## Scaling Considerations
|
| 157 |
+
|
| 158 |
+
### Memory Usage
|
| 159 |
+
|
| 160 |
+
The GAIA agent can be memory-intensive, especially when processing complex questions or using large language models. Consider the following:
|
| 161 |
+
|
| 162 |
+
- Monitor memory usage during benchmark testing
|
| 163 |
+
- Adjust `max_tokens` and other model parameters to control memory usage
|
| 164 |
+
- Consider using a memory cache for frequently asked questions
|
| 165 |
+
|
| 166 |
+
### API Rate Limits
|
| 167 |
+
|
| 168 |
+
Be aware of rate limits for external APIs:
|
| 169 |
+
|
| 170 |
+
- OpenAI has rate limits based on your subscription tier
|
| 171 |
+
- Serper and other search APIs typically have daily or monthly quotas
|
| 172 |
+
- Implement retry logic with exponential backoff for rate limit errors
|
| 173 |
+
|
| 174 |
+
### Cost Management
|
| 175 |
+
|
| 176 |
+
Using external APIs can incur costs:
|
| 177 |
+
|
| 178 |
+
- Monitor your API usage and costs
|
| 179 |
+
- Consider caching results to reduce API calls
|
| 180 |
+
- Use smaller or less expensive models for simpler tasks
|
| 181 |
+
|
| 182 |
+
## Production Best Practices
|
| 183 |
+
|
| 184 |
+
### Logging
|
| 185 |
+
|
| 186 |
+
Implement comprehensive logging:
|
| 187 |
+
|
| 188 |
+
```python
|
| 189 |
+
import logging
|
| 190 |
+
|
| 191 |
+
logging.basicConfig(
|
| 192 |
+
level=logging.INFO,
|
| 193 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 194 |
+
filename='gaia_agent.log'
|
| 195 |
+
)
|
| 196 |
+
```
|
| 197 |
+
|
| 198 |
+
### Monitoring
|
| 199 |
+
|
| 200 |
+
Set up monitoring for:
|
| 201 |
+
|
| 202 |
+
- API response times
|
| 203 |
+
- Error rates
|
| 204 |
+
- Memory and CPU usage
|
| 205 |
+
- Cost metrics
|
| 206 |
+
|
| 207 |
+
### Security
|
| 208 |
+
|
| 209 |
+
Protect sensitive information:
|
| 210 |
+
|
| 211 |
+
- Never hardcode API keys in your code
|
| 212 |
+
- Use environment variables or a secure secrets manager
|
| 213 |
+
- Implement proper authentication for your API endpoints
|
| 214 |
+
- Validate and sanitize all user inputs
|
| 215 |
+
|
| 216 |
+
### Backup and Recovery
|
| 217 |
+
|
| 218 |
+
Implement backup and recovery procedures:
|
| 219 |
+
|
| 220 |
+
- Regularly backup your Supabase database
|
| 221 |
+
- Create snapshots of your deployment environment
|
| 222 |
+
- Document recovery procedures
|
| 223 |
+
|
| 224 |
+
## Continuous Integration/Continuous Deployment (CI/CD)
|
| 225 |
+
|
| 226 |
+
Set up CI/CD pipelines to automate testing and deployment:
|
| 227 |
+
|
| 228 |
+
### GitHub Actions Example
|
| 229 |
+
|
| 230 |
+
Create a `.github/workflows/main.yml` file:
|
| 231 |
+
|
| 232 |
+
```yaml
|
| 233 |
+
name: CI/CD Pipeline
|
| 234 |
+
|
| 235 |
+
on:
|
| 236 |
+
push:
|
| 237 |
+
branches: [ main ]
|
| 238 |
+
pull_request:
|
| 239 |
+
branches: [ main ]
|
| 240 |
+
|
| 241 |
+
jobs:
|
| 242 |
+
test:
|
| 243 |
+
runs-on: ubuntu-latest
|
| 244 |
+
steps:
|
| 245 |
+
- uses: actions/checkout@v2
|
| 246 |
+
- name: Set up Python
|
| 247 |
+
uses: actions/setup-python@v2
|
| 248 |
+
with:
|
| 249 |
+
python-version: '3.9'
|
| 250 |
+
- name: Install dependencies
|
| 251 |
+
run: |
|
| 252 |
+
python -m pip install --upgrade pip
|
| 253 |
+
pip install -r requirements.txt
|
| 254 |
+
- name: Run tests
|
| 255 |
+
run: |
|
| 256 |
+
python -m unittest discover tests
|
| 257 |
+
|
| 258 |
+
deploy:
|
| 259 |
+
needs: test
|
| 260 |
+
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
| 261 |
+
runs-on: ubuntu-latest
|
| 262 |
+
steps:
|
| 263 |
+
- uses: actions/checkout@v2
|
| 264 |
+
- name: Deploy to Hugging Face Spaces
|
| 265 |
+
uses: huggingface/huggingface-spaces-deploy-action@main
|
| 266 |
+
with:
|
| 267 |
+
space_id: ${{ secrets.SPACE_ID }}
|
| 268 |
+
token: ${{ secrets.HF_TOKEN }}
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
## Troubleshooting
|
| 272 |
+
|
| 273 |
+
### Common Issues
|
| 274 |
+
|
| 275 |
+
1. **API Key Errors**:
|
| 276 |
+
- Ensure all API keys are correctly set in your environment variables
|
| 277 |
+
- Check for typos or trailing spaces in your API keys
|
| 278 |
+
|
| 279 |
+
2. **Memory Issues**:
|
| 280 |
+
- Reduce the `max_tokens` parameter in your model configuration
|
| 281 |
+
- Implement memory cleanup after processing each question
|
| 282 |
+
|
| 283 |
+
3. **Timeout Errors**:
|
| 284 |
+
- Increase the timeout values in your configuration
|
| 285 |
+
- Optimize your agent's workflow to reduce processing time
|
| 286 |
+
|
| 287 |
+
4. **Rate Limit Errors**:
|
| 288 |
+
- Implement retry logic with exponential backoff
|
| 289 |
+
- Consider upgrading your API subscription tier
|
| 290 |
+
|
| 291 |
+
### Getting Help
|
| 292 |
+
|
| 293 |
+
If you encounter issues not covered in this guide:
|
| 294 |
+
|
| 295 |
+
1. Check the project's GitHub issues for similar problems
|
| 296 |
+
2. Consult the documentation for the specific components (LangChain, LangGraph, etc.)
|
| 297 |
+
3. Reach out to the community for assistance
|
| 298 |
+
|
| 299 |
+
## Next Steps
|
| 300 |
+
|
| 301 |
+
For usage examples, see [Usage Examples](examples.md).
|
| 302 |
+
|
| 303 |
+
For configuration options, see [Configuration Guide](configuration.md).
|
docs/duckduckgo_integration.md
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DuckDuckGo Integration for GAIA Agent
|
| 2 |
+
|
| 3 |
+
This document describes how to set up and use the DuckDuckGo search integration with the GAIA agent.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
The GAIA agent now supports DuckDuckGo as an alternative search engine for web searches. This integration allows the agent to perform web searches without requiring an API key, making it a good fallback option when other search providers are unavailable or rate-limited.
|
| 8 |
+
|
| 9 |
+
## Features
|
| 10 |
+
|
| 11 |
+
- **No API Key Required**: DuckDuckGo search works without requiring an API key
|
| 12 |
+
- **Configurable Result Count**: Control how many search results are returned
|
| 13 |
+
- **Error Handling**: Robust error handling for various search scenarios
|
| 14 |
+
- **Standardized Results**: Results are formatted consistently with other search providers
|
| 15 |
+
|
| 16 |
+
## Installation
|
| 17 |
+
|
| 18 |
+
The DuckDuckGo integration requires the `duckduckgo-search` package:
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
pip install duckduckgo-search
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
## Configuration
|
| 25 |
+
|
| 26 |
+
The DuckDuckGo search tool can be configured in the GAIA agent's configuration:
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
# In agent/config.py
|
| 30 |
+
class GaiaConfig:
|
| 31 |
+
def __init__(self):
|
| 32 |
+
# ...
|
| 33 |
+
self.duckduckgo_enabled = True
|
| 34 |
+
self.duckduckgo_result_count = 5
|
| 35 |
+
# ...
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
### Configuration Options
|
| 39 |
+
|
| 40 |
+
| Option | Description | Default |
|
| 41 |
+
|--------|-------------|---------|
|
| 42 |
+
| `duckduckgo_enabled` | Enable/disable DuckDuckGo search | `True` |
|
| 43 |
+
| `duckduckgo_result_count` | Number of results to return | `5` |
|
| 44 |
+
| `duckduckgo_timeout` | Timeout in seconds for search requests | `30` |
|
| 45 |
+
|
| 46 |
+
## Usage
|
| 47 |
+
|
| 48 |
+
### Basic Usage
|
| 49 |
+
|
| 50 |
+
```python
|
| 51 |
+
from tools.web_tools import create_duckduckgo_search
|
| 52 |
+
|
| 53 |
+
# Create a DuckDuckGo search tool
|
| 54 |
+
search_tool = create_duckduckgo_search()
|
| 55 |
+
|
| 56 |
+
# Perform a search
|
| 57 |
+
results = search_tool.search("python programming")
|
| 58 |
+
|
| 59 |
+
# Process the results
|
| 60 |
+
for result in results:
|
| 61 |
+
print(f"Title: {result['title']}")
|
| 62 |
+
print(f"URL: {result['link']}")
|
| 63 |
+
print(f"Snippet: {result['snippet']}")
|
| 64 |
+
print("---")
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
### Integration with GAIA Agent
|
| 68 |
+
|
| 69 |
+
The DuckDuckGo search tool is automatically integrated with the GAIA agent if enabled in the configuration:
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
from agent.agent import GaiaAgent
|
| 73 |
+
from agent.config import GaiaConfig
|
| 74 |
+
|
| 75 |
+
# Create a configuration with DuckDuckGo enabled
|
| 76 |
+
config = GaiaConfig()
|
| 77 |
+
config.duckduckgo_enabled = True
|
| 78 |
+
|
| 79 |
+
# Create a GAIA agent with the configuration
|
| 80 |
+
agent = GaiaAgent(config=config)
|
| 81 |
+
|
| 82 |
+
# The agent will now use DuckDuckGo for web searches
|
| 83 |
+
response = agent.process("What is the latest version of Python?")
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
## Result Format
|
| 87 |
+
|
| 88 |
+
The DuckDuckGo search tool returns results in the following format:
|
| 89 |
+
|
| 90 |
+
```json
|
| 91 |
+
[
|
| 92 |
+
{
|
| 93 |
+
"title": "Result title",
|
| 94 |
+
"link": "https://example.com/result",
|
| 95 |
+
"snippet": "A brief excerpt from the search result..."
|
| 96 |
+
},
|
| 97 |
+
// More results...
|
| 98 |
+
]
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
## Fallback Mechanism
|
| 102 |
+
|
| 103 |
+
The GAIA agent can be configured to use DuckDuckGo as a fallback when other search providers fail:
|
| 104 |
+
|
| 105 |
+
```python
|
| 106 |
+
# In agent/config.py
|
| 107 |
+
class GaiaConfig:
|
| 108 |
+
def __init__(self):
|
| 109 |
+
# ...
|
| 110 |
+
self.search_fallback_order = ["serper", "duckduckgo", "perplexity"]
|
| 111 |
+
# ...
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
With this configuration, the agent will try Serper first, then DuckDuckGo if Serper fails, and finally Perplexity if both fail.
|
| 115 |
+
|
| 116 |
+
## Testing
|
| 117 |
+
|
| 118 |
+
You can test the DuckDuckGo integration using the provided test scripts:
|
| 119 |
+
|
| 120 |
+
```bash
|
| 121 |
+
# Test just the DuckDuckGo search
|
| 122 |
+
python tests/test_duckduckgo_search.py
|
| 123 |
+
|
| 124 |
+
# Test all search providers together
|
| 125 |
+
python tests/test_gaia_multi_search_providers.py
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
## Troubleshooting
|
| 129 |
+
|
| 130 |
+
### Common Issues
|
| 131 |
+
|
| 132 |
+
1. **No Results Returned**: DuckDuckGo may return no results for certain queries. Try reformulating the query.
|
| 133 |
+
|
| 134 |
+
2. **Connection Errors**: If you're experiencing connection errors, check your internet connection and ensure that DuckDuckGo is accessible from your network.
|
| 135 |
+
|
| 136 |
+
3. **Rate Limiting**: While DuckDuckGo doesn't require an API key, it may still rate-limit excessive requests. Consider adding delays between searches if you're making many requests.
|
| 137 |
+
|
| 138 |
+
### Debugging
|
| 139 |
+
|
| 140 |
+
To enable debug logging for the DuckDuckGo search tool:
|
| 141 |
+
|
| 142 |
+
```python
|
| 143 |
+
import logging
|
| 144 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 145 |
+
logger = logging.getLogger("tools.web_tools")
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
## Limitations
|
| 149 |
+
|
| 150 |
+
- DuckDuckGo search may not provide as many results as commercial search APIs
|
| 151 |
+
- Some advanced search features (like filtering by date) may not be available
|
| 152 |
+
- Results may be less comprehensive than those from paid search providers
|
| 153 |
+
|
| 154 |
+
## Conclusion
|
| 155 |
+
|
| 156 |
+
The DuckDuckGo integration provides a reliable, no-cost alternative for web searches in the GAIA agent. It's particularly useful as a fallback option or for development and testing purposes.
|
docs/examples.md
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA Agent Usage Examples
|
| 2 |
+
|
| 3 |
+
This document provides examples of how to use the GAIA agent in different scenarios. These examples demonstrate the agent's capabilities and how to integrate it into your applications.
|
| 4 |
+
|
| 5 |
+
## Basic Usage
|
| 6 |
+
|
| 7 |
+
### Initializing the Agent
|
| 8 |
+
|
| 9 |
+
```python
|
| 10 |
+
from agent import GAIAAgent
|
| 11 |
+
|
| 12 |
+
# Initialize with default configuration
|
| 13 |
+
agent = GAIAAgent()
|
| 14 |
+
|
| 15 |
+
# Or with custom configuration
|
| 16 |
+
custom_config = {
|
| 17 |
+
"model": {
|
| 18 |
+
"reasoning_model": "gpt-4",
|
| 19 |
+
"temperature": 0.2,
|
| 20 |
+
"max_tokens": 1000
|
| 21 |
+
},
|
| 22 |
+
"tools": {
|
| 23 |
+
"web_search": {
|
| 24 |
+
"enabled": True,
|
| 25 |
+
"providers": ["duckduckgo", "serper"]
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
agent = GAIAAgent(custom_config)
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
### Asking Questions
|
| 33 |
+
|
| 34 |
+
```python
|
| 35 |
+
# Ask a simple factual question
|
| 36 |
+
answer = agent("What is the capital of France?")
|
| 37 |
+
print(f"Answer: {answer}")
|
| 38 |
+
|
| 39 |
+
# Ask a more complex question requiring reasoning
|
| 40 |
+
answer = agent("If a train travels at 120 km/h for 2.5 hours, how far does it travel?")
|
| 41 |
+
print(f"Answer: {answer}")
|
| 42 |
+
|
| 43 |
+
# Ask a question requiring web search
|
| 44 |
+
answer = agent("What were the key announcements at the most recent Apple WWDC?")
|
| 45 |
+
print(f"Answer: {answer}")
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
## Advanced Usage
|
| 49 |
+
|
| 50 |
+
### Using Memory Components
|
| 51 |
+
|
| 52 |
+
```python
|
| 53 |
+
# Get a snapshot of the agent's memory
|
| 54 |
+
memory_snapshot = agent.get_memory_snapshot()
|
| 55 |
+
print(f"Conversation history: {memory_snapshot['conversation']}")
|
| 56 |
+
print(f"Cached results: {memory_snapshot['cached_results']}")
|
| 57 |
+
|
| 58 |
+
# Clear the agent's memory
|
| 59 |
+
agent.clear_memory()
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
### Error Handling
|
| 63 |
+
|
| 64 |
+
```python
|
| 65 |
+
try:
|
| 66 |
+
answer = agent("What is the meaning of life?")
|
| 67 |
+
print(f"Answer: {answer}")
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"Error: {e}")
|
| 70 |
+
|
| 71 |
+
# You can also configure the agent to return error messages instead of raising exceptions
|
| 72 |
+
agent_with_error_messages = GAIAAgent({
|
| 73 |
+
"agent": {
|
| 74 |
+
"return_error_message": True
|
| 75 |
+
}
|
| 76 |
+
})
|
| 77 |
+
|
| 78 |
+
answer = agent_with_error_messages("What is the meaning of life?")
|
| 79 |
+
if answer.startswith("Error:"):
|
| 80 |
+
print(f"Agent encountered an error: {answer}")
|
| 81 |
+
else:
|
| 82 |
+
print(f"Answer: {answer}")
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
## Integration Examples
|
| 86 |
+
|
| 87 |
+
### Integration with Gradio
|
| 88 |
+
|
| 89 |
+
```python
|
| 90 |
+
import gradio as gr
|
| 91 |
+
from agent import GAIAAgent
|
| 92 |
+
|
| 93 |
+
# Initialize the agent
|
| 94 |
+
agent = GAIAAgent()
|
| 95 |
+
|
| 96 |
+
# Define the Gradio interface
|
| 97 |
+
def process_question(question):
|
| 98 |
+
try:
|
| 99 |
+
answer = agent(question)
|
| 100 |
+
return answer
|
| 101 |
+
except Exception as e:
|
| 102 |
+
return f"Error: {e}"
|
| 103 |
+
|
| 104 |
+
# Create the interface
|
| 105 |
+
demo = gr.Interface(
|
| 106 |
+
fn=process_question,
|
| 107 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter your question here..."),
|
| 108 |
+
outputs=gr.Textbox(label="Answer"),
|
| 109 |
+
title="GAIA Agent Demo",
|
| 110 |
+
description="Ask a question and get an answer from the GAIA agent."
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Launch the interface
|
| 114 |
+
demo.launch()
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
### Integration with FastAPI
|
| 118 |
+
|
| 119 |
+
```python
|
| 120 |
+
from fastapi import FastAPI, HTTPException
|
| 121 |
+
from pydantic import BaseModel
|
| 122 |
+
from agent import GAIAAgent
|
| 123 |
+
|
| 124 |
+
# Initialize the agent
|
| 125 |
+
agent = GAIAAgent()
|
| 126 |
+
|
| 127 |
+
# Create the FastAPI app
|
| 128 |
+
app = FastAPI(title="GAIA Agent API")
|
| 129 |
+
|
| 130 |
+
# Define the request model
|
| 131 |
+
class QuestionRequest(BaseModel):
|
| 132 |
+
question: str
|
| 133 |
+
|
| 134 |
+
# Define the response model
|
| 135 |
+
class AnswerResponse(BaseModel):
|
| 136 |
+
answer: str
|
| 137 |
+
processing_time: float
|
| 138 |
+
|
| 139 |
+
# Define the endpoint
|
| 140 |
+
@app.post("/ask", response_model=AnswerResponse)
|
| 141 |
+
async def ask_question(request: QuestionRequest):
|
| 142 |
+
try:
|
| 143 |
+
import time
|
| 144 |
+
start_time = time.time()
|
| 145 |
+
answer = agent(request.question)
|
| 146 |
+
processing_time = time.time() - start_time
|
| 147 |
+
return AnswerResponse(answer=answer, processing_time=processing_time)
|
| 148 |
+
except Exception as e:
|
| 149 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 150 |
+
|
| 151 |
+
# Run with: uvicorn api:app --reload
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
## Benchmark Testing
|
| 155 |
+
|
| 156 |
+
```python
|
| 157 |
+
from tests.benchmark import run_benchmark, SAMPLE_QUESTIONS
|
| 158 |
+
|
| 159 |
+
# Run the benchmark with default settings
|
| 160 |
+
result = run_benchmark(SAMPLE_QUESTIONS)
|
| 161 |
+
|
| 162 |
+
# Print the summary
|
| 163 |
+
result.print_summary()
|
| 164 |
+
|
| 165 |
+
# Save the results to a file
|
| 166 |
+
result.save_to_file("benchmark_results.json")
|
| 167 |
+
|
| 168 |
+
# Run with custom configuration
|
| 169 |
+
custom_config = {
|
| 170 |
+
"model": {
|
| 171 |
+
"reasoning_model": "gpt-4",
|
| 172 |
+
"temperature": 0.1
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
result = run_benchmark(SAMPLE_QUESTIONS, agent_config=custom_config)
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
## Command-Line Usage
|
| 179 |
+
|
| 180 |
+
You can also run the agent from the command line using the provided scripts:
|
| 181 |
+
|
| 182 |
+
```bash
|
| 183 |
+
# Run the Gradio interface
|
| 184 |
+
python app.py
|
| 185 |
+
|
| 186 |
+
# Run benchmark tests
|
| 187 |
+
python -m tests.benchmark --output benchmark_results.json
|
| 188 |
+
|
| 189 |
+
# Run benchmark tests with custom questions
|
| 190 |
+
python -m tests.benchmark --questions custom_questions.json --output benchmark_results.json
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
## Next Steps
|
| 194 |
+
|
| 195 |
+
For more detailed information on configuration options, see [Configuration Guide](configuration.md).
|
| 196 |
+
|
| 197 |
+
For deployment instructions, see [Deployment Guide](deployment.md).
|
docs/gaia_memory_integration.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA Memory Integration with Supabase
|
| 2 |
+
|
| 3 |
+
This document describes the integration of Supabase as a persistent memory store for the GAIA agent. The integration enables the agent to maintain conversation history, cache results, and store intermediate data across multiple sessions.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
The GAIA agent uses Supabase as a backend database to store various types of memory:
|
| 8 |
+
|
| 9 |
+
1. **Conversation Memory**: Stores the history of interactions between users and the agent
|
| 10 |
+
2. **Result Cache**: Caches tool results and answers to avoid redundant computations
|
| 11 |
+
3. **Working Memory**: Stores intermediate results during agent execution
|
| 12 |
+
|
| 13 |
+
This memory architecture allows the agent to:
|
| 14 |
+
- Maintain context across multiple turns in a conversation
|
| 15 |
+
- Remember previous interactions even after the agent is restarted
|
| 16 |
+
- Build upon previous knowledge in follow-up questions
|
| 17 |
+
- Optimize performance by caching expensive operations
|
| 18 |
+
|
| 19 |
+
## Architecture
|
| 20 |
+
|
| 21 |
+
The memory system consists of several components:
|
| 22 |
+
|
| 23 |
+
### SupabaseMemory
|
| 24 |
+
|
| 25 |
+
The core memory implementation that handles the connection to Supabase and provides basic CRUD operations:
|
| 26 |
+
|
| 27 |
+
- `store(key, value, metadata, ttl)`: Store a value in memory
|
| 28 |
+
- `retrieve(key, default)`: Retrieve a value from memory
|
| 29 |
+
- `delete(key)`: Delete a value from memory
|
| 30 |
+
- `clear()`: Clear all values from memory
|
| 31 |
+
- `list_keys(prefix)`: List all keys in memory
|
| 32 |
+
|
| 33 |
+
### ConversationMemory
|
| 34 |
+
|
| 35 |
+
A specialized memory interface for storing conversation history:
|
| 36 |
+
|
| 37 |
+
- `add_message(role, content, metadata)`: Add a message to the conversation history
|
| 38 |
+
- `get_messages(limit, before, after)`: Get messages from the conversation history
|
| 39 |
+
- `clear()`: Clear the conversation history
|
| 40 |
+
|
| 41 |
+
### ResultCache
|
| 42 |
+
|
| 43 |
+
A specialized memory interface for caching tool results and answers:
|
| 44 |
+
|
| 45 |
+
- `cache_result(tool_name, input_hash, result)`: Cache a tool result
|
| 46 |
+
- `get_result(tool_name, input_hash)`: Get a cached result
|
| 47 |
+
- `invalidate(key)`: Invalidate a cached result
|
| 48 |
+
- `clear()`: Clear all cached results
|
| 49 |
+
|
| 50 |
+
### WorkingMemory
|
| 51 |
+
|
| 52 |
+
A specialized memory interface for storing intermediate results during agent execution:
|
| 53 |
+
|
| 54 |
+
- `store_intermediate_result(key, value, metadata)`: Store an intermediate result
|
| 55 |
+
- `get_intermediate_result(key, default)`: Get an intermediate result
|
| 56 |
+
- `list_intermediate_results()`: List all intermediate results
|
| 57 |
+
- `clear()`: Clear all intermediate results
|
| 58 |
+
|
| 59 |
+
## Database Schema
|
| 60 |
+
|
| 61 |
+
The Supabase database uses the following tables:
|
| 62 |
+
|
| 63 |
+
### gaia_memory
|
| 64 |
+
|
| 65 |
+
The main memory table with the following columns:
|
| 66 |
+
|
| 67 |
+
- `id`: UUID primary key
|
| 68 |
+
- `key`: Text, unique key for the memory entry
|
| 69 |
+
- `value`: Text, JSON-serialized value
|
| 70 |
+
- `metadata`: JSONB, additional metadata
|
| 71 |
+
- `created_at`: Timestamp with timezone, creation time
|
| 72 |
+
- `expires_at`: Timestamp with timezone, expiration time (optional)
|
| 73 |
+
|
| 74 |
+
## Configuration
|
| 75 |
+
|
| 76 |
+
The memory system is configured through the `agent/config.py` file:
|
| 77 |
+
|
| 78 |
+
```python
|
| 79 |
+
# Memory Settings
|
| 80 |
+
MEMORY_ENABLED = True
|
| 81 |
+
MEMORY_TABLE_NAME = "gaia_memory"
|
| 82 |
+
MEMORY_TTL = 86400 # 24 hours in seconds
|
| 83 |
+
MEMORY_CACHE_SIZE = 100
|
| 84 |
+
MEMORY_SIMILARITY_THRESHOLD = 0.85
|
| 85 |
+
MEMORY_MAX_ENTRIES = 1000
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
## Usage
|
| 89 |
+
|
| 90 |
+
### Initializing the Agent with Memory
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
from agent.agent import GAIAAgent
|
| 94 |
+
|
| 95 |
+
# Create an agent with memory enabled
|
| 96 |
+
agent = GAIAAgent({
|
| 97 |
+
"memory": {
|
| 98 |
+
"enabled": True,
|
| 99 |
+
"table_name": "gaia_memory",
|
| 100 |
+
"conversation_id": "unique-conversation-id"
|
| 101 |
+
}
|
| 102 |
+
})
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
### Using Memory Across Sessions
|
| 106 |
+
|
| 107 |
+
The memory system allows the agent to maintain context across multiple sessions:
|
| 108 |
+
|
| 109 |
+
```python
|
| 110 |
+
# Session 1
|
| 111 |
+
agent1 = GAIAAgent({"memory": {"conversation_id": "conversation-123"}})
|
| 112 |
+
answer1 = agent1("What is the capital of France?")
|
| 113 |
+
|
| 114 |
+
# Session 2 (could be a different process or even a different day)
|
| 115 |
+
agent2 = GAIAAgent({"memory": {"conversation_id": "conversation-123"}})
|
| 116 |
+
answer2 = agent2("What is the population of that city?") # Agent remembers "that city" refers to Paris
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
## Testing
|
| 120 |
+
|
| 121 |
+
The integration can be tested using the `tests/test_gaia_with_memory.py` script:
|
| 122 |
+
|
| 123 |
+
```bash
|
| 124 |
+
# Test memory persistence
|
| 125 |
+
python tests/test_gaia_with_memory.py --test memory
|
| 126 |
+
|
| 127 |
+
# Test API integration with memory
|
| 128 |
+
python tests/test_gaia_with_memory.py --test api
|
| 129 |
+
|
| 130 |
+
# Run all tests
|
| 131 |
+
python tests/test_gaia_with_memory.py --test all
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
## Error Handling
|
| 135 |
+
|
| 136 |
+
The memory system is designed to be resilient to failures:
|
| 137 |
+
|
| 138 |
+
1. If Supabase is unavailable, the agent falls back to in-memory storage
|
| 139 |
+
2. If a memory entry expires, it is automatically removed from the system
|
| 140 |
+
3. If a memory operation fails, the error is logged and the agent continues operation
|
| 141 |
+
|
| 142 |
+
## Security Considerations
|
| 143 |
+
|
| 144 |
+
1. Supabase credentials are stored as environment variables
|
| 145 |
+
2. The memory system uses Supabase's built-in security features
|
| 146 |
+
3. Sensitive data should be encrypted before storage
|
| 147 |
+
4. Memory entries can have a time-to-live (TTL) to automatically expire
|
| 148 |
+
|
| 149 |
+
## Future Improvements
|
| 150 |
+
|
| 151 |
+
1. Implement vector embeddings for semantic search
|
| 152 |
+
2. Add memory compression to reduce storage requirements
|
| 153 |
+
3. Implement memory prioritization to focus on relevant information
|
| 154 |
+
4. Add support for multi-user memory isolation
|
| 155 |
+
5. Implement memory summarization for long conversations
|
docs/index.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAIA Agent Documentation
|
| 2 |
+
|
| 3 |
+
Welcome to the GAIA Agent documentation. This comprehensive guide provides detailed information about the GAIA agent, its components, configuration options, and usage examples.
|
| 4 |
+
|
| 5 |
+
## Table of Contents
|
| 6 |
+
|
| 7 |
+
### Getting Started
|
| 8 |
+
- [Project Overview](../README.md): Introduction to the GAIA agent project
|
| 9 |
+
- [Configuration Guide](configuration.md): Detailed information about configuration options
|
| 10 |
+
- [Deployment Guide](deployment.md): Instructions for deploying the agent in various environments
|
| 11 |
+
|
| 12 |
+
### Core Components
|
| 13 |
+
- [Agent Architecture](agent_architecture.md): Overview of the agent's architecture and components
|
| 14 |
+
- [Memory System](gaia_memory_integration.md): Information about the agent's memory system
|
| 15 |
+
- [Tool Integration](tool_integration.md): Guide to the agent's tool integration system
|
| 16 |
+
|
| 17 |
+
### API Integrations
|
| 18 |
+
- [OpenAI Integration](openai_integration_testing.md): Guide for testing OpenAI integration with newer models
|
| 19 |
+
- [LangChain OpenAI Integration](langchain_openai_integration.md): Guide for the langchain_openai package integration
|
| 20 |
+
- [Serper Integration](serper_integration.md): Guide for using the Serper API for Google search
|
| 21 |
+
- [DuckDuckGo Integration](duckduckgo_integration.md): Guide for using DuckDuckGo search
|
| 22 |
+
- [Multi-Search Integration](multi_search_integration.md): Guide for using multiple search providers
|
| 23 |
+
- [Perplexity Integration](perplexity_integration.md): Guide for using Perplexity AI
|
| 24 |
+
|
| 25 |
+
### Memory Integrations
|
| 26 |
+
- [Supabase Memory Integration](supabase_memory_integration.md): Guide for setting up and using Supabase memory
|
| 27 |
+
|
| 28 |
+
### Testing and Verification
|
| 29 |
+
- [Connection Verification](connection_verification.md): Guide for verifying connections to external services
|
| 30 |
+
- [All APIs Integration Testing](all_apis_integration_testing.md): Guide for testing all API integrations together
|
| 31 |
+
|
| 32 |
+
### Examples and Tutorials
|
| 33 |
+
- [Usage Examples](examples.md): Examples of how to use the GAIA agent in different scenarios
|
| 34 |
+
|
| 35 |
+
### Troubleshooting
|
| 36 |
+
- [Troubleshooting Guide](troubleshooting.md): Solutions for common issues and problems
|
| 37 |
+
|
| 38 |
+
## Quick Links
|
| 39 |
+
|
| 40 |
+
- [GitHub Repository](https://github.com/your-repo): Source code repository
|
| 41 |
+
- [Issue Tracker](https://github.com/your-repo/issues): Report issues and request features
|
| 42 |
+
- [Hugging Face Agents Course](https://huggingface.co/learn/agents): Learn more about the Hugging Face Agents Course
|
| 43 |
+
|
| 44 |
+
## Recent Updates
|
| 45 |
+
|
| 46 |
+
- **April 30, 2025**: Added troubleshooting guide and langchain_openai integration documentation
|
| 47 |
+
- **April 25, 2025**: Updated model configurations to use GPT-4o
|
| 48 |
+
- **April 20, 2025**: Added multi-search integration documentation
|
| 49 |
+
- **April 15, 2025**: Added Perplexity integration documentation
|
| 50 |
+
- **April 10, 2025**: Initial documentation release
|
| 51 |
+
|
| 52 |
+
## Contributing
|
| 53 |
+
|
| 54 |
+
If you'd like to contribute to the documentation, please follow these steps:
|
| 55 |
+
|
| 56 |
+
1. Fork the repository
|
| 57 |
+
2. Create a new branch for your changes
|
| 58 |
+
3. Make your changes
|
| 59 |
+
4. Submit a pull request
|
| 60 |
+
|
| 61 |
+
## License
|
| 62 |
+
|
| 63 |
+
This documentation is part of the Hugging Face Agents Course and follows its licensing terms.
|
docs/langchain_openai_integration.md
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LangChain OpenAI Integration Guide
|
| 2 |
+
|
| 3 |
+
This document provides detailed information about the integration between LangChain and OpenAI in the GAIA agent, focusing on the `langchain_openai` package.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
The GAIA agent uses the `langchain_openai` package to interact with OpenAI's language models. This package provides a clean interface for using OpenAI models within the LangChain framework, enabling features like:
|
| 8 |
+
|
| 9 |
+
- Chat completions with various OpenAI models
|
| 10 |
+
- Embeddings generation
|
| 11 |
+
- Function calling
|
| 12 |
+
- Streaming responses
|
| 13 |
+
- Vision capabilities
|
| 14 |
+
|
| 15 |
+
## Recent Changes
|
| 16 |
+
|
| 17 |
+
As of recent updates to the LangChain ecosystem, the OpenAI integration has been moved from the core `langchain` package to a separate `langchain_openai` package. This change was made to:
|
| 18 |
+
|
| 19 |
+
1. Modularize the LangChain ecosystem
|
| 20 |
+
2. Allow for more frequent updates to specific integrations
|
| 21 |
+
3. Reduce the size of the core package
|
| 22 |
+
4. Enable more flexible dependency management
|
| 23 |
+
|
| 24 |
+
## Installation
|
| 25 |
+
|
| 26 |
+
To use the `langchain_openai` package, you need to install it separately:
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
pip install langchain_openai
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
For the GAIA agent, this dependency is included in the `requirements.txt` file, so it should be installed automatically when you run:
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
pip install -r requirements.txt
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
If you encounter issues, try upgrading to the latest version:
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
pip install --upgrade langchain_openai
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
## Usage in GAIA Agent
|
| 45 |
+
|
| 46 |
+
The GAIA agent uses the `langchain_openai` package in several components:
|
| 47 |
+
|
| 48 |
+
### 1. Agent Graph (agent/graph.py)
|
| 49 |
+
|
| 50 |
+
```python
|
| 51 |
+
from langchain_openai import ChatOpenAI
|
| 52 |
+
|
| 53 |
+
# Initialize the model
|
| 54 |
+
model = ChatOpenAI(
|
| 55 |
+
model=get_model_config().get("reasoning_model", "gpt-4o"),
|
| 56 |
+
temperature=get_model_config().get("temperature", 0.1),
|
| 57 |
+
max_tokens=get_model_config().get("max_tokens", 4096)
|
| 58 |
+
)
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
### 2. Reasoning Tools (tools/reasoning_tools.py)
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
from langchain_openai import ChatOpenAI
|
| 65 |
+
|
| 66 |
+
# Initialize the model for reasoning
|
| 67 |
+
reasoning_model = ChatOpenAI(
|
| 68 |
+
model=get_model_config().get("reasoning_model", "gpt-4o"),
|
| 69 |
+
temperature=get_model_config().get("temperature", 0.1)
|
| 70 |
+
)
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
### 3. Multimodal Tools (tools/multimodal_tools.py)
|
| 74 |
+
|
| 75 |
+
```python
|
| 76 |
+
from langchain_openai import ChatOpenAI
|
| 77 |
+
|
| 78 |
+
# Initialize the model for vision tasks
|
| 79 |
+
vision_model = ChatOpenAI(
|
| 80 |
+
model=get_model_config().get("vision_model", "gpt-4o"),
|
| 81 |
+
temperature=get_model_config().get("temperature", 0.1)
|
| 82 |
+
)
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
## Common Issues and Solutions
|
| 86 |
+
|
| 87 |
+
### 1. Import Errors
|
| 88 |
+
|
| 89 |
+
If you encounter import errors like:
|
| 90 |
+
|
| 91 |
+
```
|
| 92 |
+
ImportError: No module named 'langchain_openai'
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
or
|
| 96 |
+
|
| 97 |
+
```
|
| 98 |
+
ImportError: cannot import name 'ChatOpenAI' from 'langchain_openai'
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
**Solutions:**
|
| 102 |
+
|
| 103 |
+
1. Ensure the package is installed:
|
| 104 |
+
```bash
|
| 105 |
+
pip install langchain_openai
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
2. Check for conflicts with older versions:
|
| 109 |
+
```bash
|
| 110 |
+
pip uninstall langchain-openai # Note the hyphen
|
| 111 |
+
pip install langchain_openai # Note the underscore
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
3. Update your import statements:
|
| 115 |
+
```python
|
| 116 |
+
# Old import (no longer works)
|
| 117 |
+
# from langchain.chat_models import ChatOpenAI
|
| 118 |
+
|
| 119 |
+
# New import (correct)
|
| 120 |
+
from langchain_openai import ChatOpenAI
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
### 2. Version Compatibility
|
| 124 |
+
|
| 125 |
+
If you encounter compatibility issues between `langchain`, `langchain_openai`, and other LangChain packages:
|
| 126 |
+
|
| 127 |
+
**Solution:**
|
| 128 |
+
```bash
|
| 129 |
+
pip install --upgrade langchain langchain_openai langgraph
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
This ensures all LangChain-related packages are updated to compatible versions.
|
| 133 |
+
|
| 134 |
+
### 3. API Key Issues
|
| 135 |
+
|
| 136 |
+
If you encounter authentication errors:
|
| 137 |
+
|
| 138 |
+
**Solution:**
|
| 139 |
+
Ensure your OpenAI API key is correctly set:
|
| 140 |
+
```python
|
| 141 |
+
import os
|
| 142 |
+
from dotenv import load_dotenv
|
| 143 |
+
|
| 144 |
+
load_dotenv()
|
| 145 |
+
|
| 146 |
+
# Check if the API key is set
|
| 147 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 148 |
+
if not api_key:
|
| 149 |
+
raise ValueError("OPENAI_API_KEY environment variable is not set")
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
## Model Configuration
|
| 153 |
+
|
| 154 |
+
The GAIA agent uses the following OpenAI models by default:
|
| 155 |
+
|
| 156 |
+
| Purpose | Model | Environment Variable |
|
| 157 |
+
|---------|-------|----------------------|
|
| 158 |
+
| Reasoning | gpt-4o | REASONING_MODEL |
|
| 159 |
+
| Tool Execution | gpt-3.5-turbo | TOOL_MODEL |
|
| 160 |
+
| Vision | gpt-4o | VISION_MODEL |
|
| 161 |
+
| Embeddings | text-embedding-3-large | EMBEDDING_MODEL |
|
| 162 |
+
|
| 163 |
+
You can customize these models by setting the appropriate environment variables or by passing a configuration dictionary when initializing the agent.
|
| 164 |
+
|
| 165 |
+
## Best Practices
|
| 166 |
+
|
| 167 |
+
1. **Always specify the model version**: This ensures consistent behavior even when OpenAI releases new model versions.
|
| 168 |
+
```python
|
| 169 |
+
ChatOpenAI(model="gpt-4o") # Specific model version
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
2. **Set appropriate temperature**: Lower values (0.0-0.3) for factual tasks, higher values (0.5-0.8) for creative tasks.
|
| 173 |
+
```python
|
| 174 |
+
ChatOpenAI(model="gpt-4o", temperature=0.1) # Low temperature for factual responses
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
3. **Handle rate limits gracefully**: Implement exponential backoff and retry logic.
|
| 178 |
+
```python
|
| 179 |
+
from tenacity import retry, stop_after_attempt, wait_exponential
|
| 180 |
+
|
| 181 |
+
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
|
| 182 |
+
def query_model(prompt):
|
| 183 |
+
model = ChatOpenAI(model="gpt-4o")
|
| 184 |
+
return model.invoke(prompt)
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
4. **Use streaming for long responses**: This provides a better user experience for long-running queries.
|
| 188 |
+
```python
|
| 189 |
+
model = ChatOpenAI(model="gpt-4o", streaming=True)
|
| 190 |
+
for chunk in model.stream("Tell me about AI"):
|
| 191 |
+
print(chunk.content, end="", flush=True)
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
5. **Set max_tokens appropriately**: This prevents unnecessarily long responses and reduces token usage.
|
| 195 |
+
```python
|
| 196 |
+
ChatOpenAI(model="gpt-4o", max_tokens=1000)
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+
## Testing
|
| 200 |
+
|
| 201 |
+
The GAIA agent includes tests for OpenAI integration in `tests/test_openai_integration.py`. These tests verify:
|
| 202 |
+
|
| 203 |
+
1. Connection to the OpenAI API
|
| 204 |
+
2. Compatibility with newer models like GPT-4o
|
| 205 |
+
3. Integration with the GAIA agent
|
| 206 |
+
|
| 207 |
+
To run these tests:
|
| 208 |
+
|
| 209 |
+
```bash
|
| 210 |
+
python tests/test_openai_integration.py
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
For more comprehensive testing:
|
| 214 |
+
|
| 215 |
+
```bash
|
| 216 |
+
python tests/run_openai_tests.py
|
| 217 |
+
```
|
| 218 |
+
|
| 219 |
+
## Troubleshooting
|
| 220 |
+
|
| 221 |
+
If you encounter issues with the `langchain_openai` integration, check the [Troubleshooting Guide](troubleshooting.md) for common problems and solutions.
|
| 222 |
+
|
| 223 |
+
## Related Documentation
|
| 224 |
+
|
| 225 |
+
- [OpenAI API Documentation](https://platform.openai.com/docs/api-reference)
|
| 226 |
+
- [LangChain Documentation](https://python.langchain.com/docs/get_started/introduction)
|
| 227 |
+
- [LangChain OpenAI Integration Documentation](https://python.langchain.com/docs/integrations/llms/openai)
|
docs/multi_search_integration.md
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Multi-Search Provider Integration for GAIA Agent
|
| 2 |
+
|
| 3 |
+
This document explains how to integrate and use multiple search providers with the GAIA agent, including:
|
| 4 |
+
|
| 5 |
+
1. DuckDuckGo
|
| 6 |
+
2. Serper (Google Search API)
|
| 7 |
+
3. Perplexity
|
| 8 |
+
4. arXiv
|
| 9 |
+
|
| 10 |
+
## Overview
|
| 11 |
+
|
| 12 |
+
The GAIA agent can leverage multiple search providers to get comprehensive and diverse search results. Each provider has its strengths:
|
| 13 |
+
|
| 14 |
+
- **DuckDuckGo**: Privacy-focused search with no API key required
|
| 15 |
+
- **Serper**: Google search results with structured data
|
| 16 |
+
- **Perplexity**: AI-powered search with reasoning capabilities
|
| 17 |
+
- **arXiv**: Academic paper search for scientific research
|
| 18 |
+
|
| 19 |
+
## Configuration
|
| 20 |
+
|
| 21 |
+
### Environment Variables
|
| 22 |
+
|
| 23 |
+
Set up the necessary API keys in your environment:
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
# Required for Serper
|
| 27 |
+
export SERPER_API_KEY="your_serper_api_key"
|
| 28 |
+
|
| 29 |
+
# Required for Perplexity
|
| 30 |
+
export PERPLEXITY_API_KEY="your_perplexity_api_key"
|
| 31 |
+
|
| 32 |
+
# DuckDuckGo and arXiv don't require API keys
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
### Tool Configuration
|
| 36 |
+
|
| 37 |
+
The search providers are configured in `agent/config.py`:
|
| 38 |
+
|
| 39 |
+
```python
|
| 40 |
+
# Tool Parameters (hardcoded)
|
| 41 |
+
WEB_SEARCH_RESULT_COUNT = 5
|
| 42 |
+
WEB_SEARCH_TIMEOUT = 10
|
| 43 |
+
DUCKDUCKGO_TIMEOUT = 10
|
| 44 |
+
DUCKDUCKGO_MAX_RESULTS = 5
|
| 45 |
+
PERPLEXITY_TIMEOUT = 30
|
| 46 |
+
PERPLEXITY_MODEL = "sonar-reasoning"
|
| 47 |
+
ARXIV_MAX_RESULTS = 3
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## Using Search Providers
|
| 51 |
+
|
| 52 |
+
### Creating Search Tool Instances
|
| 53 |
+
|
| 54 |
+
```python
|
| 55 |
+
# Import the necessary tools
|
| 56 |
+
from tools.web_tools import create_duckduckgo_search, create_serper_search
|
| 57 |
+
from tools.perplexity_tool import PerplexityTool
|
| 58 |
+
from tools.arxiv_tool import create_arxiv_search
|
| 59 |
+
|
| 60 |
+
# Create DuckDuckGo search tool (no API key required)
|
| 61 |
+
duckduckgo_tool = create_duckduckgo_search()
|
| 62 |
+
|
| 63 |
+
# Create Serper search tool (requires API key in environment)
|
| 64 |
+
serper_tool = create_serper_search()
|
| 65 |
+
|
| 66 |
+
# Create Perplexity tool (requires API key in environment)
|
| 67 |
+
perplexity_tool = PerplexityTool()
|
| 68 |
+
|
| 69 |
+
# Create arXiv search tool (no API key required)
|
| 70 |
+
arxiv_tool = create_arxiv_search()
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
### Performing Searches
|
| 74 |
+
|
| 75 |
+
Each search provider has a similar interface:
|
| 76 |
+
|
| 77 |
+
```python
|
| 78 |
+
# DuckDuckGo search
|
| 79 |
+
duckduckgo_results = duckduckgo_tool.search("your search query")
|
| 80 |
+
# Returns a list of dictionaries with 'title', 'link', and 'snippet' keys
|
| 81 |
+
|
| 82 |
+
# Serper search
|
| 83 |
+
serper_results = serper_tool.search("your search query")
|
| 84 |
+
# Returns a list of dictionaries with 'title', 'link', and 'snippet' keys
|
| 85 |
+
|
| 86 |
+
# Perplexity search
|
| 87 |
+
perplexity_results = perplexity_tool.search("your search query")
|
| 88 |
+
# Returns a dictionary with 'content', 'citations', and other metadata
|
| 89 |
+
|
| 90 |
+
# arXiv search
|
| 91 |
+
arxiv_results = arxiv_tool.search("your search query")
|
| 92 |
+
# Returns a list of dictionaries with paper information
|
| 93 |
+
|
| 94 |
+
# arXiv get paper by ID
|
| 95 |
+
paper = arxiv_tool.get_paper_by_id("2303.08774")
|
| 96 |
+
# Returns a dictionary with detailed paper information
|
| 97 |
+
|
| 98 |
+
# arXiv search by category
|
| 99 |
+
category_results = arxiv_tool.search_by_category("cs.AI")
|
| 100 |
+
# Returns a list of dictionaries with papers in the specified category
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
## Integrating with LangGraph
|
| 104 |
+
|
| 105 |
+
To integrate these search providers with the LangGraph-based GAIA agent, you need to modify the `execute_tool` function in `agent/graph.py`:
|
| 106 |
+
|
| 107 |
+
```python
|
| 108 |
+
# Create a tool registry
|
| 109 |
+
tool_registry = {
|
| 110 |
+
"duckduckgo_search": create_duckduckgo_search(),
|
| 111 |
+
"serper_search": create_serper_search(),
|
| 112 |
+
"perplexity_search": PerplexityTool(),
|
| 113 |
+
"arxiv_search": create_arxiv_search(),
|
| 114 |
+
"arxiv_get_paper": create_arxiv_search(),
|
| 115 |
+
"arxiv_search_category": create_arxiv_search()
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
def execute_tool(state: AgentState) -> AgentState:
|
| 119 |
+
# Get the current step from the plan
|
| 120 |
+
current_step = state["plan"][state["current_step"]]
|
| 121 |
+
tool_name = current_step.get("tool")
|
| 122 |
+
tool_input = current_step.get("tool_input", {})
|
| 123 |
+
|
| 124 |
+
logger.debug(f"Executing tool {tool_name} for step {current_step['step_number']}")
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
# Get the tool from the registry
|
| 128 |
+
tool = tool_registry.get(tool_name)
|
| 129 |
+
if not tool:
|
| 130 |
+
raise Exception(f"Tool {tool_name} not found in registry")
|
| 131 |
+
|
| 132 |
+
# Execute the tool based on its type
|
| 133 |
+
if tool_name in ["duckduckgo_search", "serper_search"]:
|
| 134 |
+
result = tool.search(tool_input.get("query", ""))
|
| 135 |
+
elif tool_name == "perplexity_search":
|
| 136 |
+
result = tool.search(tool_input.get("query", ""))
|
| 137 |
+
elif tool_name == "arxiv_search":
|
| 138 |
+
result = tool.search(tool_input.get("query", ""), tool_input.get("max_results"))
|
| 139 |
+
elif tool_name == "arxiv_get_paper":
|
| 140 |
+
result = tool.get_paper_by_id(tool_input.get("paper_id", ""))
|
| 141 |
+
elif tool_name == "arxiv_search_category":
|
| 142 |
+
result = tool.search_by_category(tool_input.get("category", ""), tool_input.get("max_results"))
|
| 143 |
+
else:
|
| 144 |
+
# Generic tool execution
|
| 145 |
+
result = tool.run(tool_input)
|
| 146 |
+
|
| 147 |
+
# Create a tool result
|
| 148 |
+
tool_result = {
|
| 149 |
+
"tool_name": tool_name,
|
| 150 |
+
"success": True,
|
| 151 |
+
"result": result,
|
| 152 |
+
"error": None
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
# Update the state
|
| 156 |
+
new_state = state.copy()
|
| 157 |
+
new_state["tool_results"] = state.get("tool_results", []) + [tool_result]
|
| 158 |
+
new_state["current_step"] += 1
|
| 159 |
+
|
| 160 |
+
return new_state
|
| 161 |
+
except Exception as e:
|
| 162 |
+
# Handle error...
|
| 163 |
+
# (rest of the function remains the same)
|
| 164 |
+
}
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
## Comparison of Search Providers
|
| 168 |
+
|
| 169 |
+
| Provider | API Key Required | Result Format | Strengths | Limitations |
|
| 170 |
+
|-------------|------------------|------------------------------|--------------------------------------------|--------------------------------------------|
|
| 171 |
+
| DuckDuckGo | No | List of result dictionaries | Privacy-focused, No API key | Sometimes less comprehensive |
|
| 172 |
+
| Serper | Yes | List of result dictionaries | Google results, Structured data | Requires API key, Usage limits |
|
| 173 |
+
| Perplexity | Yes | Content with citations | AI-powered, Reasoning capabilities | Requires API key, Slower response time |
|
| 174 |
+
| arXiv | No | List of paper dictionaries | Academic papers, Scientific research | Limited to academic content |
|
| 175 |
+
|
| 176 |
+
## Best Practices
|
| 177 |
+
|
| 178 |
+
1. **Fallback Mechanism**: Implement a fallback mechanism to try alternative search providers if one fails.
|
| 179 |
+
|
| 180 |
+
```python
|
| 181 |
+
def robust_search(query):
|
| 182 |
+
# Try DuckDuckGo first (no API key required)
|
| 183 |
+
try:
|
| 184 |
+
results = duckduckgo_tool.search(query)
|
| 185 |
+
if results:
|
| 186 |
+
return {"provider": "duckduckgo", "results": results}
|
| 187 |
+
except Exception as e:
|
| 188 |
+
logger.warning(f"DuckDuckGo search failed: {str(e)}")
|
| 189 |
+
|
| 190 |
+
# Try Serper as fallback
|
| 191 |
+
try:
|
| 192 |
+
results = serper_tool.search(query)
|
| 193 |
+
if results:
|
| 194 |
+
return {"provider": "serper", "results": results}
|
| 195 |
+
except Exception as e:
|
| 196 |
+
logger.warning(f"Serper search failed: {str(e)}")
|
| 197 |
+
|
| 198 |
+
# Try Perplexity as third option
|
| 199 |
+
try:
|
| 200 |
+
results = perplexity_tool.search(query)
|
| 201 |
+
if results:
|
| 202 |
+
return {"provider": "perplexity", "results": results}
|
| 203 |
+
except Exception as e:
|
| 204 |
+
logger.warning(f"Perplexity search failed: {str(e)}")
|
| 205 |
+
|
| 206 |
+
# Try arXiv as last resort
|
| 207 |
+
try:
|
| 208 |
+
results = arxiv_tool.search(query)
|
| 209 |
+
if results:
|
| 210 |
+
return {"provider": "arxiv", "results": results}
|
| 211 |
+
except Exception as e:
|
| 212 |
+
logger.warning(f"arXiv search failed: {str(e)}")
|
| 213 |
+
|
| 214 |
+
# All providers failed
|
| 215 |
+
raise Exception("All search providers failed")
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
2. **Query Optimization**: Different search providers may respond better to different query formats.
|
| 219 |
+
|
| 220 |
+
3. **Result Merging**: For comprehensive results, consider merging results from multiple providers.
|
| 221 |
+
|
| 222 |
+
```python
|
| 223 |
+
def merged_search(query):
|
| 224 |
+
results = {
|
| 225 |
+
"duckduckgo": [],
|
| 226 |
+
"serper": [],
|
| 227 |
+
"perplexity": None,
|
| 228 |
+
"arxiv": []
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
# Collect results from all providers
|
| 232 |
+
try:
|
| 233 |
+
results["duckduckgo"] = duckduckgo_tool.search(query)
|
| 234 |
+
except Exception:
|
| 235 |
+
pass
|
| 236 |
+
|
| 237 |
+
try:
|
| 238 |
+
results["serper"] = serper_tool.search(query)
|
| 239 |
+
except Exception:
|
| 240 |
+
pass
|
| 241 |
+
|
| 242 |
+
try:
|
| 243 |
+
results["perplexity"] = perplexity_tool.search(query)
|
| 244 |
+
except Exception:
|
| 245 |
+
pass
|
| 246 |
+
|
| 247 |
+
# Try arXiv
|
| 248 |
+
try:
|
| 249 |
+
results["arxiv"] = arxiv_tool.search(query)
|
| 250 |
+
except Exception:
|
| 251 |
+
pass
|
| 252 |
+
|
| 253 |
+
# Merge and deduplicate results
|
| 254 |
+
merged = []
|
| 255 |
+
seen_urls = set()
|
| 256 |
+
|
| 257 |
+
# Add DuckDuckGo results
|
| 258 |
+
for result in results["duckduckgo"]:
|
| 259 |
+
if result["link"] not in seen_urls:
|
| 260 |
+
merged.append(result)
|
| 261 |
+
seen_urls.add(result["link"])
|
| 262 |
+
|
| 263 |
+
# Add Serper results
|
| 264 |
+
for result in results["serper"]:
|
| 265 |
+
if result["link"] not in seen_urls:
|
| 266 |
+
merged.append(result)
|
| 267 |
+
seen_urls.add(result["link"])
|
| 268 |
+
|
| 269 |
+
# Add arXiv results
|
| 270 |
+
arxiv_results = []
|
| 271 |
+
for result in results["arxiv"]:
|
| 272 |
+
if "url" in result and result["url"] not in seen_urls:
|
| 273 |
+
# Convert arXiv result to standard format
|
| 274 |
+
formatted_result = {
|
| 275 |
+
"title": result.get("title", ""),
|
| 276 |
+
"link": result.get("url", ""),
|
| 277 |
+
"snippet": result.get("summary", "")[:200] + "..." if result.get("summary") else ""
|
| 278 |
+
}
|
| 279 |
+
merged.append(formatted_result)
|
| 280 |
+
seen_urls.add(result["url"])
|
| 281 |
+
arxiv_results.append(result) # Keep original format for context
|
| 282 |
+
|
| 283 |
+
# Add Perplexity content as context
|
| 284 |
+
perplexity_content = results["perplexity"].get("content") if results["perplexity"] else None
|
| 285 |
+
|
| 286 |
+
return {
|
| 287 |
+
"merged_results": merged,
|
| 288 |
+
"perplexity_context": perplexity_content,
|
| 289 |
+
"arxiv_context": arxiv_results
|
| 290 |
+
}
|
| 291 |
+
```
|
| 292 |
+
|
| 293 |
+
## Testing
|
| 294 |
+
|
| 295 |
+
To test the integration of all search providers, run:
|
| 296 |
+
|
| 297 |
+
```bash
|
| 298 |
+
python tests/test_duckduckgo_integration.py
|
| 299 |
+
python tests/test_arxiv_integration.py
|
| 300 |
+
```
|
| 301 |
+
|
| 302 |
+
These tests verify:
|
| 303 |
+
1. Direct connection to each search provider
|
| 304 |
+
2. Proper functioning of each search tool
|
| 305 |
+
3. Error handling
|
| 306 |
+
4. Using multiple search providers together
|
| 307 |
+
5. Integration with the GAIA agent
|
| 308 |
+
|
| 309 |
+
## Conclusion
|
| 310 |
+
|
| 311 |
+
By integrating multiple search providers, the GAIA agent can provide more robust and comprehensive search capabilities. The agent can fall back to alternative providers if one fails, and can leverage the strengths of each provider for different types of queries:
|
| 312 |
+
|
| 313 |
+
- Use DuckDuckGo for general web searches without API key requirements
|
| 314 |
+
- Use Serper for more comprehensive Google search results
|
| 315 |
+
- Use Perplexity for AI-powered reasoning and analysis
|
| 316 |
+
- Use arXiv for academic and scientific research papers
|
| 317 |
+
|
| 318 |
+
This multi-provider approach ensures the GAIA agent can handle a wide range of search queries and provide the most relevant information to users.
|
docs/openai_integration_testing.md
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Testing OpenAI Integration with Newer Models
|
| 2 |
+
|
| 3 |
+
This document provides instructions for testing the OpenAI integration with newer models like GPT-4o in the GAIA agent.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
The GAIA agent has been updated to support newer OpenAI models, including:
|
| 8 |
+
|
| 9 |
+
- **GPT-4o**: The latest multimodal model that replaces both GPT-4-turbo and GPT-4-vision-preview
|
| 10 |
+
- **text-embedding-3-large**: The latest embedding model that replaces text-embedding-ada-002
|
| 11 |
+
|
| 12 |
+
These test scripts verify that the configuration changes are working properly and that the GAIA agent can use these newer models effectively.
|
| 13 |
+
|
| 14 |
+
## Prerequisites
|
| 15 |
+
|
| 16 |
+
Before running the tests, make sure you have:
|
| 17 |
+
|
| 18 |
+
1. Set up your environment variables with the necessary API keys:
|
| 19 |
+
- `OPENAI_API_KEY`: Your OpenAI API key
|
| 20 |
+
- `PERPLEXITY_API_KEY`: Your Perplexity API key (for multi-provider tests)
|
| 21 |
+
|
| 22 |
+
2. Installed all required dependencies:
|
| 23 |
+
```bash
|
| 24 |
+
pip install -r requirements.txt
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
## Test Scripts
|
| 28 |
+
|
| 29 |
+
### 1. OpenAI Integration Test
|
| 30 |
+
|
| 31 |
+
This script tests the OpenAI integration with newer models.
|
| 32 |
+
|
| 33 |
+
**File**: `tests/test_openai_integration.py`
|
| 34 |
+
|
| 35 |
+
**Features**:
|
| 36 |
+
- Verifies connection to the OpenAI API
|
| 37 |
+
- Tests sending requests to newer models (GPT-4o, etc.)
|
| 38 |
+
- Tests vision capabilities with GPT-4o
|
| 39 |
+
- Optionally tests the GAIA agent with OpenAI models
|
| 40 |
+
|
| 41 |
+
**Usage**:
|
| 42 |
+
```bash
|
| 43 |
+
python tests/test_openai_integration.py [--verbose] [--output FILENAME] [--test-agent]
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
**Options**:
|
| 47 |
+
- `--verbose`, `-v`: Enable verbose logging
|
| 48 |
+
- `--output`, `-o`: Specify output file for test results (default: openai_test_results.json)
|
| 49 |
+
- `--test-agent`, `-a`: Test the GAIA agent with OpenAI models
|
| 50 |
+
|
| 51 |
+
### 2. GAIA Multi-Provider Test
|
| 52 |
+
|
| 53 |
+
This script tests the GAIA agent's ability to use both OpenAI and Perplexity tools together.
|
| 54 |
+
|
| 55 |
+
**File**: `tests/test_gaia_multi_provider.py`
|
| 56 |
+
|
| 57 |
+
**Features**:
|
| 58 |
+
- Tests OpenAI-only questions
|
| 59 |
+
- Tests Perplexity-only questions
|
| 60 |
+
- Tests questions that require both providers
|
| 61 |
+
- Tests memory components with multi-provider data
|
| 62 |
+
|
| 63 |
+
**Usage**:
|
| 64 |
+
```bash
|
| 65 |
+
python tests/test_gaia_multi_provider.py [--verbose] [--output FILENAME]
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
**Options**:
|
| 69 |
+
- `--verbose`, `-v`: Enable verbose logging
|
| 70 |
+
- `--output`, `-o`: Specify output file for test results (default: gaia_multi_provider_test_report.json)
|
| 71 |
+
|
| 72 |
+
## Test Results
|
| 73 |
+
|
| 74 |
+
Both test scripts generate detailed reports in JSON format, which include:
|
| 75 |
+
|
| 76 |
+
- Connection status
|
| 77 |
+
- Model test results
|
| 78 |
+
- Vision test results (for OpenAI)
|
| 79 |
+
- Agent test results
|
| 80 |
+
- Memory component test results
|
| 81 |
+
- Summary statistics
|
| 82 |
+
|
| 83 |
+
The reports are saved to the specified output file and also printed to the console.
|
| 84 |
+
|
| 85 |
+
## Interpreting Results
|
| 86 |
+
|
| 87 |
+
### OpenAI Integration Test
|
| 88 |
+
|
| 89 |
+
A successful test should show:
|
| 90 |
+
- ✅ Connection to OpenAI API established
|
| 91 |
+
- ✅ All model tests passed
|
| 92 |
+
- ✅ Vision test passed (if applicable)
|
| 93 |
+
- ✅ Agent test passed (if enabled)
|
| 94 |
+
|
| 95 |
+
### GAIA Multi-Provider Test
|
| 96 |
+
|
| 97 |
+
A successful test should show:
|
| 98 |
+
- ✅ Both API keys available
|
| 99 |
+
- ✅ OpenAI-only questions answered correctly
|
| 100 |
+
- ✅ Perplexity-only questions answered correctly
|
| 101 |
+
- ✅ Combined questions answered correctly
|
| 102 |
+
- ✅ All memory components working
|
| 103 |
+
|
| 104 |
+
## Troubleshooting
|
| 105 |
+
|
| 106 |
+
### Common Issues
|
| 107 |
+
|
| 108 |
+
1. **API Key Issues**:
|
| 109 |
+
- Make sure your API keys are set correctly in your environment variables
|
| 110 |
+
- Check that your API keys have not expired
|
| 111 |
+
- Verify that your API keys have access to the models being tested
|
| 112 |
+
|
| 113 |
+
2. **Model Availability**:
|
| 114 |
+
- Some newer models may not be available to all accounts
|
| 115 |
+
- Check the OpenAI dashboard to see which models you have access to
|
| 116 |
+
|
| 117 |
+
3. **Rate Limiting**:
|
| 118 |
+
- If you encounter rate limiting errors, try running the tests with fewer questions
|
| 119 |
+
- Add delays between requests by modifying the test scripts
|
| 120 |
+
|
| 121 |
+
4. **Memory Issues**:
|
| 122 |
+
- If memory tests fail, check your Supabase configuration
|
| 123 |
+
- Verify that the memory tables exist and have the correct schema
|
| 124 |
+
|
| 125 |
+
## Next Steps
|
| 126 |
+
|
| 127 |
+
After verifying that the OpenAI integration works with newer models, you can:
|
| 128 |
+
|
| 129 |
+
1. Update your application to use the newer models
|
| 130 |
+
2. Optimize your prompts for the newer models
|
| 131 |
+
3. Implement additional features that leverage the capabilities of the newer models
|
| 132 |
+
4. Monitor performance and costs to ensure efficient usage
|
| 133 |
+
|
| 134 |
+
## Additional Resources
|
| 135 |
+
|
| 136 |
+
- [OpenAI API Documentation](https://platform.openai.com/docs/api-reference)
|
| 137 |
+
- [GPT-4o Documentation](https://platform.openai.com/docs/models/gpt-4o)
|
| 138 |
+
- [Perplexity API Documentation](https://docs.perplexity.ai/)
|
docs/serper_integration.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Serper API Integration
|
| 2 |
+
|
| 3 |
+
This document provides information about the Serper API integration in the GAIA agent, including configuration, usage, and testing procedures.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
Serper is a Google Search API that our GAIA agent uses for web searches. It provides a reliable way to access Google search results programmatically, which enhances the agent's ability to retrieve up-to-date information from the web.
|
| 8 |
+
|
| 9 |
+
## Configuration
|
| 10 |
+
|
| 11 |
+
The Serper API integration requires the following configuration:
|
| 12 |
+
|
| 13 |
+
1. **API Key**: Set the `SERPER_API_KEY` environment variable with your Serper API key.
|
| 14 |
+
2. **API URL**: The API endpoint is configured in `agent/config.py` as `SERPER_API_URL`.
|
| 15 |
+
|
| 16 |
+
Example configuration in `.env` file:
|
| 17 |
+
|
| 18 |
+
```
|
| 19 |
+
SERPER_API_KEY=your_serper_api_key_here
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
## Testing Results
|
| 23 |
+
|
| 24 |
+
We have successfully tested the Serper API integration and confirmed that it works correctly. The key findings from our testing are:
|
| 25 |
+
|
| 26 |
+
1. **API Connection**: The Serper API connection is working correctly. We can successfully connect to the API and receive a 200 status code.
|
| 27 |
+
2. **Search Functionality**: The search functionality works as expected. We can send search queries and receive relevant results.
|
| 28 |
+
3. **Response Format**: The API returns results in the expected format, with organic search results containing title, link, and snippet information.
|
| 29 |
+
|
| 30 |
+
### Sample Response
|
| 31 |
+
|
| 32 |
+
Here's an example of the response format from the Serper API:
|
| 33 |
+
|
| 34 |
+
```json
|
| 35 |
+
{
|
| 36 |
+
"organic": [
|
| 37 |
+
{
|
| 38 |
+
"title": "Artificial Intelligence News - ScienceDaily",
|
| 39 |
+
"link": "https://www.sciencedaily.com/news/computers_math/artificial_intelligence/",
|
| 40 |
+
"snippet": "Latest Headlines • AI Tool Outperforms Most Doctors On Exams • Brain-Inspired AI Breakthrough • Robot See, Robot Do • Explainable AI for Ship Navigation Raises ..."
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"title": "...",
|
| 44 |
+
"link": "...",
|
| 45 |
+
"snippet": "..."
|
| 46 |
+
}
|
| 47 |
+
]
|
| 48 |
+
}
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
### Environment Configuration
|
| 52 |
+
|
| 53 |
+
The Serper API key must be properly configured in the `.env` file. Our testing confirmed that the key is correctly loaded from the `.env` file and used in API requests.
|
| 54 |
+
|
| 55 |
+
### Integration with GAIA Agent
|
| 56 |
+
|
| 57 |
+
The Serper API is integrated with the GAIA agent through the `SerperSearchTool` class in `tools/web_tools.py`. This integration allows the agent to use the Serper API for web searches as part of its capabilities.
|
| 58 |
+
|
| 59 |
+
## Implementation
|
| 60 |
+
|
| 61 |
+
The Serper API is integrated through the `SerperSearchTool` class in `tools/web_tools.py`. This class:
|
| 62 |
+
|
| 63 |
+
1. Initializes with the Serper API key and URL
|
| 64 |
+
2. Provides a `search` method that accepts a query string
|
| 65 |
+
3. Formats the request with appropriate headers and payload
|
| 66 |
+
4. Processes the response to extract relevant search results
|
| 67 |
+
5. Returns the results in a standardized format
|
| 68 |
+
|
| 69 |
+
## Usage
|
| 70 |
+
|
| 71 |
+
### Basic Usage
|
| 72 |
+
|
| 73 |
+
```python
|
| 74 |
+
from tools.web_tools import create_serper_search
|
| 75 |
+
|
| 76 |
+
# Create a Serper search tool instance
|
| 77 |
+
serper_tool = create_serper_search()
|
| 78 |
+
|
| 79 |
+
# Perform a search
|
| 80 |
+
results = serper_tool.search("artificial intelligence latest developments")
|
| 81 |
+
|
| 82 |
+
# Process the results
|
| 83 |
+
for result in results:
|
| 84 |
+
print(f"Title: {result['title']}")
|
| 85 |
+
print(f"Link: {result['link']}")
|
| 86 |
+
print(f"Snippet: {result['snippet']}")
|
| 87 |
+
print()
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
### Integration with GAIA Agent
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
from agent.agent import GaiaAgent
|
| 94 |
+
from tools.web_tools import create_serper_search
|
| 95 |
+
|
| 96 |
+
# Create a GAIA agent instance
|
| 97 |
+
agent = GaiaAgent()
|
| 98 |
+
|
| 99 |
+
# Create and register the Serper search tool
|
| 100 |
+
serper_tool = create_serper_search()
|
| 101 |
+
agent.register_tool("serper_search", serper_tool.search)
|
| 102 |
+
|
| 103 |
+
# Run the agent with a query that would use the Serper tool
|
| 104 |
+
response = agent.run(
|
| 105 |
+
"What are the latest developments in artificial intelligence?",
|
| 106 |
+
tools=["serper_search"]
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
print(response)
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
## Testing
|
| 113 |
+
|
| 114 |
+
We have implemented several tests to verify the Serper API integration:
|
| 115 |
+
|
| 116 |
+
1. **Standalone API Test**: `tests/test_serper_api.py` - Tests the direct connection to the Serper API.
|
| 117 |
+
2. **Unit Tests**: `tests/test_tools.py` - Contains unit tests for the `SerperSearchTool` class.
|
| 118 |
+
3. **Integration Tests**: `tests/test_gaia_serper_integration.py` - Tests the integration of Serper with the GAIA agent.
|
| 119 |
+
4. **Connection Verification**: `tests/verify_connections.py` - Includes a function to verify the Serper API connection.
|
| 120 |
+
|
| 121 |
+
### Running the Tests
|
| 122 |
+
|
| 123 |
+
To test the Serper API connection:
|
| 124 |
+
|
| 125 |
+
```bash
|
| 126 |
+
python tests/test_serper_api.py
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
To run the integration tests:
|
| 130 |
+
|
| 131 |
+
```bash
|
| 132 |
+
python tests/test_gaia_serper_integration.py
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
To verify all connections including Serper:
|
| 136 |
+
|
| 137 |
+
```bash
|
| 138 |
+
python tests/verify_connections.py
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
## Troubleshooting
|
| 142 |
+
|
| 143 |
+
Common issues and their solutions:
|
| 144 |
+
|
| 145 |
+
1. **API Key Not Set**: Ensure the `SERPER_API_KEY` environment variable is set correctly.
|
| 146 |
+
2. **Connection Timeout**: Check your internet connection and try again later.
|
| 147 |
+
3. **Rate Limiting**: Serper API has rate limits. Check your usage and consider upgrading your plan if necessary.
|
| 148 |
+
4. **Invalid Response Format**: If the API response format changes, update the `SerperSearchTool.search` method to handle the new format.
|
| 149 |
+
|
| 150 |
+
## References
|
| 151 |
+
|
| 152 |
+
- [Serper API Documentation](https://serper.dev/docs)
|
| 153 |
+
- [GAIA Agent Documentation](./configuration.md)
|
docs/supabase_memory_integration.md
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Supabase Memory Integration for GAIA Agent
|
| 2 |
+
|
| 3 |
+
This document provides an overview of the Supabase memory integration for the GAIA agent, including setup instructions, table structure, and testing procedures.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
The GAIA agent uses Supabase as a persistent memory storage solution. This allows the agent to maintain memory across different sessions and provides a reliable way to store conversation history, cache results, and track intermediate results during agent execution.
|
| 8 |
+
|
| 9 |
+
The memory implementation consists of the following components:
|
| 10 |
+
|
| 11 |
+
1. **SupabaseMemory**: Base memory implementation using Supabase for storage
|
| 12 |
+
2. **ConversationMemory**: Memory implementation for storing conversation history
|
| 13 |
+
3. **ResultCache**: Memory implementation for caching tool results and answers
|
| 14 |
+
4. **WorkingMemory**: Memory implementation for storing intermediate results during agent execution
|
| 15 |
+
|
| 16 |
+
## Supabase Setup
|
| 17 |
+
|
| 18 |
+
### Prerequisites
|
| 19 |
+
|
| 20 |
+
- A Supabase account
|
| 21 |
+
- A Supabase project
|
| 22 |
+
- Supabase API key with appropriate permissions
|
| 23 |
+
|
| 24 |
+
### Environment Variables
|
| 25 |
+
|
| 26 |
+
The following environment variables need to be set:
|
| 27 |
+
|
| 28 |
+
```
|
| 29 |
+
SUPABASE_KEY=your_supabase_api_key
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
The Supabase URL and project details are configured in `agent/config.py`:
|
| 33 |
+
|
| 34 |
+
```python
|
| 35 |
+
# Supabase Configuration
|
| 36 |
+
SUPABASE_URL = "https://tjamxhvvtnypbadvrkjq.supabase.co"
|
| 37 |
+
SUPABASE_PROJECT_ID = "tjamxhvvtnypbadvrkjq"
|
| 38 |
+
SUPABASE_PROJECT_NAME = "HF_GAIA_Assessment_AGT"
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
### Table Structure
|
| 42 |
+
|
| 43 |
+
The Supabase integration uses the following tables:
|
| 44 |
+
|
| 45 |
+
1. **gaia_memory**: Main memory table for storing key-value pairs
|
| 46 |
+
2. **gaia_memory_conversations**: Conversation history table
|
| 47 |
+
3. **gaia_memory_cache**: Cache table for storing tool results and answers
|
| 48 |
+
4. **gaia_memory_working**: Working memory table for storing intermediate results
|
| 49 |
+
5. **test_connection**: Test table for verifying connection
|
| 50 |
+
|
| 51 |
+
You can create these tables by running the SQL statements in `supabase_tables.sql` in the Supabase SQL Editor.
|
| 52 |
+
|
| 53 |
+
## Memory Implementation
|
| 54 |
+
|
| 55 |
+
### SupabaseMemory
|
| 56 |
+
|
| 57 |
+
The `SupabaseMemory` class provides the base memory implementation using Supabase for storage. It supports the following operations:
|
| 58 |
+
|
| 59 |
+
- `store(key, value, metadata, ttl)`: Store a value in memory
|
| 60 |
+
- `retrieve(key, default)`: Retrieve a value from memory
|
| 61 |
+
- `delete(key)`: Delete a value from memory
|
| 62 |
+
- `clear()`: Clear all values from memory
|
| 63 |
+
- `list_keys(prefix)`: List all keys in memory
|
| 64 |
+
|
| 65 |
+
### ConversationMemory
|
| 66 |
+
|
| 67 |
+
The `ConversationMemory` class provides memory implementation for storing conversation history. It supports the following operations:
|
| 68 |
+
|
| 69 |
+
- `add_message(role, content, metadata)`: Add a message to the conversation history
|
| 70 |
+
- `get_messages(limit, before, after)`: Get messages from the conversation history
|
| 71 |
+
- `clear()`: Clear the conversation history
|
| 72 |
+
|
| 73 |
+
### ResultCache
|
| 74 |
+
|
| 75 |
+
The `ResultCache` class provides memory implementation for caching tool results and answers. It supports the following operations:
|
| 76 |
+
|
| 77 |
+
- `cache_result(query, result, metadata, ttl)`: Cache a result
|
| 78 |
+
- `get_result(query, default)`: Get a cached result
|
| 79 |
+
- `invalidate(key)`: Invalidate a cached result
|
| 80 |
+
- `clear()`: Clear all cached results
|
| 81 |
+
|
| 82 |
+
### WorkingMemory
|
| 83 |
+
|
| 84 |
+
The `WorkingMemory` class provides memory implementation for storing intermediate results during agent execution. It supports the following operations:
|
| 85 |
+
|
| 86 |
+
- `store_intermediate_result(key, value, metadata, ttl)`: Store an intermediate result
|
| 87 |
+
- `get_intermediate_result(key, default)`: Get an intermediate result
|
| 88 |
+
- `list_intermediate_results()`: List all intermediate results
|
| 89 |
+
- `clear()`: Clear all intermediate results
|
| 90 |
+
|
| 91 |
+
## Testing
|
| 92 |
+
|
| 93 |
+
### Test Scripts
|
| 94 |
+
|
| 95 |
+
The following test scripts are available for testing the Supabase memory integration:
|
| 96 |
+
|
| 97 |
+
1. **test_supabase_connection.py**: Tests the connection to Supabase and verifies that the required tables exist
|
| 98 |
+
2. **test_supabase_memory.py**: Tests the Supabase memory module implementation
|
| 99 |
+
3. **test_gaia_supabase_integration.py**: Tests the integration of the GAIA agent with Supabase memory
|
| 100 |
+
4. **run_supabase_integration_tests.py**: Runs all the Supabase integration tests and documents the results
|
| 101 |
+
|
| 102 |
+
### Running the Tests
|
| 103 |
+
|
| 104 |
+
To run all the Supabase integration tests, use the following command:
|
| 105 |
+
|
| 106 |
+
```bash
|
| 107 |
+
python tests/run_supabase_integration_tests.py
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
For verbose output, add the `--verbose` flag:
|
| 111 |
+
|
| 112 |
+
```bash
|
| 113 |
+
python tests/run_supabase_integration_tests.py --verbose
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
To specify a custom output directory for the test results, use the `--output-dir` option:
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
python tests/run_supabase_integration_tests.py --output-dir custom_docs
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
### Test Results
|
| 123 |
+
|
| 124 |
+
The test results are documented in a markdown file in the specified output directory (default: `docs`). The file includes:
|
| 125 |
+
|
| 126 |
+
- Test summary with date and Supabase project details
|
| 127 |
+
- Results for each test with status (passed/failed)
|
| 128 |
+
- Detailed test output in collapsible sections
|
| 129 |
+
- Overall assessment and recommendations
|
| 130 |
+
|
| 131 |
+
## Troubleshooting
|
| 132 |
+
|
| 133 |
+
If the tests fail, check the following:
|
| 134 |
+
|
| 135 |
+
1. **Supabase Connection**:
|
| 136 |
+
- Verify that the Supabase URL and API key are correctly set
|
| 137 |
+
- Check that the Supabase project is active
|
| 138 |
+
- Ensure that the API key has the necessary permissions
|
| 139 |
+
|
| 140 |
+
2. **Table Structure**:
|
| 141 |
+
- Verify that all required tables exist in the Supabase database
|
| 142 |
+
- Check that the tables have the correct structure
|
| 143 |
+
- Ensure that the indexes are properly created
|
| 144 |
+
|
| 145 |
+
3. **Memory Configuration**:
|
| 146 |
+
- Check that memory is enabled in the configuration
|
| 147 |
+
- Verify that the table names are correctly set
|
| 148 |
+
- Ensure that the TTL and cache size settings are appropriate
|
| 149 |
+
|
| 150 |
+
4. **Agent Integration**:
|
| 151 |
+
- Check that the agent is correctly using the memory components
|
| 152 |
+
- Verify that the conversation ID and session ID are properly set
|
| 153 |
+
- Ensure that the agent is correctly processing questions
|
| 154 |
+
|
| 155 |
+
## Best Practices
|
| 156 |
+
|
| 157 |
+
1. **Memory Management**:
|
| 158 |
+
- Regularly clear unused memory to prevent excessive storage usage
|
| 159 |
+
- Use appropriate TTL values for different types of memory entries
|
| 160 |
+
- Monitor memory usage and adjust cache sizes as needed
|
| 161 |
+
|
| 162 |
+
2. **Error Handling**:
|
| 163 |
+
- Implement proper error handling for memory operations
|
| 164 |
+
- Gracefully handle connection issues and retry operations when appropriate
|
| 165 |
+
- Log memory-related errors for debugging purposes
|
| 166 |
+
|
| 167 |
+
3. **Security**:
|
| 168 |
+
- Use a secure API key with appropriate permissions
|
| 169 |
+
- Do not store sensitive information in memory
|
| 170 |
+
- Regularly rotate API keys for security
|
| 171 |
+
|
| 172 |
+
4. **Performance**:
|
| 173 |
+
- Use efficient queries to minimize latency
|
| 174 |
+
- Implement caching to reduce database load
|
| 175 |
+
- Monitor query performance and optimize as needed
|
docs/troubleshooting.md
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Troubleshooting Guide for GAIA Agent
|
| 2 |
+
|
| 3 |
+
This guide addresses common issues you might encounter when setting up, configuring, or running the GAIA agent. It provides solutions and workarounds for these issues.
|
| 4 |
+
|
| 5 |
+
## Table of Contents
|
| 6 |
+
|
| 7 |
+
- [Dependency Issues](#dependency-issues)
|
| 8 |
+
- [langchain_openai Issues](#langchain_openai-issues)
|
| 9 |
+
- [Other Dependency Issues](#other-dependency-issues)
|
| 10 |
+
- [API Connection Issues](#api-connection-issues)
|
| 11 |
+
- [OpenAI API Issues](#openai-api-issues)
|
| 12 |
+
- [Serper API Issues](#serper-api-issues)
|
| 13 |
+
- [Perplexity API Issues](#perplexity-api-issues)
|
| 14 |
+
- [Supabase Issues](#supabase-issues)
|
| 15 |
+
- [Connection Issues](#connection-issues)
|
| 16 |
+
- [Table Structure Issues](#table-structure-issues)
|
| 17 |
+
- [Memory Issues](#memory-issues)
|
| 18 |
+
- [Agent Execution Issues](#agent-execution-issues)
|
| 19 |
+
- [Testing Issues](#testing-issues)
|
| 20 |
+
|
| 21 |
+
## Dependency Issues
|
| 22 |
+
|
| 23 |
+
### langchain_openai Issues
|
| 24 |
+
|
| 25 |
+
The `langchain_openai` package is a critical dependency for the GAIA agent, as it provides the interface to OpenAI's language models. Here are common issues and their solutions:
|
| 26 |
+
|
| 27 |
+
#### ImportError: No module named 'langchain_openai'
|
| 28 |
+
|
| 29 |
+
This error occurs when the `langchain_openai` package is not installed or not in your Python path.
|
| 30 |
+
|
| 31 |
+
**Solution:**
|
| 32 |
+
```bash
|
| 33 |
+
pip install langchain_openai
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
If you already have it installed, try upgrading to the latest version:
|
| 37 |
+
```bash
|
| 38 |
+
pip install --upgrade langchain_openai
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
#### AttributeError: module 'langchain_openai' has no attribute 'ChatOpenAI'
|
| 42 |
+
|
| 43 |
+
This error can occur if you have an outdated version of `langchain_openai` or if there's a conflict with other packages.
|
| 44 |
+
|
| 45 |
+
**Solutions:**
|
| 46 |
+
|
| 47 |
+
1. Upgrade to the latest version:
|
| 48 |
+
```bash
|
| 49 |
+
pip install --upgrade langchain_openai
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
2. Check for conflicts with older versions of langchain:
|
| 53 |
+
```bash
|
| 54 |
+
pip uninstall langchain-openai # Note the hyphen instead of underscore
|
| 55 |
+
pip install langchain_openai # Install the correct package
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
3. Verify your import statement:
|
| 59 |
+
```python
|
| 60 |
+
# Correct import
|
| 61 |
+
from langchain_openai import ChatOpenAI
|
| 62 |
+
|
| 63 |
+
# Incorrect import (old style)
|
| 64 |
+
# from langchain.chat_models import ChatOpenAI
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
#### Version Compatibility Issues
|
| 68 |
+
|
| 69 |
+
If you're experiencing compatibility issues between `langchain`, `langchain_openai`, and other LangChain packages:
|
| 70 |
+
|
| 71 |
+
**Solution:**
|
| 72 |
+
```bash
|
| 73 |
+
pip install --upgrade langchain langchain_openai langgraph
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
This ensures all LangChain-related packages are updated to compatible versions.
|
| 77 |
+
|
| 78 |
+
### Other Dependency Issues
|
| 79 |
+
|
| 80 |
+
#### Missing Dependencies
|
| 81 |
+
|
| 82 |
+
If you encounter errors about missing dependencies:
|
| 83 |
+
|
| 84 |
+
**Solution:**
|
| 85 |
+
```bash
|
| 86 |
+
pip install -r requirements.txt
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
#### Conflicting Dependencies
|
| 90 |
+
|
| 91 |
+
If you have conflicting dependencies:
|
| 92 |
+
|
| 93 |
+
**Solution:**
|
| 94 |
+
```bash
|
| 95 |
+
# Create a fresh virtual environment
|
| 96 |
+
python -m venv fresh_env
|
| 97 |
+
source fresh_env/bin/activate # On Windows: fresh_env\Scripts\activate
|
| 98 |
+
pip install -r requirements.txt
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
## API Connection Issues
|
| 102 |
+
|
| 103 |
+
### OpenAI API Issues
|
| 104 |
+
|
| 105 |
+
#### Authentication Error
|
| 106 |
+
|
| 107 |
+
If you see an error like `AuthenticationError: Incorrect API key provided`:
|
| 108 |
+
|
| 109 |
+
**Solutions:**
|
| 110 |
+
1. Verify your API key is correct and active in your OpenAI account
|
| 111 |
+
2. Check that the environment variable is set correctly:
|
| 112 |
+
```bash
|
| 113 |
+
# In your .env file
|
| 114 |
+
OPENAI_API_KEY=your_actual_api_key
|
| 115 |
+
```
|
| 116 |
+
3. Try setting the API key directly in your code (for testing only):
|
| 117 |
+
```python
|
| 118 |
+
import os
|
| 119 |
+
os.environ["OPENAI_API_KEY"] = "your_actual_api_key"
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
#### Rate Limit Exceeded
|
| 123 |
+
|
| 124 |
+
If you encounter rate limit errors:
|
| 125 |
+
|
| 126 |
+
**Solutions:**
|
| 127 |
+
1. Implement exponential backoff and retry logic
|
| 128 |
+
2. Reduce the frequency of API calls
|
| 129 |
+
3. Consider upgrading your OpenAI plan for higher rate limits
|
| 130 |
+
|
| 131 |
+
### Serper API Issues
|
| 132 |
+
|
| 133 |
+
#### Authentication Error
|
| 134 |
+
|
| 135 |
+
If you encounter authentication errors with Serper:
|
| 136 |
+
|
| 137 |
+
**Solution:**
|
| 138 |
+
Verify your Serper API key is correctly set in the environment variables:
|
| 139 |
+
```bash
|
| 140 |
+
# In your .env file
|
| 141 |
+
SERPER_API_KEY=your_serper_api_key
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
#### No Results Returned
|
| 145 |
+
|
| 146 |
+
If Serper searches return no results:
|
| 147 |
+
|
| 148 |
+
**Solutions:**
|
| 149 |
+
1. Check your query formatting
|
| 150 |
+
2. Verify that Serper is available and operational
|
| 151 |
+
3. Try using an alternative search provider like DuckDuckGo
|
| 152 |
+
|
| 153 |
+
### Perplexity API Issues
|
| 154 |
+
|
| 155 |
+
#### Authentication Error
|
| 156 |
+
|
| 157 |
+
If you encounter authentication errors with Perplexity:
|
| 158 |
+
|
| 159 |
+
**Solution:**
|
| 160 |
+
Verify your Perplexity API key is correctly set in the environment variables:
|
| 161 |
+
```bash
|
| 162 |
+
# In your .env file
|
| 163 |
+
PERPLEXITY_API_KEY=your_perplexity_api_key
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
#### Model Not Available
|
| 167 |
+
|
| 168 |
+
If you encounter errors about a model not being available:
|
| 169 |
+
|
| 170 |
+
**Solution:**
|
| 171 |
+
Check the available models in your Perplexity account and update the configuration accordingly.
|
| 172 |
+
|
| 173 |
+
## Supabase Issues
|
| 174 |
+
|
| 175 |
+
### Connection Issues
|
| 176 |
+
|
| 177 |
+
#### Authentication Error
|
| 178 |
+
|
| 179 |
+
If you encounter authentication errors with Supabase:
|
| 180 |
+
|
| 181 |
+
**Solution:**
|
| 182 |
+
Verify your Supabase URL and API key are correctly set:
|
| 183 |
+
```bash
|
| 184 |
+
# In your .env file
|
| 185 |
+
SUPABASE_URL=https://your-project-id.supabase.co
|
| 186 |
+
SUPABASE_KEY=your_supabase_api_key
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
#### Connection Timeout
|
| 190 |
+
|
| 191 |
+
If you encounter connection timeouts:
|
| 192 |
+
|
| 193 |
+
**Solutions:**
|
| 194 |
+
1. Check your internet connection
|
| 195 |
+
2. Verify that your Supabase project is active
|
| 196 |
+
3. Implement retry logic with exponential backoff
|
| 197 |
+
|
| 198 |
+
### Table Structure Issues
|
| 199 |
+
|
| 200 |
+
#### Missing Tables
|
| 201 |
+
|
| 202 |
+
If you encounter errors about missing tables:
|
| 203 |
+
|
| 204 |
+
**Solution:**
|
| 205 |
+
Run the SQL statements in `supabase_tables.sql` in the Supabase SQL Editor to create the required tables.
|
| 206 |
+
|
| 207 |
+
#### Incorrect Table Structure
|
| 208 |
+
|
| 209 |
+
If you encounter errors about incorrect table structure:
|
| 210 |
+
|
| 211 |
+
**Solution:**
|
| 212 |
+
Compare your table structure with the expected structure in `supabase_tables.sql` and make any necessary adjustments.
|
| 213 |
+
|
| 214 |
+
## Memory Issues
|
| 215 |
+
|
| 216 |
+
#### Memory Not Persisting
|
| 217 |
+
|
| 218 |
+
If the agent's memory is not persisting between sessions:
|
| 219 |
+
|
| 220 |
+
**Solutions:**
|
| 221 |
+
1. Verify that memory is enabled in the configuration
|
| 222 |
+
2. Check that the Supabase connection is working correctly
|
| 223 |
+
3. Verify that the memory tables exist and have the correct structure
|
| 224 |
+
|
| 225 |
+
#### Memory Retrieval Issues
|
| 226 |
+
|
| 227 |
+
If the agent is unable to retrieve memory:
|
| 228 |
+
|
| 229 |
+
**Solutions:**
|
| 230 |
+
1. Check the memory key format
|
| 231 |
+
2. Verify that the TTL (time-to-live) settings are appropriate
|
| 232 |
+
3. Check for errors in the Supabase logs
|
| 233 |
+
|
| 234 |
+
## Agent Execution Issues
|
| 235 |
+
|
| 236 |
+
#### Agent Not Responding
|
| 237 |
+
|
| 238 |
+
If the agent is not responding or taking too long:
|
| 239 |
+
|
| 240 |
+
**Solutions:**
|
| 241 |
+
1. Check the timeout settings in the configuration
|
| 242 |
+
2. Verify that all required APIs are available
|
| 243 |
+
3. Check for errors in the logs
|
| 244 |
+
|
| 245 |
+
#### Incorrect Answers
|
| 246 |
+
|
| 247 |
+
If the agent is providing incorrect answers:
|
| 248 |
+
|
| 249 |
+
**Solutions:**
|
| 250 |
+
1. Check the question format
|
| 251 |
+
2. Verify that the agent is using the correct tools
|
| 252 |
+
3. Check the answer extraction logic
|
| 253 |
+
|
| 254 |
+
## Testing Issues
|
| 255 |
+
|
| 256 |
+
#### Tests Failing
|
| 257 |
+
|
| 258 |
+
If tests are failing:
|
| 259 |
+
|
| 260 |
+
**Solutions:**
|
| 261 |
+
1. Check that all required environment variables are set
|
| 262 |
+
2. Verify that all required APIs are available
|
| 263 |
+
3. Check for errors in the test logs
|
| 264 |
+
|
| 265 |
+
#### Test Timeouts
|
| 266 |
+
|
| 267 |
+
If tests are timing out:
|
| 268 |
+
|
| 269 |
+
**Solutions:**
|
| 270 |
+
1. Increase the timeout settings
|
| 271 |
+
2. Run tests individually to identify the problematic test
|
| 272 |
+
3. Check for resource-intensive operations that might be causing the timeout
|
| 273 |
+
|
| 274 |
+
## Additional Resources
|
| 275 |
+
|
| 276 |
+
If you're still experiencing issues after trying the solutions in this guide, consider the following resources:
|
| 277 |
+
|
| 278 |
+
1. Check the [GitHub repository](https://github.com/your-repo) for open issues or create a new one
|
| 279 |
+
2. Consult the [LangChain documentation](https://python.langchain.com/docs/get_started/introduction)
|
| 280 |
+
3. Refer to the [OpenAI API documentation](https://platform.openai.com/docs/api-reference)
|
| 281 |
+
4. Check the [Supabase documentation](https://supabase.com/docs)
|