### Install Dependencies and Setup Source: https://github.com/camel-ai/camel/blob/master/examples/usecases/chat_with_youtube/README.md Instructions for setting up the project environment, including cloning the repository, creating a virtual environment, installing Python dependencies, and configuring environment variables. ```bash git clone https://github.com/camel-ai/camel.git cd examples/usecases/chat_with_youtube python -m venv venv source venv/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Get Started: RolePlaying in Action Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/key_modules/societies.mdx An example demonstrating how to use the RolePlaying class to set up a turn-based multi-agent chat with custom roles and live output. ```APIDOC ## Get Started: RolePlaying in Action This example demonstrates a turn-based multi-agent chat with custom roles and live output colors. ### Method N/A (This is a usage example, not an API endpoint) ### Endpoint N/A ### Request Body N/A ### Request Example ```python from colorama import Fore from camel.societies import RolePlaying from camel.utils import print_text_animated def main(model=None, chat_turn_limit=50) -> None: # Initialize a session for developing a trading bot task_prompt = "Develop a trading bot for the stock market" role_play_session = RolePlaying( assistant_role_name="Python Programmer", assistant_agent_kwargs=dict(model=model), user_role_name="Stock Trader", user_agent_kwargs=dict(model=model), task_prompt=task_prompt, with_task_specify=True, task_specify_agent_kwargs=dict(model=model), ) # Print initial system messages print( Fore.GREEN + f"AI Assistant sys message:\n{role_play_session.assistant_sys_msg}\n" ) print( Fore.BLUE + f"AI User sys message:\n{role_play_session.user_sys_msg}\n" ) print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n") print( Fore.CYAN + "Specified task prompt:" + f"\n{role_play_session.specified_task_prompt}\n" ) print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n") n = 0 input_msg = role_play_session.init_chat() # Turn-based simulation while n < chat_turn_limit: n += 1 assistant_response, user_response = role_play_session.step(input_msg) if assistant_response.terminated: print( Fore.GREEN + ( "AI Assistant terminated. Reason: " f"{assistant_response.info['termination_reasons']}." ) ) break if user_response.terminated: print( Fore.GREEN + ( "AI User terminated. " f"Reason: {user_response.info['termination_reasons']}." ) ) break print_text_animated( Fore.BLUE + f"AI User:\n\n{user_response.msg.content}\n" ) print_text_animated( Fore.GREEN + "AI Assistant:\n\n" f"{assistant_response.msg.content}\n" ) if "CAMEL_TASK_DONE" in user_response.msg.content: break input_msg = assistant_response.msg if __name__ == "__main__": main() ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Install and Start MCP Filesystem Server Source: https://github.com/camel-ai/camel/blob/master/docs/mcp/connecting_existing_mcp_tools.md Commands to install the official MCP filesystem server globally via npm and start it to expose a specific directory. ```bash npm install -g @modelcontextprotocol/server-filesystem npx -y @modelcontextprotocol/server-filesystem . ``` -------------------------------- ### Install Dependencies Source: https://github.com/camel-ai/camel/blob/master/CONTRIBUTING.md Commands to install all necessary dependencies for running the package, examples, linting, formatting, tests, and coverage. Ensures the project environment is correctly set up. ```bash pip install -e "[dev,test,lint,format,test,coverage]" ``` -------------------------------- ### Self-Instruct Generation - Quick Start Source: https://github.com/camel-ai/camel/blob/master/docs/key_modules/datagen.md This example demonstrates how to quickly set up and run the Self-Instruct generation pipeline using default settings. It initializes a ChatAgent, creates a SelfInstructPipeline with a seed file and specified number of machine instructions, and then generates the instructions. ```APIDOC ## Self-Instruct Generation - Quick Start ### Description Quickly set up an instruction generation pipeline with both human and machine prompts. ### Method N/A (Python Script) ### Endpoint N/A (Python Script) ### Parameters N/A (Python Script) ### Request Example ```python from camel.agents import ChatAgent from camel.datagen.self_instruct import SelfInstructPipeline # Initialize agent agent = ChatAgent() # Create pipeline with default settings pipeline = SelfInstructPipeline( agent=agent, seed='seed_tasks.jsonl', # Path to human-written seed tasks num_machine_instructions=5, data_output_path='./data_output.json', human_to_machine_ratio=(6, 2) ) # Generate instructions pipeline.generate() ``` ### Response N/A (Python Script output to file) ### Response Example N/A (Python Script output to file) ``` -------------------------------- ### Setup Initial Environment with uv Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/reference/camel.toolkits.terminal_toolkit.mdx Configures the initial environment specifically using 'uv' for package management and environment setup. This leverages 'uv's speed for a more efficient setup process. ```python def _setup_initial_env_with_uv(self): """Set up initial environment using uv.""" ``` -------------------------------- ### Setup Local Jupyter Runtime Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/cookbooks/applications/customer_service_Discord_bot_using_local_model_with_agentic_RAG.mdx Commands to install and launch a local Jupyter notebook server configured to allow connections from Google Colab. ```bash pip install notebook jupyter notebook --NotebookApp.allow_origin='https://colab.research.google.com' --port=8888 --no-browser ``` -------------------------------- ### Usage Examples Source: https://github.com/camel-ai/camel/blob/master/services/README.md Examples demonstrating how to use the `step` tool and other resources provided by the CAMEL Agent MCP Server. ```APIDOC ## Usage Examples ### Description These examples illustrate how to interact with the CAMEL Agent MCP Server using its provided tools and resources. ### Using the Step Tool Execute a single conversation step with an agent: ```python # Example of using the step tool response = await step( name="search", message="What is the latest news about artificial intelligence?", ctx=context ) ``` ### Using Resources Retrieve information about agents and their chat history: ```python # Get information about available agents agent_info = await get_agents_info() # Get chat history for a specific agent history = await get_chat_history(name="general") ``` ``` -------------------------------- ### Environment and Dependency Setup Source: https://github.com/camel-ai/camel/blob/master/examples/usecases/chat_with_github/README.md Commands to initialize the Python virtual environment and install necessary MCP plugins. This ensures the project dependencies are isolated and the git MCP server is globally available. ```bash python -m venv venv source venv/bin/activate pip install -r requirements.txt npm install -g @openbnb/mcp-server-git ``` -------------------------------- ### Example User Query for ACIToolkit Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/cookbooks/mcp/camel_aci_mcp_cookbook.mdx An example of a user query to be used with the ACIToolkit method, demonstrating a request to create a GitHub repository with a README file. ```bash "Create a GitHub repository named 'my-aci-toolkit-demo' and add a README.md file with the content '# ACI Toolkit Demo'." ``` -------------------------------- ### Get Started: RolePlaying in Action Source: https://github.com/camel-ai/camel/blob/master/docs/key_modules/societies.md Example of turn-based multi-agent chat with custom roles and live output colors. ```python from colorama import Fore from camel.societies import RolePlaying from camel.utils import print_text_animated def main(model=None, chat_turn_limit=50) -> None: # Initialize a session for developing a trading bot task_prompt = "Develop a trading bot for the stock market" role_play_session = RolePlaying( assistant_role_name="Python Programmer", assistant_agent_kwargs=dict(model=model), user_role_name="Stock Trader", user_agent_kwargs=dict(model=model), task_prompt=task_prompt, with_task_specify=True, task_specify_agent_kwargs=dict(model=model), ) # Print initial system messages print( Fore.GREEN + f"AI Assistant sys message:\n{role_play_session.assistant_sys_msg}\n" ) print( Fore.BLUE + f"AI User sys message:\n{role_play_session.user_sys_msg}\n" ) print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n") print( Fore.CYAN + "Specified task prompt:" + f"\n{role_play_session.specified_task_prompt}\n" ) print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n") n = 0 input_msg = role_play_session.init_chat() # Turn-based simulation while n < chat_turn_limit: n += 1 assistant_response, user_response = role_play_session.step(input_msg) if assistant_response.terminated: print( Fore.GREEN + ( "AI Assistant terminated. Reason: " f"{assistant_response.info['termination_reasons']}." ) ) break if user_response.terminated: print( Fore.GREEN + ( "AI User terminated. " f"Reason: {user_response.info['termination_reasons']}." ) ) break print_text_animated( Fore.BLUE + f"AI User:\n\n{user_response.msg.content}\n" ) print_text_animated( Fore.GREEN + "AI Assistant:\n\n" f"{assistant_response.msg.content}\n" ) if "CAMEL_TASK_DONE" in user_response.msg.content: break input_msg = assistant_response.msg if __name__ == "__main__": main() ``` -------------------------------- ### Run Workforce Example Script Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/get_started/installation.mdx Command to execute the workforce example script, demonstrating multi-agent collaboration at scale. ```bash python examples/workforce/multiple_single_agents.py ``` -------------------------------- ### Build Documentation Locally with Mintlify Source: https://github.com/camel-ai/camel/blob/master/CONTRIBUTING.md Instructions for installing the Mintlify CLI and running the development server to preview documentation changes locally. This facilitates contributing to the project's documentation. ```bash npm install -g mintlify ``` ```bash mintlify dev ``` -------------------------------- ### Run AutoRetriever with Default Settings Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/cookbooks/advanced_features/agents_with_rag.mdx Demonstrates how to initialize the AutoRetriever with Qdrant storage and execute a vector retrieval query using local files or remote URLs as content sources. ```python from camel.retrievers import AutoRetriever from camel.types import StorageType auto_retriever = AutoRetriever( vector_storage_local_path="local_data2/", storage_type=StorageType.QDRANT, embedding_model=embedding_instance) retrieved_info = auto_retriever.run_vector_retriever( query="If I'm interest in contributing to the CAMEL project, what should I do?", contents=[ "local_data/camel_paper.pdf", "https://github.com/camel-ai/camel/wiki/Contributing-Guidlines", ], top_k=1, return_detailed_info=True, similarity_threshold=0.5 ) print(retrieved_info) ``` -------------------------------- ### Install Camel Package Source: https://github.com/camel-ai/camel/blob/master/docs/cookbooks/loong/single_step_env.ipynb Installs the required CAMEL package version for environment setup. ```bash %pip install camel-ai[all]==0.2.46 ``` -------------------------------- ### Install CAMEL Package Source: https://github.com/camel-ai/camel/blob/master/docs/cookbooks/advanced_features/agent_generate_structured_output.ipynb Installs the CAMEL package with all its dependencies. This is a prerequisite for running the examples. ```python ! ``` -------------------------------- ### Setup Initial Environment with UV Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/reference/camel.toolkits.terminal_toolkit.utils.mdx Sets up an initial Python environment using uv at the specified environment path. It requires the path to uv, a working directory, and an optional update callback. ```python def setup_initial_env_with_uv( env_path: str, uv_path: str, working_dir: str, update_callback = None ): pass ``` -------------------------------- ### Install CAMEL AI Package Source: https://github.com/camel-ai/camel/blob/master/docs/cookbooks/applications/customer_service_Discord_bot_using_Cohere_model_with_agentic_RAG.ipynb Installs the CAMEL AI package with all dependencies, along with starlette and nest_asyncio. This is the initial setup step for the project. ```python !pip install "camel-ai[all]==0.2.16" !pip install starlette !pip install nest_asyncio ``` -------------------------------- ### Initialize and Run DiscordApp Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/reference/camel.bots.discord.discord_app.mdx Demonstrates how to instantiate the DiscordApp class with specific channel restrictions and authentication tokens, and how to start the bot's event loop. ```python from camel.bots.discord.discord_app import DiscordApp # Initialize the bot bot = DiscordApp(channel_ids=[123456789], token="YOUR_DISCORD_TOKEN") # Start the bot bot.run() ``` -------------------------------- ### Install CAMEL-AI and Dependencies Source: https://github.com/camel-ai/camel/blob/master/examples/usecases/aci_mcp/README.md Installs the CAMEL-AI framework and necessary dependencies, including 'aci-mcp', using uv pip. This command ensures all required packages are available for the ACI integration examples. ```bash uv pip install camel-ai[all]==0.2.61 rich aci-mcp ``` -------------------------------- ### generate_structured_prompt Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/reference/camel.societies.workforce.structured_output_handler.mdx Generates a prompt that guides agents to produce output conforming to a specified Pydantic schema, optionally including examples and additional instructions. ```APIDOC ## POST /api/generate_structured_prompt ### Description Generate a prompt that guides agents to produce structured output based on a given schema and base prompt. ### Method POST ### Endpoint /api/generate_structured_prompt ### Parameters #### Request Body - **base_prompt** (str) - Required - The base prompt content. - **schema** (Type[BaseModel]) - Required - The Pydantic model schema for the expected output. - **examples** (Optional[List[Dict[str, Any]]]) - Optional - Optional examples of valid output. - **additional_instructions** (Optional[str]) - Optional - Additional instructions for output formatting. ### Request Example ```json { "base_prompt": "Please provide information about the user.", "schema": "UserSchema", "examples": [ { "name": "John Doe", "age": 30 } ], "additional_instructions": "Ensure the output is a valid JSON object." } ``` ### Response #### Success Response (200) - **prompt** (str) - The generated prompt with structured output instructions. #### Response Example ```json { "prompt": "Please provide information about the user. The output must be a JSON object conforming to the UserSchema. Example: {\"name\": \"John Doe\", \"age\": 30}. Ensure the output is a valid JSON object." } ``` ``` -------------------------------- ### Troubleshooting: Browser Start Issues in Python Source: https://github.com/camel-ai/camel/blob/master/docs/key_modules/browsertoolkit.md Provides a solution for troubleshooting browser startup failures in Python mode. It suggests installing Playwright dependencies. ```bash playwright install chromium ``` -------------------------------- ### Quick Start: Initialize and Run Self-Improving CoT Pipeline Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/key_modules/datagen.mdx Demonstrates how to quickly set up and execute the SelfImprovingCoTPipeline using ChatAgent for reasoning and evaluation. It outlines the initialization of agents, preparation of problems, and the pipeline execution to generate improved reasoning traces. The output is saved to a JSON file. ```python from camel.agents import ChatAgent from camel.datagen import SelfImprovingCoTPipeline # Initialize agents reason_agent = ChatAgent( """Answer my question and give your final answer within \boxed{}.""" ) evaluate_agent = ChatAgent( "You are a highly critical teacher who evaluates the student's answers with a meticulous and demanding approach." ) # Prepare your problems problems = [ {"problem": "Your problem text here"}, # Add more problems... ] # Create and run the pipeline pipeline = SelfImprovingCoTPipeline( reason_agent=reason_agent, evaluate_agent=evaluate_agent, problems=problems, max_iterations=3, output_path="star_output.json" ) results = pipeline.generate() ``` -------------------------------- ### Clone CAMEL Repository Source: https://github.com/camel-ai/camel/blob/master/examples/usecases/multi_agent_research_assistant/README.md Clones the CAMEL AI repository and navigates into the multi-agent research assistant example directory. This is the first step to get the project code. ```bash git clone https://github.com/camel-ai/camel.git cd camel/examples/usecases/multi_agent_research_assistant ``` -------------------------------- ### Get Earnings Calendar (Python) Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/reference/camel.toolkits.openbb_toolkit.mdx Retrieves a company earnings calendar, allowing filtering by start and end dates. This is useful for tracking upcoming earnings announcements. ```python def get_earnings_calendar( self, start_date: Optional[str] = None, end_date: Optional[str] = None ): """Get company earnings calendar with filtering and sorting options.""" pass ``` -------------------------------- ### Setup Initial Environment with Venv Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/reference/camel.toolkits.terminal_toolkit.utils.mdx Sets up an initial Python environment using the standard venv module. It requires the environment path, working directory, and an optional update callback. ```python def setup_initial_env_with_venv(env_path: str, working_dir: str, update_callback = None): pass ``` -------------------------------- ### Run CAMEL AI Examples (Bash) Source: https://github.com/camel-ai/camel/blob/master/docs/get_started/installation.md Demonstrates how to run various example scripts included with CAMEL, showcasing functionalities like role-playing agents, tool usage, knowledge graph generation, and multi-agent collaboration. ```bash # Two agents role-playing and collaborating python examples/ai_society/role_playing.py # Agent utilizing code execution tools python examples/toolkits/code_execution_toolkit.py # Generating knowledge graphs with agents python examples/knowledge_graph/knowledge_graph_agent_example.py # Multiple agents collaborating on complex tasks python examples/workforce/multiple_single_agents.py # Creative image generation with agents python examples/vision/image_crafting.py ``` -------------------------------- ### Generate Structured Prompts Source: https://github.com/camel-ai/camel/blob/master/docs/reference/camel.societies.workforce.structured_output_handler.md Creates a prompt enhanced with instructions for structured output based on a Pydantic model. It accepts base prompts, schemas, and optional examples to guide the agent. ```python def generate_structured_prompt(base_prompt: str, schema: Type[BaseModel], examples: Optional[List[Dict[str, Any]]] = None, additional_instructions: Optional[str] = None): # Implementation logic for prompt generation ``` -------------------------------- ### Set Up API Keys Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/get_started/installation.mdx Configures API credentials for various providers across different operating systems and shell environments, including a recommended .env file approach. ```bash export OPENAI_API_KEY= export OPENAI_API_BASE_URL= ``` ```cmd set OPENAI_API_KEY= set OPENAI_API_BASE_URL= ``` ```powershell $env:OPENAI_API_KEY="" $env:OPENAI_API_BASE_URL="" ``` ```bash OPENAI_API_KEY= ANTHROPIC_API_KEY= GOOGLE_API_KEY= ``` ```python from dotenv import load_dotenv load_dotenv() ``` -------------------------------- ### Configure and Run SFTTrainer Source: https://github.com/camel-ai/camel/blob/master/docs/cookbooks/data_generation/sft_data_generation_and_unsloth_finetuning_mistral_7b_instruct.ipynb Initializes the SFTTrainer with specific training arguments, including packing for efficiency and hardware-specific optimizations. It also demonstrates how to initiate the training process. ```python from trl import SFTTrainer from transformers import TrainingArguments from unsloth import is_bfloat16_supported trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset, dataset_text_field = "text", max_seq_length = 1024, dataset_num_proc = 2, packing = True, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_steps = 5, num_train_epochs = 20, learning_rate = 0.001, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 1, optim = "adamw_8bit", weight_decay = 0.01, lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", ), ) model = FastLanguageModel.for_training(model) trainer_stats = trainer.train() ``` -------------------------------- ### Use BaseMessage with ChatAgent Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/cookbooks/basic_concepts/agents_message.mdx Shows a practical example of using BaseMessage with ChatAgent. It includes fetching an image, creating system and user messages (with the image attached), and sending them to the agent to get a response. ```python from io import BytesIO import requests from PIL import Image from camel.agents import ChatAgent from camel.messages import BaseMessage # URL of the image url = "https://raw.githubusercontent.com/camel-ai/camel/master/misc/logo_light.png" response = requests.get(url) img = Image.open(BytesIO(response.content)) # Define system message sys_msg = BaseMessage.make_assistant_message( role_name="Assistant", content="You are a helpful assistant.", ) # Set agent camel_agent = ChatAgent(system_message=sys_msg) # Set user message user_msg = BaseMessage.make_user_message( role_name="User", content="""what's in the image?""", image_list=[img] ) # Get response information response = camel_agent.step(user_msg) print(response.msgs[0].content) ``` -------------------------------- ### POST /planning_enter_plan_mode Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/reference/camel.toolkits.planning_worktree_toolkit.mdx Initializes the toolkit into plan mode, creating or accessing the designated plan file. ```APIDOC ## POST /planning_enter_plan_mode ### Description Initializes the toolkit into plan mode. It sets up the environment to track tasks in a markdown plan file. ### Method POST ### Endpoint /planning_enter_plan_mode ### Response #### Success Response (200) - **status** (string) - Plan mode status - **plan_file_path** (string) - Path to the active plan file #### Response Example { "status": "active", "plan_file_path": "/path/to/.camel-plan.md" } ``` -------------------------------- ### Creating and Consuming a Simple REST API with Flask (Python) Source: https://github.com/camel-ai/camel/blob/master/docs/cookbooks/applications/finance_discord_bot.ipynb This snippet demonstrates the creation of a basic RESTful API using the Flask framework in Python. It includes defining endpoints for GET and POST requests. Requires Flask to be installed (`pip install Flask`). ```python from flask import Flask, request, jsonify app = Flask(__name__) # In-memory data store items = [] @app.route('/items', methods=['GET']) def get_items(): return jsonify(items) @app.route('/items', methods=['POST']) def add_item(): new_item = request.get_json() if new_item: items.append(new_item) return jsonify({"message": "Item added successfully"}), 201 return jsonify({"error": "Invalid input"}), 400 if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Using Built-in Toolkits Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/key_modules/tools.mdx Shows how to instantiate and use built-in toolkits, such as the SearchToolkit, and retrieve available tools. ```python from camel.toolkits import SearchToolkit toolkit = SearchToolkit() tools = toolkit.get_tools() ``` -------------------------------- ### Get Historical Market Data (Python) Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/reference/camel.toolkits.openbb_toolkit.mdx Retrieves historical market data for a specified symbol, asset type, and date range. Supports various data providers and intervals, with options for custom start and end dates. ```python def get_historical_data( self, symbol: str, provider: Literal['fmp', 'polygon', 'tiingo', 'yfinance'] = 'fmp', asset_type: Literal['equity', 'currency', 'crypto'] = 'equity', start_date: Optional[str] = None, end_date: Optional[str] = None, interval: Literal['1m', '5m', '15m', '30m', '1h', '4h', '1d'] = '1d' ): """Retrieves historical market data from OpenBB Platform providers.""" pass ``` -------------------------------- ### Generate Structured Prompt Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/reference/camel.societies.workforce.structured_output_handler.mdx Generates a prompt that guides AI agents to produce output conforming to a specified Pydantic schema. It can include base prompt content, schema definition, optional examples, and additional instructions for formatting. ```python def generate_structured_prompt( base_prompt: str, schema: Type[BaseModel], examples: Optional[List[Dict[str, Any]]] = None, additional_instructions: Optional[str] = None ): """Generate a prompt that guides agents to produce structured output. **Parameters:** - **base_prompt** (str): The base prompt content. - **schema** (Type[BaseModel]): The Pydantic model schema for the expected output. - **examples** (Optional[List[Dict[str, Any]]]): Optional examples of valid output. - **additional_instructions** (Optional[str]): Additional instructions for output formatting. **Returns:** str: The enhanced prompt with structured output instructions. """ ``` -------------------------------- ### Set up ChatAgent with OpenBB and Date Tools (Python) Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/cookbooks/applications/finance_discord_bot.mdx This snippet defines the system prompt for a ChatAgent, incorporating instructions for financial data retrieval using OpenBB and accurate date handling. It then initializes the agent with the specified prompt, the OpenBB toolkit, and a custom date tool. ```python from camel.agents import ChatAgent from camel.messages import BaseMessage from camel.toolkits import OpenBBToolkit, FunctionTool from datetime import date OPENBB_AGENT_SYSTEM_PROMPT = """ You are a helpful assistant providing detailed financial data, including stocks, coins, and similar assets, using OpenBB tools and the date tool. Role: - Deliver accurate, data-driven responses about financial assets using structured ASCII tables. Objective: 1. Answer asset-specific queries concisely and professionally. 2. Always display the current date prominently and interpret relative dates accurately. 3. Use ASCII tables for all data summaries. Instructions: 1. Input Validation: - Confirm the query is specific to an asset (e.g., stock, coin, or similar). - If unclear, request clarification (e.g., "Could you specify which asset you're referring to?"). 2. Date Awareness: - Dynamically fetch and display the current date for context in all responses. - Interpret relative dates (e.g., "yesterday," "last week") accurately: - "Yesterday": Subtract one day from the current date. - "Last week": Provide the range for the previous 7 days from the current date. - Ensure the calculated date or date range is clearly displayed. 3. Symbol Handling: - Extract the ticker symbol or lookup based on the asset name. - Correct misspellings or broaden the search scope if necessary. 4. Information Retrieval: - Fetch key metrics (e.g., PE ratio, market cap, price trends, trading volume) using the tools in the OpenBB toolkit. - If no data could be retrieved using the OpenBB tools, kindly inform the user. - Avoid reliance on FMP for data. 5. Response Composition: - Use a professional tone and concise formatting. - Represent all data in clean ASCII tables with proper alignment and headers. Output Guidelines: 1. Enhanced ASCII Table Format: Example: ``` +--------+-------------------+--------+-----------+----------+-------------+ | Symbol | Asset | Price | Change ($)| % Change | Volume | +--------+-------------------+--------+-----------+----------+-------------+ | MSFT | Microsoft Stock | $320.11| -$3.25 | -1.01% | 19,000,000 | | BTC | Bitcoin | $28,550| +$150 | +0.53% | 22,000 BTC | +--------+-------------------+--------+-----------+----------+-------------+ ``` 2. Current Date and Context: - Prominently include the current date or inferred relative date in all responses: - Example: *Query:* "Show data for yesterday." *Response:* "The data for 2025-01-21 (yesterday) is as follows:" By following these enhanced instructions, provide clear, accurate, and professional financial data summaries for stocks, coins, and similar assets without graphical visualizations, while incorporating dynamic date awareness. """ # Define the date tool def get_today_date(): r"""Get the date of today.""" return date.today() # Set up tools to be used openbb_toolkit = OpenBBToolkit() openbb_tools = openbb_toolkit.get_tools() date_tool = [FunctionTool(get_today_date)] # Set up ChatAgent with defined prompt and tools openbb_agent = ChatAgent( system_message=OPENBB_AGENT_SYSTEM_PROMPT, model=qwen_model, tools=openbb_tools + date_tool ) ``` -------------------------------- ### Sending an HTTP GET Request with Requests Library (Python) Source: https://github.com/camel-ai/camel/blob/master/docs/cookbooks/applications/finance_discord_bot.ipynb This code shows how to send an HTTP GET request to a specified URL using the popular `requests` library in Python. It retrieves and prints the JSON response from the API. Requires the `requests` library (`pip install requests`). ```python import requests url = "https://jsonplaceholder.typicode.com/posts/1" try: response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) data = response.json() print("GET Request Successful:") print(data) except requests.exceptions.RequestException as e: print(f"Error making GET request: {e}") ``` -------------------------------- ### Initialize Local Development Environment Source: https://github.com/camel-ai/camel/blob/master/docs/cookbooks/data_generation/sft_data_generation_and_unsloth_finetuning_tinyllama.ipynb Commands to clone the repository and install necessary project dependencies using the poetry package manager. ```bash git clone poetry install ``` -------------------------------- ### Run Direct ACI Toolkit Integration Example Source: https://github.com/camel-ai/camel/blob/master/examples/usecases/aci_mcp/README.md Executes the Python script for direct integration of the ACI toolkit with CAMEL-AI. This approach offers a simpler setup and immediate access to ACI.dev tools, providing rich console output. ```bash python aci_toolkit_camel.py ``` -------------------------------- ### Initialize ChatAgent with Tools Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/cookbooks/basic_concepts/create_your_first_agent.mdx Demonstrates how to initialize a ChatAgent with MathToolkit and SearchToolkit. It shows how to get tools from toolkits and pass them to the agent for use in its responses. ```python from camel.toolkits import MathToolkit, SearchToolkit from camel.agents import ChatAgent sys_msg = "You are a helpful assistant." agent = ChatAgent( system_message=sys_msg, tools = [ *MathToolkit().get_tools(), *SearchToolkit().get_tools(), ] ) response = agent.step("What is CAMEL AI?") print(response.info['tool_calls']) print(response.msgs[0].content) ``` -------------------------------- ### Making an Asynchronous HTTP GET Request with Fetch API (JavaScript) Source: https://github.com/camel-ai/camel/blob/master/docs/cookbooks/applications/finance_discord_bot.ipynb This example demonstrates how to make an asynchronous HTTP GET request using the built-in `fetch` API in JavaScript. It handles the response using Promises and logs the JSON data. This is commonly used for interacting with web services. ```javascript const apiUrl = 'https://jsonplaceholder.typicode.com/todos/1'; fetch(apiUrl) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => { console.log('Fetch GET request successful:'); console.log(data); }) .catch(error => { console.error('Error fetching data:', error); }); ``` -------------------------------- ### Configure and Connect to MCP Servers Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/cookbooks/advanced_features/agents_with_MCP.mdx Shows how to initialize an MCPToolkit using a JSON configuration file and integrate it into a CAMEL agent for asynchronous tool execution. ```json { "mcpServers": { "time": { "command": "uvx", "args": ["mcp-server-time", "--local-timezone=Asia/Riyadh"] } } } ``` ```python import asyncio from camel.toolkits.mcp_toolkit import MCPToolkit async def run_time_example(): mcp_toolkit = MCPToolkit(config_path="config/time.json") await mcp_toolkit.connect() camel_agent = ChatAgent(model=model, tools=[*mcp_toolkit.get_tools()]) response = await camel_agent.astep("What time is it now?") print(response.msgs[0].content) await mcp_toolkit.disconnect() ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/camel-ai/camel/wiki/Contributing-Guidlines Commands to build the project documentation using Sphinx and Make. ```bash cd docs make html ``` -------------------------------- ### Get All GitHub File Paths (Python) Source: https://github.com/camel-ai/camel/blob/master/docs/reference/camel.toolkits.github_toolkit.md Recursively retrieves all file paths within a specified GitHub repository or a subdirectory. It accepts the repository name and an optional path to start traversal from. The function returns a list of strings, where each string is a file path. ```python def github_get_all_file_paths(self, repo_name: str, path: str = ''): """Recursively retrieves all file paths in the GitHub repository.""" pass ``` -------------------------------- ### Running Benchmark Evaluations in Python Source: https://github.com/camel-ai/camel/blob/master/docs/key_modules/Benchmark.md This snippet demonstrates the standard workflow for initializing a benchmark, loading data, configuring a ChatAgent, and executing an evaluation. It outputs summary metrics and detailed per-example results. ```python from camel.benchmarks import from camel.agents import ChatAgent # 1. Initialize benchmark = ( data_dir="./data", save_to="./results.json", processes=4 ) # 2. Load data benchmark.load(force_download=False) # 3. Create agent agent = ChatAgent(...) # 4. Run evaluation results = benchmark.run( agent=agent, randomize=False, subset=None ) # 5. Access results print(results) print(benchmark.results) ``` -------------------------------- ### Initialize and Use HybridBrowserToolkit Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/key_modules/browsertoolkit.mdx Demonstrates how to instantiate the HybridBrowserToolkit, attach it to a ChatAgent, and execute a web navigation task. This example uses the asynchronous pattern required for browser operations. ```python import asyncio from camel.agents import ChatAgent from camel.models import ModelFactory from camel.toolkits import HybridBrowserToolkit from camel.types import ModelPlatformType, ModelType async def main(): toolkit = HybridBrowserToolkit(headless=False) model = ModelFactory.create( model_platform=ModelPlatformType.OPENAI, model_type=ModelType.GPT_4O, ) agent = ChatAgent(model=model, tools=toolkit.get_tools()) response = await agent.astep("Go to google.com and search for 'CAMEL AI framework'") print(response.msgs[0].content) await toolkit.browser_close() asyncio.run(main()) ``` -------------------------------- ### Setup Ollama Local Model Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/cookbooks/applications/customer_service_Discord_bot_using_local_model_with_agentic_RAG.mdx This section details how to set up a local AI model using Ollama. It includes pulling a base model, creating a custom model with a ModelFile, and a shell script to automate the creation process. Dependencies include Ollama installation. ```bash ollama pull qwq cd FROM qwq # Set parameters PARAMETER temperature 0.8 PARAMETER stop Result # Sets a custom system message to specify the behavior of the chat assistant # Leaving it blank for now. SYSTEM "" "" #!/bin/zsh # variables model_name="qwq" custom_model_name="camel-qwq" #get the base model ollama pull $model_name #create the model file ollama create $custom_model_name -f ./ModelFile ``` -------------------------------- ### Initialize WebDeployToolkit Source: https://github.com/camel-ai/camel/blob/master/docs/mintlify/reference/camel.toolkits.web_deploy_toolkit.mdx Configures the toolkit with deployment settings, including branding, server location, and timeout parameters. ```APIDOC ## POST /WebDeployToolkit/__init__ ### Description Initializes the WebDeployToolkit instance with specific configuration for server deployment and branding. ### Method POST ### Endpoint /WebDeployToolkit/__init__ ### Parameters #### Request Body - **timeout** (float) - Optional - Command timeout in seconds. - **add_branding_tag** (bool) - Optional - Whether to add brand tag to deployed pages. Default: True. - **logo_path** (str) - Optional - Path to custom logo file. Default: '../camel/misc/favicon.png'. - **tag_text** (str) - Optional - Text to display in the tag. Default: 'Created by CAMEL'. - **tag_url** (str) - Optional - URL to open when tag is clicked. - **remote_server_ip** (str) - Optional - Remote server IP for deployment. - **remote_server_port** (int) - Optional - Remote server port. Default: 8080. ### Request Example { "timeout": 30.0, "add_branding_tag": true, "remote_server_port": 8080 } ### Response #### Success Response (200) - **status** (string) - Confirmation of successful initialization. ``` -------------------------------- ### Get Current Time in Go Source: https://github.com/camel-ai/camel/blob/master/docs/cookbooks/applications/finance_discord_bot.ipynb This Go function returns the current local time as a `time.Time` object. It uses `time.Now()`. This is the starting point for most time-related operations. ```Go func GetCurrentTime() time.Time { return time.Now() } ```