### Quick Start: Setup and Basic Usage Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/image_tools.md Set environment variables and initialize toolkits. Shows default local storage and custom storage path using LocalStorageHandler. ```python from evoagentx.tools import OpenAIImageToolkit, OpenRouterImageToolkit, FluxImageGenerationToolkit # Basic usage with default local storage tk = OpenAIImageToolkit(api_key=OPENAI_API_KEY) # Custom storage path from evoagentx.tools import LocalStorageHandler storage_handler = LocalStorageHandler(base_path="./my_images") tk = OpenAIImageToolkit(api_key=OPENAI_API_KEY, storage_handler=storage_handler) ``` -------------------------------- ### Run all tool examples Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Executes the comprehensive examples file, excluding image tools. ```bash # Run the comprehensive examples file (except for image tools) python -m examples.tools.tools ``` -------------------------------- ### Example output from interpreter examples Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Example output from running the interpreter examples, showing the sections for code, Python, and Docker interpreter examples. ```text ===== CODE INTERPRETER EXAMPLES ===== ===== PYTHON INTERPRETER EXAMPLES ===== Simple Hello World Result: -------------------------------------------------- Hello, World! This code is running inside a secure Python interpreter. -------------------------------------------------- ===== DOCKER INTERPRETER EXAMPLES ===== Running Docker interpreter examples... ... ``` -------------------------------- ### Example output from image tool examples Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Example output from running the image tool examples. Shows the OpenAIImageToolkit pipeline (generation, editing, analysis) with success indicators and generated file paths. The output confirms the toolkit initialized and used the OpenAI API key. ```text ===== IMAGE TOOL EXAMPLES ===== ===== OPENAI IMAGE TOOLKIT PIPELINE (GEN → EDIT → ANALYZE) ===== ✓ OpenAIImageToolkit initialized ✓ Using OpenAI API key: your-key... Generating: A cute baby owl sitting on a tree branch at sunset, digital art ✓ Image generation successful Generated image: ./generated_images/generated_1757661778_1.png ✓ Image editing successful Edited image: ./generated_images/edited_minimal_1757661779_1.png ✓ Image analysis successful Analysis: This image shows a cute baby owl... ===== ALL IMAGE TOOL EXAMPLES COMPLETED ===== ``` -------------------------------- ### Running browser tool examples Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Commands to run the browser tool examples, either from the project root or from the examples/tools directory. ```bash # Run all browser tool examples python -m examples.tools.tools_browser # Or run from the examples/tools directory cd examples/tools python tools_browser.py ``` -------------------------------- ### Run interpreter examples Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Commands to run the code interpreter examples. The first runs the module directly, the second navigates to the examples directory and runs the script. ```bash # Run all interpreter examples python -m examples.tools.tools_interpreter # Or run from the examples/tools directory cd examples/tools python tools_interpreter.py ``` -------------------------------- ### Complete Example: Find and Call an MCP Tool Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/mcp.md Complete example of initializing MCPToolkit, finding a specific tool by name, calling it with parameters, and disconnecting. Shows how to search for a tool and invoke it with the arXiv search schema. ```python from evoagentx.tools import MCPToolkit # Initialize the MCP toolkit toolkit = MCPToolkit(config_path="examples/mcp.config") # Get all available toolkits toolkits = toolkit.get_toolkits() # Find a specific tool by searching through toolkits arxiv_tool = None for toolkit in toolkits: tools = toolkit.get_tools() for tool in tools: if "arxiv" in tool.name.lower() or "search" in tool.name.lower(): arxiv_tool = tool break if arxiv_tool: break if arxiv_tool: # Call the tool with appropriate parameters (showing arXiv search schema) result = arxiv_tool( query="artificial intelligence machine learning", max_results=5, sort_by="relevance", sort_order="descending" ) print(f"arXiv search results: {result}") # Clean up when done toolkit.disconnect() ``` -------------------------------- ### Full RAGEngine example with HotPotQA dataset Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/rag.md Complete example that downloads HotPotQA data, initializes storage and RAGEngine, and processes the dataset. Requires dotenv and environment variables. ```python import os import json import logging from typing import List, Dict from collections import defaultdict from dotenv import load_dotenv from evoagentx.storages.base import StorageHandler from evoagentx.rag.rag import RAGEngine from evoagentx.core.logging import logger from evoagentx.storages.storages_config import VectorStoreConfig, DBConfig, StoreConfig from evoagentx.rag.rag_config import RAGConfig, ReaderConfig, ChunkerConfig, IndexConfig, EmbeddingConfig, RetrievalConfig from evoagentx.rag.schema import Query, Corpus, Chunk, ChunkMetadata from evoagentx.benchmark.hotpotqa import HotPotQA, download_raw_hotpotqa_data # Load environment load_dotenv() # Download datasets download_raw_hotpotqa_data("hotpot_dev_distractor_v1.json", "./debug/data/hotpotqa") datasets = HotPotQA("./debug/data/hotpotqa") ``` -------------------------------- ### Run Alita agent example with uv Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/alita_agent.md Run the example script with uv. Requires OPENROUTER_API_KEY (or another LLM provider key) and SERPAPI_KEY for web search. ```bash uv run examples/alita_agent_example.py ``` -------------------------------- ### Example output from browser tool examples Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Example output from running the browser tool examples, showing the sequence of operations and results for both AI-driven and Selenium-based browser tools. ```text ===== FOCUSED BROWSER TOOL EXAMPLES ===== ===== AI-DRIVEN BROWSER SEARCH EXAMPLE ===== ✓ BrowserUseToolkit initialized ✓ Using OpenAI API key: your-key... 🔍 Task 1: Searching for EvoAgentX project information... Task: Go to GitHub and search for 'EvoAgentX' project, then collect basic information about the project ✓ Project search completed successfully Result: Successfully found EvoAgentX repository with 1000+ stars, description: "Building a Self-Evolving Ecosystem of AI Agents"... 📚 Task 2: Getting project documentation... Task: Visit the EvoAgentX documentation and collect key information ✓ Documentation collection completed successfully Result: Found main features: workflow generation, agent management, tool integration... ✓ AI-driven browser search completed ===== SELENIUM BASIC BROWSER OPERATIONS ===== ✓ BrowserToolkit initialized ✓ All browser tools loaded successfully Step 1: Browser initialization... Initialization result: success Step 2: Creating and navigating to test page... ✓ Created test page at: /path/to/simple_test_page.html Navigation result: success Page title: Simple Test Page Step 3: Taking snapshot to identify elements... ✓ Snapshot successful Found 7 interactive elements Element 1: name/input Purpose: text input ID: e0 Step 4: Performing basic form operations... - Filling name field... - Filling email field... - Selecting role... - Filling message field... - Submitting form... Submit result: success Step 5: Checking form submission result... ✓ Form submission successful - data correctly displayed! Step 6: Testing clear functionality... Clear result: success Step 7: Testing show hidden content... Show result: success ✓ Hidden content successfully revealed! ✓ Basic browser operations test completed successfully! ===== BROWSER TOOL COMPARISON ===== 🔧 **BrowserToolkit (Selenium-based)** ✅ Pros: Fine-grained control, precise form filling... ❌ Cons: More complex setup, manual element identification... 🤖 **BrowserUseToolkit (AI-driven)** ✅ Pros: Natural language, AI-driven decisions... ❌ Cons: Requires API key, less precise control... ===== ALL BROWSER TOOL EXAMPLES COMPLETED ===== ``` -------------------------------- ### Local development setup with conda Source: https://github.com/anative-lab/evoagentx/blob/main/README.md Clone the repository, create a conda environment with Python 3.11, and install dependencies. Use `pip install -e .` for development mode. ```bash git clone https://github.com/EvoAgentX/EvoAgentX.git cd EvoAgentX # Create a new conda environment conda create -n evoagentx python=3.11 # Activate the environment conda activate evoagentx # Install the package pip install -r requirements.txt # OR install in development mode pip install -e . ``` -------------------------------- ### Example output from converter examples Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Expected output from running the converter examples. Shows the RapidAPI smoke test discovering three weather tools and the MCP integration example initializing and connecting to MCP servers. The real API call is optional and only performed if RAPIDAPI_KEY is set. ```text ===== CONVERTER EXAMPLES ===== ===== API CONVERTER (RapidAPI) SMOKE TEST ===== ✓ Built toolkit from provided spec Available tools: 3 Tool: getCityWeather Tool: getWeatherByCoordinates Tool: getFiveDayForecast (Optional) Real API call performed if RAPIDAPI_KEY is set Result type: ... ===== MCP INTEGRATION EXAMPLE ===== ✓ MCPToolkit initialized ✓ Connected to configured MCP server(s) ✓ Discovered tools and performed sample invocation ``` -------------------------------- ### FluxImageGenerationToolkit Setup Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Setup for FluxImageGenerationToolkit with basic configuration using an API key or environment variable, and an optional custom local storage handler. ```python from evoagentx.tools import FluxImageGenerationToolkit # Basic setup toolkit = FluxImageGenerationToolkit( name="DemoFluxImageToolkit", api_key="your-bfl-api-key", # Or set BFL_API_KEY environment variable save_path="./flux_generated_images" ) # With custom storage from evoagentx.tools import LocalStorageHandler storage_handler = LocalStorageHandler(base_path="./flux_images") toolkit = FluxImageGenerationToolkit( api_key="your-bfl-api-key", storage_handler=storage_handler ) ``` -------------------------------- ### Run converter examples with python -m examples.tools.tools_converters Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Commands to run the converter examples. The first runs the module from the project root; the second changes into the examples/tools directory and runs the script directly. ```bash # Run all converter examples (MCP + API Converter) python -m examples.tools.tools_converters # Or run from the examples/tools directory cd examples/tools python tools_converters.py ``` -------------------------------- ### Run image tool examples Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Commands to run the image handling tool examples. The first command runs the module from the project root, while the second changes to the examples/tools directory and runs the script directly. Requires the appropriate API keys (OPENAI_API_KEY, OPENROUTER_API_KEY, BFL_API_KEY) to be set in environment variables. ```bash # Run all image tool examples python -m examples.tools.tools_images # Or run from the examples/tools directory cd examples/tools python tools_images.py ``` -------------------------------- ### Run individual tool category examples Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Commands to run specific tool category examples, each focusing on a particular tool type. ```bash # Run specific tool categories python -m examples.tools.tools_interpreter # Code interpreters python -m examples.tools.tools_search # Search and request tools python -m examples.tools.tools_files # File system tools python -m examples.tools.tools_database # Database tools python -m examples.tools.tools_images # Image handling tools python -m examples.tools.tools_browser # Browser automation tools python -m examples.tools.tools_integration # MCP and integration tools python -m examples.tools.google_maps_example.py # Google maps tool python -m examples.tools.telegram_example # Telegram tools python -m examples.tools.gmail_example # Gmail tools ``` -------------------------------- ### Install dependencies with pip Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/rag.md Installs the required Python packages for RAGEngine. Run this in your terminal before proceeding. ```bash pip install evoagentx llama_index pydantic python-dotenv ``` -------------------------------- ### Setup OpenAIImageToolkit with storage options Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Setup for OpenAIImageToolkit with default local storage or a custom storage handler. The api_key can be omitted if OPENAI_API_KEY is set. ```python from evoagentx.tools import OpenAIImageToolkit # Basic setup with default local storage toolkit = OpenAIImageToolkit( name="DemoOpenAIImageToolkit", api_key="your-openai-api-key", # Or set OPENAI_API_KEY environment variable organization_id="your-organization-id", # Optional generation_model="dall-e-3", save_path="./generated_images" ) # With custom storage handler from evoagentx.tools import LocalStorageHandler storage_handler = LocalStorageHandler(base_path="./custom_images") toolkit = OpenAIImageToolkit( api_key="your-openai-api-key", storage_handler=storage_handler ) ``` -------------------------------- ### OpenRouterImageToolkit Setup Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Setup for OpenRouterImageToolkit with basic configuration using an API key or environment variable, and an optional custom Supabase storage handler. ```python from evoagentx.tools import OpenRouterImageToolkit # Basic setup toolkit = OpenRouterImageToolkit( name="DemoOpenRouterImageToolkit", api_key="your-openrouter-api-key" # Or set OPENROUTER_API_KEY environment variable ) # With custom storage from evoagentx.tools import SupabaseStorageHandler storage_handler = SupabaseStorageHandler(bucket_name="my-images") toolkit = OpenRouterImageToolkit( api_key="your-openrouter-api-key", storage_handler=storage_handler ) ``` -------------------------------- ### Setup DockerInterpreterToolkit with existing image Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Initializes the toolkit using an existing Docker Hub image (python:3.9-slim) and sets the container directory to /app. This is one of two mutually exclusive setup options. ```python toolkit = DockerInterpreterToolkit( image_tag="python:3.9-slim", # Uses an existing Docker Hub image container_directory="/app" ) ``` -------------------------------- ### Install EvoAgentX from source with pip Source: https://github.com/anative-lab/evoagentx/blob/main/README.md Install the latest version directly from the GitHub repository. ```bash pip install git+https://github.com/EvoAgentX/EvoAgentX.git ``` -------------------------------- ### Install Additional Dependencies Source: https://github.com/anative-lab/evoagentx/blob/main/docs/ColabNotebook/tutorial_notebooks/aflow_optimizer.ipynb Installs additional dependencies required for the AFlow optimizer tutorial. ```python !pip install PyPDF2 selenium html2text fastmcp ``` -------------------------------- ### PostgreSQLToolkit Setup Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Initialize PostgreSQLToolkit with either default storage or custom connection parameters including host, port, user, and password. ```python from evoagentx.tools import PostgreSQLToolkit # Initialize with default storage toolkit = PostgreSQLToolkit( name="DemoPostgreSQLToolkit", database_name="demo_db", auto_save=True ) # Or with custom configuration toolkit = PostgreSQLToolkit( name="CustomPostgreSQLToolkit", database_name="my_database", host="localhost", port=5432, user="myuser", password="mypassword" ) ``` -------------------------------- ### HumanEval example format Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/benchmark.md Shows the format of each example in the HumanEval dataset. The `task_id` is a string like "HumanEval/0", and the example includes the prompt, entry point, canonical solution, and unit tests. ```json { "task_id": "HumanEval/0", "prompt": "the prompt of the problem", "entry_point": "the name of the function to be tested", "canonical_solution": "the canonical solution of the problem", "test": "the unit tests of the problem" } ``` -------------------------------- ### Usage for initialize_browser Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Usage example for the initialize_browser tool. Must be called before any other browser operations. ```python # Get and use the tool initialize_tool = toolkit.get_tool("initialize_browser") result = initialize_tool() ``` -------------------------------- ### View Browser Toolkit Source Files Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Commands to view the browser toolkit source files and the example file. Useful for inspecting the implementation before running examples. ```bash # View toolkit implementations ls evoagentx/tools/browser_*.py # View example file cat examples/tools/tools_browser.py # View toolkit source files cat evoagentx/tools/browser_tool.py cat evoagentx/tools/browser_use.py ``` -------------------------------- ### Usage for navigate_to_url Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Usage example for the navigate_to_url tool. Requires a complete URL with protocol. ```python # Get and use the tool navigate_tool = toolkit.get_tool("navigate_to_url") result = navigate_tool(url="https://example.com") ``` -------------------------------- ### Install EvoAgentX from source Source: https://github.com/anative-lab/evoagentx/blob/main/docs/installation.md Clones the EvoAgentX repository, navigates to the project directory, and installs the package in development mode. This method is intended for contributors or users needing the latest development version. ```bash # Clone the repository git clone https://github.com/EvoAgentX/EvoAgentX.git # Navigate to the project directory cd EvoAgentX # Install the package in development mode pip install -e . ``` -------------------------------- ### MCP configuration file format (FastMCP 2.0) Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/mcp.md Example JSON configuration file for MCP servers. Each server entry can include command (required), args, env, and timeout (optional, defaults to 120.0). This example configures GitHub and arxiv servers. ```json { "mcpServers": { "github": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-github" ], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "your_github_token_here" }, "timeout": 30 }, "arxiv": { "command": "uv", "args": [ "tool", "run", "arxiv-mcp-server", "--storage-path", "./data/" ], "timeout": 45 } } } ``` -------------------------------- ### Configure executor and optimizer LLMs Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/textgrad_optimizer.md Configures two separate LLMs: one for workflow execution (gpt-4o-mini) and one for optimization (gpt-4o). Requires valid API keys; see the Quickstart guide for setup. ```python executor_config = OpenAILLMConfig(model="gpt-4o-mini", openai_key="your_openai_api_key") executor_llm = OpenAILLM(config=executor_config) optimizer_config = OpenAILLMConfig(model="gpt-4o", openai_key="your_openai_api_key") optimizer_llm = OpenAILLM(config=optimizer_config) ``` -------------------------------- ### __init__ Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/rag.md Initializes the RAGEngine with RAG and storage configurations. ```APIDOC ## __init__ ### Description Initializes the RAGEngine with RAG and storage configurations. ### Method Constructor ### Parameters - **config** (RAGConfig) - Required - RAG configuration. - **storage_handler** (StorageHandler) - Required - Storage handler for persistence. ### Return Value None ``` -------------------------------- ### Google Maps Toolkit Complete Example Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Complete example demonstrating Google Maps Toolkit usage: geocoding an address, searching for nearby places, and getting driving directions. Requires GOOGLE_MAPS_API_KEY environment variable; exits if missing. ```python from evoagentx.tools import GoogleMapsToolkit # Initialize the toolkit toolkit = GoogleMapsToolkit() # Check if API key is available if not toolkit.google_maps_base.api_key: print("Please set GOOGLE_MAPS_API_KEY environment variable") print("Get your API key from: https://console.cloud.google.com/apis/") exit(1) print("=== Google Maps Platform Tools Demo ===\n") # 1. Geocoding - Convert address to coordinates print("1. Geocoding Address to Coordinates") geocode_tool = toolkit.get_tool("geocode_address") result = geocode_tool(address="1600 Amphitheatre Parkway, Mountain View, CA") if result["success"]: print(f"Address: {result['formatted_address']}") print(f"Coordinates: {result['latitude']}, {result['longitude']}") lat, lng = result['latitude'], result['longitude'] else: print(f"Geocoding failed: {result['error']}") exit(1) # 2. Places Search - Find nearby restaurants print("\n2. Places Search - Find Restaurants") places_search_tool = toolkit.get_tool("places_search") result = places_search_tool( query="restaurants near Mountain View, CA", location=f"{lat},{lng}", radius=2000 ) if result["success"]: print(f"Found {result['places_found']} restaurants") for i, place in enumerate(result['places'][:3]): print(f" {i+1}. {place['name']} - Rating: {place.get('rating', 'N/A')}") else: print(f"Places search failed: {result['error']}") # 3. Directions - Get driving directions print("\n3. Directions - Driving Route") directions_tool = toolkit.get_tool("directions") result = directions_tool( origin="San Francisco, CA", destination="Mountain View, CA", mode="driving" ) if result["success"] and result['routes']: route = result['routes'][0] print(f"Route from {result['origin']} to {result['destination']}") print(f"Distance: {route['total_distance_meters']} meters") print(f"Duration: {route['total_duration_seconds']} seconds") else: print(f"Directions failed: {result['error']}") print("\n=== Demo Complete ===") ``` -------------------------------- ### Sample return from python_execute_script Source: https://github.com/anative-lab/evoagentx/blob/main/docs/ColabNotebook/tutorial_notebooks/tools.ipynb Sample output from the python_execute_script tool when running the example script. It shows the script execution messages. ```python Running hello_world.py... Hello from the script file! Script execution completed. ``` -------------------------------- ### Batch generation with lists Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/llm.md Batch generation example showing how to pass lists of prompts and system messages to the generate function. ```python # Batch processing example responses = llm.generate( prompt=["What is machine learning?", "Explain neural networks."], system_message=["You are a data scientist.", "You are an AI researcher."] ) ``` -------------------------------- ### Asynchronous Evaluation with asyncio Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/evaluator.md Shows how to run evaluation asynchronously using the async_evaluate method. The example defines an async function that creates an evaluator and runs it with asyncio.run. It includes the necessary imports and setup for async evaluation. ```python import asyncio from evoagentx.evaluators import Evaluator from evoagentx.models import OpenAILLMConfig, OpenAILLM from evoagentx.agents import AgentManager from evoagentx.workflow.workflow_graph import WorkFlowGraph from evoagentx.benchmark import SomeBenchmark from evoagentx.core.callbacks import suppress_logger_info # Initialize LLM and components llm_config = OpenAILLMConfig(model="gpt-4o-mini", openai_key="xxx") llm = OpenAILLM(llm_config) agent_manager = AgentManager() workflow_graph = WorkFlowGraph.from_file("path/to/workflow.json") benchmark = SomeBenchmark() # Create evaluator evaluator = Evaluator( llm=llm, agent_manager=agent_manager, num_workers=4 ) # Run async evaluation async def run_async_eval(): with suppress_logger_info(): results = await evaluator.async_evaluate( graph=workflow_graph, benchmark=benchmark ) return results # Execute async evaluation results = asyncio.run(run_async_eval()) ``` -------------------------------- ### Use FaissToolkit methods for insert, query, stats, and delete Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Demonstrates the main FaissToolkit operations: retrieving tools, inserting documents with metadata, performing a semantic query with top_k and similarity_threshold, getting statistics, and deleting by metadata filter. The example uses AI knowledge documents and a metadata filter on the source field. ```python # Get tools insert_tool = toolkit.get_tool("faiss_insert") query_tool = toolkit.get_tool("faiss_query") stats_tool = toolkit.get_tool("faiss_stats") delete_tool = toolkit.get_tool("faiss_delete") # Insert AI knowledge documents documents = [ "Artificial Intelligence (AI) is a branch of computer science that aims to create intelligent machines capable of performing tasks that typically require human intelligence.", "Machine learning is a subset of artificial intelligence that enables computers to learn and improve from experience without being explicitly programmed.", "Deep learning is a specialized form of machine learning that uses neural networks with multiple layers to analyze and learn from data." ] # Insert with metadata result = insert_tool( documents=documents, metadata={ "source": "AI_knowledge_base", "topic": "artificial_intelligence", "language": "en" } ) # Perform semantic search search_result = query_tool( query="How do machines learn?", top_k=3, similarity_threshold=0.1 ) # Get database statistics stats_result = stats_tool() # Delete documents by metadata filter delete_result = delete_tool( metadata_filters={"source": "AI_knowledge_base"} ) ``` -------------------------------- ### Sample Return for initialize_browser Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Sample return from the initialize_browser tool. Indicates successful browser initialization. ```python { "status": "success", "message": "Browser chrome initialized successfully" } ``` -------------------------------- ### Setup DockerInterpreterToolkit with Dockerfile Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Initializes the toolkit by building a custom Docker image from a Dockerfile. The dockerfile_path and image_tag are required, and the container directory is set to /app. This is the alternative to using an existing image. ```python toolkit = DockerInterpreterToolkit( dockerfile_path="path/to/Dockerfile", # Builds a custom image image_tag="my-custom-image-name", # Name for the built image container_directory="/app" ) ``` -------------------------------- ### GSM8K dataset example format Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/benchmark.md Format of each example in the GSM8K dataset. ```json { "id": "test-1", "question": "the question", "answer": "the answer" } ``` -------------------------------- ### initialize_browser: Sample Return and Usage Source: https://github.com/anative-lab/evoagentx/blob/main/docs/ColabNotebook/tutorial_notebooks/tools.ipynb Sample return and usage for the initialize_browser method. Must be called before any other browser operations. ```python { "status": "success", "message": "Browser chrome initialized successfully" } ``` ```python # Get and use the tool initialize_tool = toolkit.get_tool("initialize_browser") result = initialize_tool() ``` -------------------------------- ### 创建 rag_tutorial.py 索引并查询 HotPotQA 文档 Source: https://github.com/anative-lab/evoagentx/blob/main/docs/zh/tutorial/rag.md 完整脚本,用于加载 HotPotQA 示例、配置 RAGEngine(使用 SQLite 存储元数据、FAISS 存储向量、OpenAI 嵌入)、索引文本文件并执行查询。需要设置 OPENAI_API_KEY 环境变量,并确保 ./data/hotpotqa_sample.json 存在。 ```python import os import json from dotenv import load_dotenv from evoagentx.rag.schema import Query from evoagentx.rag.rag import RAGEngine from evoagentx.rag.rag_config import RAGConfig, ReaderConfig, ChunkerConfig, EmbeddingConfig, IndexConfig, RetrievalConfig from evoagentx.storages.base import StorageHandler from evoagentx.storages.storages_config import StoreConfig, VectorStoreConfig, DBConfig # 加载环境变量 load_dotenv() OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") # 配置存储(SQLite 用于元数据,FAISS 用于向量) store_config = StoreConfig( dbConfig=DBConfig(db_name="sqlite", path="./data/cache.db"), vectorConfig=VectorStoreConfig(vector_name="faiss", dimensions=1536, index_type="flat_l2"), graphConfig=None, path="./data/indexing" ) storage_handler = StorageHandler(storageConfig=store_config) # 配置 RAGEngine rag_config = RAGConfig( reader=ReaderConfig(recursive=False, exclude_hidden=True), chunker=ChunkerConfig(strategy="simple", chunk_size=512, chunk_overlap=50), embedding=EmbeddingConfig(provider="openai", model_name="text-embedding-ada-002", api_key=OPENAI_API_KEY), index=IndexConfig(index_type="vector"), retrieval=RetrievalConfig(retrieval_type="vector", postprocessor_type="simple", top_k=3, similarity_cutoff=0.3) ) # 初始化 RAGEngine rag_engine = RAGEngine(config=rag_config, storage_handler=storage_handler) print("RAGEngine 已准备就绪!") # 步骤 1:加载并索引 HotPotQA 示例 with open("./data/hotpotqa_sample.json", "r", encoding="utf-8") as f: hotpotqa_data = json.load(f) # 创建一个临时文本文件,包含上下文用于索引 context = hotpotqa_data["context"] with open("./data/hotpotqa_context.txt", "w", encoding="utf-8") as f: for title, sentences in context: f.write(f"# {title}") for sentence in sentences: f.write(f"{sentence}\n") f.write(f"\n\n") # 索引文本文件 corpus = rag_engine.read( file_paths="./data/hotpotqa_context.txt", filter_file_by_suffix=[".txt"], merge_by_file=True, show_progress=True, corpus_id="hotpotqa_corpus" ) rag_engine.add(index_type="vector", nodes=corpus, corpus_id="hotpotqa_corpus") print("文档索引成功!") # 步骤 2:查询索引 query = Query(query_str="Were Scott Derrickson and Ed Wood of the same nationality?", top_k=3) result = rag_engine.query(query, corpus_id="hotpotqa_corpus") # 打印检索到的分块 print("\n检索到的答案:") for i, chunk in enumerate(result.corpus.chunks, 1): print(f"{i}. {chunk.text}") # 清理 rag_engine.clear(corpus_id="hotpotqa_corpus") ``` -------------------------------- ### Install dependencies with pip Source: https://github.com/anative-lab/evoagentx/blob/main/Wonderful_workflow_corpus/README.md Install required Python packages from requirements.txt. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install EvoAgentX from GitHub Source: https://github.com/anative-lab/evoagentx/blob/main/docs/ColabNotebook/tutorial_notebooks/aflow_optimizer.ipynb Installs the EvoAgentX package directly from the GitHub repository. ```python !pip install git+https://github.com/EvoAgentX/EvoAgentX.git ``` -------------------------------- ### Run rag_tutorial.py Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/rag.md Runs the rag_tutorial.py script to execute the indexing and querying workflow. ```bash python rag_tutorial.py ``` -------------------------------- ### Install EvoAgentX optional feature sets Source: https://github.com/anative-lab/evoagentx/blob/main/docs/installation.md Installs additional optional features for EvoAgentX, such as RAG, tools, multimodal, optimizers, benchmarks, visualization, or all features. Each command installs a specific feature set. ```bash pip install "evoagentx[rag]" ``` ```bash pip install "evoagentx[tools]" ``` ```bash pip install "evoagentx[multimodal]" ``` ```bash pip install "evoagentx[optimizers]" ``` ```bash pip install "evoagentx[benchmarks]" ``` ```bash pip install "evoagentx[viz]" ``` ```bash pip install "evoagentx[all]" ``` -------------------------------- ### Create CustomizeAgent via direct initialization Source: https://github.com/anative-lab/evoagentx/blob/main/docs/ColabNotebook/tutorial_notebooks/first_agent.ipynb Creates a simple agent that prints 'hello world' by directly instantiating CustomizeAgent with a name, description, prompt, and LLM configuration. ```python first_agent = CustomizeAgent( name="FirstAgent", description="A simple agent that prints hello world", prompt="Print 'hello world'", llm_config=openai_config # specify the LLM configuration ) ``` -------------------------------- ### MCPToolkit initialization with config file or dictionary Source: https://github.com/anative-lab/evoagentx/blob/main/docs/ColabNotebook/tutorial_notebooks/tools.ipynb Shows two ways to initialize an MCPToolkit: with a configuration file path or with a configuration dictionary. The dictionary example defines a 'hirebase' MCP server using the 'uvx' command and an environment variable for the API key. ```python from evoagentx.tools import MCPToolkit # Initialize with a configuration file toolkit = MCPToolkit(config_path="examples/sample_mcp.config") # Or initialize with a configuration dictionary config = { "mcpServers": { "hirebase": { "command": "uvx", "args": ["hirebase-mcp"], "env": {"HIREBASE_API_KEY": "your_api_key_here"} } } } toolkit = MCPToolkit(config=config) ``` -------------------------------- ### Install EvoAgentX via pip Source: https://github.com/anative-lab/evoagentx/blob/main/README.md Install the EvoAgentX package from PyPI using pip. ```bash pip install evoagentx ``` -------------------------------- ### Install EvoAgentX using Conda environment Source: https://github.com/anative-lab/evoagentx/blob/main/docs/installation.md Creates a new Conda environment with Python 3.11, activates it, and installs the package dependencies. Includes options for installing with dev dependencies, optional features, or in development mode. ```bash # Create a new conda environment conda create -n evoagentx python=3.11 # Activate the environment conda activate evoagentx # Install the package dependencies pip install -e ".[dev]" # Or install with optional features pip install -e ".[dev,rag,tools]" # OR install in development mode pip install -e . ``` -------------------------------- ### NQ dataset example format Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/benchmark.md Format of each example in the NQ dataset. The answers field contains a list of possible ground-truth answers. ```json { "id": "test-1", "question": "the question", "answers": ["possible answers"] } ``` -------------------------------- ### Sample return from write_file tool Source: https://github.com/anative-lab/evoagentx/blob/main/docs/ColabNotebook/tutorial_notebooks/tools.ipynb Sample return dictionary from the write_file tool. Contains success flag, confirmation message, and the file path. ```python { "success": True, "message": "Content written to examples/output.txt", "file_path": "examples/output.txt" } ``` -------------------------------- ### FluxImageGenerationToolkit Usage Example Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Usage example for FluxImageGenerationToolkit: generates an image with specified parameters and edits an existing image by passing a base64-encoded input. ```python # Get the generation tool gen_tool = toolkit.get_tool("flux_image_generation_edit") # Generate an image result = gen_tool( prompt="A futuristic cyberpunk city with neon lights and flying cars", seed=42, output_format="jpeg", prompt_upsampling=False, safety_tolerance=2 ) # Edit an existing image import base64 with open("existing_image.jpg", "rb") as f: b64_image = base64.b64encode(f.read()).decode("utf-8") edit_result = gen_tool( prompt="Add a glowing red umbrella held by a person in the foreground", input_image=b64_image, seed=43, output_format="jpeg" ) ``` -------------------------------- ### Initialize RAGEngine with RAGConfig and StorageHandler Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/rag.md Sets up storage with SQLite and FAISS, configures RAG parameters (reader, chunker, embedding, index, retrieval), and initializes the RAGEngine. Requires environment variables like OPENAI_API_KEY for embeddings. ```python from evoagentx.rag.rag import RAGEngine from evoagentx.rag.rag_config import RAGConfig, ReaderConfig, ChunkerConfig, EmbeddingConfig, IndexConfig, RetrievalConfig from evoagentx.storages.base import StorageHandler from evoagentx.storages.storages_config import StoreConfig, VectorStoreConfig, DBConfig # Configure storage store_config = StoreConfig( dbConfig=DBConfig(db_name="sqlite", path="./data/cache.db"), vectorConfig=VectorStoreConfig(vector_name="faiss", dimensions=1536, index_type="flat_l2"), graphConfig=None, path="./data/indexing" ) storage_handler = StorageHandler(storageConfig=store_config) # Configure RAG rag_config = RAGConfig( reader=ReaderConfig(recursive=False, exclude_hidden=True), chunker=ChunkerConfig(strategy="simple", chunk_size=512, chunk_overlap=0), embedding=EmbeddingConfig(provider="openai", model_name="text-embedding-ada-002", api_key="your-api-key"), index=IndexConfig(index_type="vector"), retrieval=RetrievalConfig(retrivel_type="vector", postprocessor_type="simple", top_k=10, similarity_cutoff=0.3) ) # Initialize RAGEngine rag_engine = RAGEngine(config=rag_config, storage_handler=storage_handler) ``` -------------------------------- ### Verify EvoAgentX installation Source: https://github.com/anative-lab/evoagentx/blob/main/docs/installation.md Imports the evoagentx package and prints its version to confirm that the installation was successful. The expected output is the current version number. ```python import evoagentx # Print the version print(evoagentx.__version__) ``` -------------------------------- ### Create and run a simple CustomizeAgent Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/customize_agent.md Creates a minimal CustomizeAgent with a name, description, prompt, and input definition, then executes it and prints the raw response content. Requires an OPENAI_API_KEY environment variable and the evoagentx package. All input names in the inputs list must appear in the prompt, otherwise an error is raised. ```python import os from dotenv import load_dotenv from evoagentx.models import OpenAILLMConfig from evoagentx.agents import CustomizeAgent load_dotenv() OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") # Configure LLM openai_config = OpenAILLMConfig(model="gpt-4o-mini", openai_key=OPENAI_API_KEY) # Create a simple agent simple_agent = CustomizeAgent( name="SimpleAgent", description="A basic agent that responds to queries", prompt="Answer the following question: {question}", llm_config=openai_config, inputs=[ {"name": "question", "type": "string", "description": "The question to answer"} ] ) # Execute the agent response = simple_agent(inputs={"question": "What is a language model?"}) print(response.content.content) # Access the raw response content ``` -------------------------------- ### Install EvoAgentX via pip Source: https://github.com/anative-lab/evoagentx/blob/main/docs/installation.md Installs the latest version of EvoAgentX directly from the GitHub repository using pip. This is the recommended method for most users. ```bash pip install git+https://github.com/EvoAgentX/EvoAgentX.git ``` -------------------------------- ### Using MCP tools from MCPToolkit Source: https://github.com/anative-lab/evoagentx/blob/main/docs/ColabNotebook/tutorial_notebooks/tools.ipynb Shows how to retrieve tools from an MCPToolkit, find a specific tool by name, and invoke it with a query. The example searches for a tool containing 'hire' or 'search' in its name and then calls it with a search query. ```python # Get all tools from the toolkit tools = toolkit.get_toolkits() # Find a specific tool hirebase_tool = None for tool in tools: if "hire" in tool.name.lower() or "search" in tool.name.lower(): hirebase_tool = tool break if hirebase_tool: # Use the tool to search for information search_query = "data scientist" result = hirebase_tool(query=search_query) print(f"Search results for '{search_query}':") print(result) ``` -------------------------------- ### navigate_to_url: Sample Return and Usage Source: https://github.com/anative-lab/evoagentx/blob/main/docs/ColabNotebook/tutorial_notebooks/tools.ipynb Sample return and usage for the navigate_to_url method. Requires a complete URL with protocol; optional timeout parameter. ```python { "status": "success", "title": "Example Domain", "url": "https://example.com", "accessibility_tree": {...}, # Full page structure "page_content": "Example Domain\n\nThis domain is for use in illustrative examples...", "interactive_elements": [ { "id": "e0", "description": "More information.../link", "purpose": "link", "label": "More information...", "category": "navigation", "isPrimary": False, "visible": True, "interactable": True } ] } ``` ```python # Get and use the tool navigate_tool = toolkit.get_tool("navigate_to_url") result = navigate_tool(url="https://example.com") ``` -------------------------------- ### MBPP example format Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/benchmark.md Shows the format of each example in the MBPP dataset after conversion to the HumanEval format. The `task_id` is an integer (original MBPP task_id). Original MBPP attributes like "code" and "test_list" can be accessed via `example["code"]`. ```json { "task_id": 2, "prompt": "the prompt of the problem", "entry_point": "the name of the function to be tested", "canonical_solution": "the canonical solution of the problem", "test": "the unit tests of the problem" } ``` -------------------------------- ### HotPotQA dataset example format Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/benchmark.md Format of each example in the HotPotQA dataset. The second element (int) of a supporting_fact is the index of the sentence in the context that supports the answer. ```json { "_id": "the id of the example", "question": "the question", "answer": "the answer", "context": [["context_title", ["context_sentence", "another_sentence"]]], "supporting_facts": [["supporting_title", 0]] } ``` -------------------------------- ### Initialize MCPToolkit Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Initialize MCPToolkit either with a configuration file path or with a direct configuration dictionary specifying MCP servers. ```python from evoagentx.tools import MCPToolkit # Initialize with configuration file toolkit = MCPToolkit(config_path="path/to/mcp.config") # Or with direct configuration config = { "mcpServers": { "arxiv-server": { "command": "uv", "args": ["tool", "run", "arxiv-mcp-server"] } } } toolkit = MCPToolkit(config=config) ``` -------------------------------- ### OpenRouterImageToolkit Usage Example Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Usage example for OpenRouterImageToolkit: retrieves the generation and analysis tools, generates an image, edits it using the saved path, and analyzes the edited image. ```python # Get tools gen_tool = toolkit.get_tool("openrouter_image_generation_edit") analysis_tool = toolkit.get_tool("image_analysis") # Generate an image result = gen_tool( prompt="A minimalist poster of a mountain at sunrise", model="google/gemini-2.5-flash-image-preview", save_path="./openrouter_images", output_basename="mountain" ) # Edit the image edit_result = gen_tool( prompt="Add a bold 'GEMINI' text at the top", image_paths=[result["saved_paths"][0]], model="google/gemini-2.5-flash-image-preview", save_path="./openrouter_images", output_basename="edited" ) # Analyze the image analysis_result = analysis_tool( prompt="Describe this image", image_path=edit_result["saved_paths"][0] ) ``` -------------------------------- ### PostgreSQLToolkit Usage Example Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/tools.md Demonstrates using PostgreSQLToolkit tools to create a table, insert rows, query with a WHERE clause, and delete rows. The create tool accepts raw SQL and the find tool takes table name, where, columns, and sort parameters. ```python # Get tools execute_tool = toolkit.get_tool("postgresql_execute") find_tool = toolkit.get_tool("postgresql_find") create_tool = toolkit.get_tool("postgresql_create") delete_tool = toolkit.get_tool("postgresql_delete") # Create users table create_sql = """ CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, age INTEGER, department VARCHAR(50) ); """ result = create_tool(create_sql) # Insert users insert_sql = """ INSERT INTO users (name, email, age, department) VALUES ('Alice Johnson', 'alice@example.com', 28, 'Engineering'), ('Bob Smith', 'bob@example.com', 32, 'Marketing'), ('Carol Davis', 'carol@example.com', 25, 'Engineering') ON CONFLICT (email) DO NOTHING; """ result = execute_tool(insert_sql) # Query engineers find_result = find_tool( "users", where="department = 'Engineering'", columns="name, age", sort="age ASC" ) # Delete marketing users delete_result = delete_tool( "users", "department = 'Marketing'" ) ``` -------------------------------- ### Simple Prompt Template with StringTemplate Source: https://github.com/anative-lab/evoagentx/blob/main/docs/modules/customize_agent.md Creates a CustomizeAgent with a StringTemplate prompt that instructs the agent to print 'hello world'. The agent is invoked with no inputs and the response content is printed. ```python from evoagentx.prompts import StringTemplate agent = CustomizeAgent( name="FirstAgent", description="A simple agent that prints hello world", prompt_template=StringTemplate( instruction="Print 'hello world'", ), llm_config=openai_config ) message = agent() print(message.content.content) ``` -------------------------------- ### Initialize MCPToolkit and Get Toolkits Source: https://github.com/anative-lab/evoagentx/blob/main/docs/tutorial/mcp.md Initializes the MCPToolkit with a configuration file and retrieves all available toolkits from connected MCP servers. The get_toolkits() method returns a list of Toolkit objects. ```python # Initialize the MCP toolkit toolkit = MCPToolkit(config_path="examples/mcp.config") # Get all available toolkits (each toolkit contains multiple tools) toolkits = toolkit.get_toolkits() ```