{"repo_name": "owl", "file_name": "/owl/owl/webapp.py", "inference_info": {"prefix_code": "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Import from the correct module path\nfrom utils import run_society\nimport os\nimport gradio as gr\nimport time\nimport json\nimport logging\nimport datetime\nfrom typing import Tuple\nimport importlib\nfrom dotenv import load_dotenv, set_key, find_dotenv, unset_key\nimport threading\nimport queue\nimport re\n\nos.environ[\"PYTHONIOENCODING\"] = \"utf-8\"\n\n\n# Configure logging system\ndef setup_logging():\n \"\"\"Configure logging system to output logs to file, memory queue, and console\"\"\"\n # Create logs directory (if it doesn't exist)\n logs_dir = os.path.join(os.path.dirname(__file__), \"logs\")\n os.makedirs(logs_dir, exist_ok=True)\n\n # Generate log filename (using current date)\n current_date = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n log_file = os.path.join(logs_dir, f\"gradio_log_{current_date}.txt\")\n\n # Configure root logger (captures all logs)\n root_logger = logging.getLogger()\n\n # Clear existing handlers to avoid duplicate logs\n for handler in root_logger.handlers[:]:\n root_logger.removeHandler(handler)\n\n root_logger.setLevel(logging.INFO)\n\n # Create file handler\n file_handler = logging.FileHandler(log_file, encoding=\"utf-8\", mode=\"a\")\n file_handler.setLevel(logging.INFO)\n\n # Create console handler\n console_handler = logging.StreamHandler()\n console_handler.setLevel(logging.INFO)\n\n # Create formatter\n formatter = logging.Formatter(\n \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n )\n file_handler.setFormatter(formatter)\n console_handler.setFormatter(formatter)\n\n # Add handlers to root logger\n root_logger.addHandler(file_handler)\n root_logger.addHandler(console_handler)\n\n logging.info(\"Logging system initialized, log file: %s\", log_file)\n return log_file\n\n\n# Global variables\nLOG_FILE = None\nLOG_QUEUE: queue.Queue = queue.Queue() # Log queue\nSTOP_LOG_THREAD = threading.Event()\nCURRENT_PROCESS = None # Used to track the currently running process\nSTOP_REQUESTED = threading.Event() # Used to mark if stop was requested\n\n\n# Log reading and updating functions\ndef log_reader_thread(log_file):\n \"\"\"Background thread that continuously reads the log file and adds new lines to the queue\"\"\"\n try:\n with open(log_file, \"r\", encoding=\"utf-8\") as f:\n # Move to the end of file\n f.seek(0, 2)\n\n while not STOP_LOG_THREAD.is_set():\n line = f.readline()\n if line:\n LOG_QUEUE.put(line) # Add to conversation record queue\n else:\n # No new lines, wait for a short time\n time.sleep(0.1)\n except Exception as e:\n logging.error(f\"Log reader thread error: {str(e)}\")\n\n\ndef get_latest_logs(max_lines=100, queue_source=None):\n \"\"\"Get the latest log lines from the queue, or read directly from the file if the queue is empty\n\n Args:\n max_lines: Maximum number of lines to return\n queue_source: Specify which queue to use, default is LOG_QUEUE\n\n Returns:\n str: Log content\n \"\"\"\n logs = []\n log_queue = queue_source if queue_source else LOG_QUEUE\n\n # Create a temporary queue to store logs so we can process them without removing them from the original queue\n temp_queue = queue.Queue()\n temp_logs = []\n\n try:\n # Try to get all available log lines from the queue\n while not log_queue.empty() and len(temp_logs) < max_lines:\n log = log_queue.get_nowait()\n temp_logs.append(log)\n temp_queue.put(log) # Put the log back into the temporary queue\n except queue.Empty:\n pass\n\n # Process conversation records\n logs = temp_logs\n\n # If there are no new logs or not enough logs, try to read the last few lines directly from the file\n if len(logs) < max_lines and LOG_FILE and os.path.exists(LOG_FILE):\n try:\n with open(LOG_FILE, \"r\", encoding=\"utf-8\") as f:\n all_lines = f.readlines()\n # If there are already some logs in the queue, only read the remaining needed lines\n remaining_lines = max_lines - len(logs)\n file_logs = (\n all_lines[-remaining_lines:]\n if len(all_lines) > remaining_lines\n else all_lines\n )\n\n # Add file logs before queue logs\n logs = file_logs + logs\n except Exception as e:\n error_msg = f\"Error reading log file: {str(e)}\"\n logging.error(error_msg)\n if not logs: # Only add error message if there are no logs\n logs = [error_msg]\n\n # If there are still no logs, return a prompt message\n if not logs:\n return \"Initialization in progress...\"\n\n # Filter logs, only keep logs with 'camel.agents.chat_agent - INFO'\n filtered_logs = []\n for log in logs:\n if \"camel.agents.chat_agent - INFO\" in log:\n filtered_logs.append(log)\n\n # If there are no logs after filtering, return a prompt message\n if not filtered_logs:\n return \"No conversation records yet.\"\n\n # Process log content, extract the latest user and assistant messages\n simplified_logs = []\n\n # Use a set to track messages that have already been processed, to avoid duplicates\n processed_messages = set()\n\n def process_message(role, content):\n # Create a unique identifier to track messages\n msg_id = f\"{role}:{content}\"\n if msg_id in processed_messages:\n return None\n\n processed_messages.add(msg_id)\n content = content.replace(\"\\\\n\", \"\\n\")\n lines = [line.strip() for line in content.split(\"\\n\")]\n content = \"\\n\".join(lines)\n\n role_emoji = \"🙋\" if role.lower() == \"user\" else \"🤖\"\n return f\"\"\"### {role_emoji} {role.title()} Agent\n\n{content}\"\"\"\n\n for log in filtered_logs:\n formatted_messages = []\n # Try to extract message array\n messages_match = re.search(\n r\"Model (.*?), index (\\d+), processed these messages: (\\[.*\\])\", log\n )\n\n if messages_match:\n try:\n messages = json.loads(messages_match.group(3))\n for msg in messages:\n if msg.get(\"role\") in [\"user\", \"assistant\"]:\n formatted_msg = process_message(\n msg.get(\"role\"), msg.get(\"content\", \"\")\n )\n if formatted_msg:\n formatted_messages.append(formatted_msg)\n except json.JSONDecodeError:\n pass\n\n # If JSON parsing fails or no message array is found, try to extract conversation content directly\n if not formatted_messages:\n user_pattern = re.compile(r\"\\{'role': 'user', 'content': '(.*?)'\\}\")\n assistant_pattern = re.compile(\n r\"\\{'role': 'assistant', 'content': '(.*?)'\\}\"\n )\n\n for content in user_pattern.findall(log):\n formatted_msg = process_message(\"user\", content)\n if formatted_msg:\n formatted_messages.append(formatted_msg)\n\n for content in assistant_pattern.findall(log):\n formatted_msg = process_message(\"assistant\", content)\n if formatted_msg:\n formatted_messages.append(formatted_msg)\n\n if formatted_messages:\n simplified_logs.append(\"\\n\\n\".join(formatted_messages))\n\n # Format log output, ensure appropriate separation between each conversation record\n formatted_logs = []\n for i, log in enumerate(simplified_logs):\n # Remove excess whitespace characters from beginning and end\n log = log.strip()\n\n formatted_logs.append(log)\n\n # Ensure each conversation record ends with a newline\n if not log.endswith(\"\\n\"):\n formatted_logs.append(\"\\n\")\n\n return \"\\n\".join(formatted_logs)\n\n\n# Dictionary containing module descriptions\nMODULE_DESCRIPTIONS = {\n \"run\": \"Default mode: Using OpenAI model's default agent collaboration mode, suitable for most tasks.\",\n \"run_mini\": \"Using OpenAI model with minimal configuration to process tasks\",\n \"run_gemini\": \"Using Gemini model to process tasks\",\n \"run_claude\": \"Using Claude model to process tasks\",\n \"run_deepseek_zh\": \"Using deepseek model to process Chinese tasks\",\n \"run_mistral\": \"Using Mistral models to process tasks\",\n \"run_openai_compatible_model\": \"Using openai compatible model to process tasks\",\n \"run_ollama\": \"Using local ollama model to process tasks\",\n \"run_qwen_mini_zh\": \"Using qwen model with minimal configuration to process tasks\",\n \"run_qwen_zh\": \"Using qwen model to process tasks\",\n \"run_azure_openai\": \"Using azure openai model to process tasks\",\n \"run_groq\": \"Using groq model to process tasks\",\n \"run_ppio\": \"Using ppio model to process tasks\",\n \"run_together_ai\": \"Using together ai model to process tasks\",\n \"run_novita_ai\": \"Using novita ai model to process tasks\",\n}\n\n\n# Default environment variable template\nDEFAULT_ENV_TEMPLATE = \"\"\"#===========================================\n# MODEL & API \n# (See https://docs.camel-ai.org/key_modules/models.html#)\n#===========================================\n\n# OPENAI API (https://platform.openai.com/api-keys)\nOPENAI_API_KEY='Your_Key'\n# OPENAI_API_BASE_URL=\"\"\n\n# Azure OpenAI API\n# AZURE_OPENAI_BASE_URL=\"\"\n# AZURE_API_VERSION=\"\"\n# AZURE_OPENAI_API_KEY=\"\"\n# AZURE_DEPLOYMENT_NAME=\"\"\n\n\n# Qwen API (https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key)\nQWEN_API_KEY='Your_Key'\n\n# DeepSeek API (https://platform.deepseek.com/api_keys)\nDEEPSEEK_API_KEY='Your_Key'\n\n#===========================================\n# Tools & Services API\n#===========================================\n\n# Google Search API (https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3)\nGOOGLE_API_KEY='Your_Key'\nSEARCH_ENGINE_ID='Your_ID'\n\n# Chunkr API (https://chunkr.ai/)\nCHUNKR_API_KEY='Your_Key'\n\n# Firecrawl API (https://www.firecrawl.dev/)\nFIRECRAWL_API_KEY='Your_Key'\n#FIRECRAWL_API_URL=\"https://api.firecrawl.dev\"\n\"\"\"\n\n\ndef validate_input(question: str) -> bool:\n \"\"\"Validate if user input is valid\n\n Args:\n question: User question\n\n Returns:\n bool: Whether the input is valid\n \"\"\"\n # Check if input is empty or contains only spaces\n if not question or question.strip() == \"\":\n return False\n return True\n\n\ndef run_owl(question: str, example_module: str) -> Tuple[str, str, str]:\n \"\"\"Run the OWL system and return results\n\n Args:\n question: User question\n example_module: Example module name to import (e.g., \"run_terminal_zh\" or \"run_deep\")\n\n Returns:\n Tuple[...]: Answer, token count, status\n \"\"\"\n global CURRENT_PROCESS\n\n # Validate input\n if not validate_input(question):\n logging.warning(\"User submitted invalid input\")\n return (\n \"Please enter a valid question\",\n \"0\",\n \"❌ Error: Invalid input question\",\n )\n\n try:\n # Ensure environment variables are loaded\n load_dotenv(find_dotenv(), override=True)\n logging.info(\n f\"Processing question: '{question}', using module: {example_module}\"\n )\n\n # Check if the module is in MODULE_DESCRIPTIONS\n if example_module not in MODULE_DESCRIPTIONS:\n logging.error(f\"User selected an unsupported module: {example_module}\")\n return (\n f\"Selected module '{example_module}' is not supported\",\n \"0\",\n \"❌ Error: Unsupported module\",\n )\n\n # Dynamically import target module\n module_path = f\"examples.{example_module}\"\n try:\n logging.info(f\"Importing module: {module_path}\")\n module = importlib.import_module(module_path)\n except ImportError as ie:\n logging.error(f\"Unable to import module {module_path}: {str(ie)}\")\n return (\n f\"Unable to import module: {module_path}\",\n \"0\",\n f\"❌ Error: Module {example_module} does not exist or cannot be loaded - {str(ie)}\",\n )\n except Exception as e:\n logging.error(\n f\"Error occurred while importing module {module_path}: {str(e)}\"\n )\n return (\n f\"Error occurred while importing module: {module_path}\",\n \"0\",\n f\"❌ Error: {str(e)}\",\n )\n\n # Check if it contains the construct_society function\n if not hasattr(module, \"construct_society\"):\n logging.error(\n f\"construct_society function not found in module {module_path}\"\n )\n return (\n f\"construct_society function not found in module {module_path}\",\n \"0\",\n \"❌ Error: Module interface incompatible\",\n )\n\n # Build society simulation\n try:\n logging.info(\"Building society simulation...\")\n society = module.construct_society(question)\n\n except Exception as e:\n logging.error(f\"Error occurred while building society simulation: {str(e)}\")\n return (\n f\"Error occurred while building society simulation: {str(e)}\",\n \"0\",\n f\"❌ Error: Build failed - {str(e)}\",\n )\n\n # Run society simulation\n try:\n logging.info(\"Running society simulation...\")\n answer, chat_history, token_info = run_society(society)\n logging.info(\"Society simulation completed\")\n except Exception as e:\n logging.error(f\"Error occurred while running society simulation: {str(e)}\")\n return (\n f\"Error occurred while running society simulation: {str(e)}\",\n \"0\",\n f\"❌ Error: Run failed - {str(e)}\",\n )\n\n # Safely get token count\n if not isinstance(token_info, dict):\n token_info = {}\n\n completion_tokens = token_info.get(\"completion_token_count\", 0)\n prompt_tokens = token_info.get(\"prompt_token_count\", 0)\n total_tokens = completion_tokens + prompt_tokens\n\n logging.info(\n f\"Processing completed, token usage: completion={completion_tokens}, prompt={prompt_tokens}, total={total_tokens}\"\n )\n\n return (\n answer,\n f\"Completion tokens: {completion_tokens:,} | Prompt tokens: {prompt_tokens:,} | Total: {total_tokens:,}\",\n \"✅ Successfully completed\",\n )\n\n except Exception as e:\n logging.error(\n f\"Uncaught error occurred while processing the question: {str(e)}\"\n )\n return (f\"Error occurred: {str(e)}\", \"0\", f\"❌ Error: {str(e)}\")\n\n\ndef update_module_description(module_name: str) -> str:\n \"\"\"Return the description of the selected module\"\"\"\n return MODULE_DESCRIPTIONS.get(module_name, \"No description available\")\n\n\n# Store environment variables configured from the frontend\nWEB_FRONTEND_ENV_VARS: dict[str, str] = {}\n\n\ndef init_env_file():\n \"\"\"Initialize .env file if it doesn't exist\"\"\"\n dotenv_path = find_dotenv()\n if not dotenv_path:\n with open(\".env\", \"w\") as f:\n f.write(DEFAULT_ENV_TEMPLATE)\n dotenv_path = find_dotenv()\n return dotenv_path\n\n\ndef load_env_vars():\n \"\"\"Load environment variables and return as dictionary format\n\n Returns:\n dict: Environment variable dictionary, each value is a tuple containing value and source (value, source)\n \"\"\"\n dotenv_path = init_env_file()\n load_dotenv(dotenv_path, override=True)\n\n # Read environment variables from .env file\n env_file_vars = {}\n with open(dotenv_path, \"r\") as f:\n for line in f:\n line = line.strip()\n if line and not line.startswith(\"#\"):\n if \"=\" in line:\n key, value = line.split(\"=\", 1)\n env_file_vars[key.strip()] = value.strip().strip(\"\\\"'\")\n\n # Get from system environment variables\n system_env_vars = {\n k: v\n for k, v in os.environ.items()\n if k not in env_file_vars and k not in WEB_FRONTEND_ENV_VARS\n }\n\n # Merge environment variables and mark sources\n env_vars = {}\n\n # Add system environment variables (lowest priority)\n for key, value in system_env_vars.items():\n env_vars[key] = (value, \"System\")\n\n # Add .env file environment variables (medium priority)\n for key, value in env_file_vars.items():\n env_vars[key] = (value, \".env file\")\n\n # Add frontend configured environment variables (highest priority)\n for key, value in WEB_FRONTEND_ENV_VARS.items():\n env_vars[key] = (value, \"Frontend configuration\")\n # Ensure operating system environment variables are also updated\n os.environ[key] = value\n\n return env_vars\n\n\ndef save_env_vars(env_vars):\n \"\"\"Save environment variables to .env file\n\n Args:\n env_vars: Dictionary, keys are environment variable names, values can be strings or (value, source) tuples\n \"\"\"\n try:\n dotenv_path = init_env_file()\n\n # Save each environment variable\n for key, value_data in env_vars.items():\n if key and key.strip(): # Ensure key is not empty\n # Handle case where value might be a tuple\n if isinstance(value_data, tuple):\n value = value_data[0]\n else:\n value = value_data\n\n set_key(dotenv_path, key.strip(), value.strip())\n\n # Reload environment variables to ensure they take effect\n load_dotenv(dotenv_path, override=True)\n\n return True, \"Environment variables have been successfully saved!\"\n except Exception as e:\n return False, f\"Error saving environment variables: {str(e)}\"\n\n\ndef add_env_var(key, value, from_frontend=True):\n \"\"\"Add or update a single environment variable\n\n Args:\n key: Environment variable name\n value: Environment variable value\n from_frontend: Whether it's from frontend configuration, default is True\n \"\"\"\n try:\n if not key or not key.strip():\n return False, \"Variable name cannot be empty\"\n\n key = key.strip()\n value = value.strip()\n\n # If from frontend, add to frontend environment variable dictionary\n if from_frontend:\n WEB_FRONTEND_ENV_VARS[key] = value\n # Directly update system environment variables\n os.environ[key] = value\n\n # Also update .env file\n dotenv_path = init_env_file()\n set_key(dotenv_path, key, value)\n load_dotenv(dotenv_path, override=True)\n\n return True, f\"Environment variable {key} has been successfully added/updated!\"\n except Exception as e:\n return False, f\"Error adding environment variable: {str(e)}\"\n\n\ndef delete_env_var(key):\n \"\"\"Delete environment variable\"\"\"\n try:\n if not key or not key.strip():\n return False, \"Variable name cannot be empty\"\n\n key = key.strip()\n\n # Delete from .env file\n dotenv_path = init_env_file()\n unset_key(dotenv_path, key)\n\n # Delete from frontend environment variable dictionary\n if key in WEB_FRONTEND_ENV_VARS:\n del WEB_FRONTEND_ENV_VARS[key]\n\n # Also delete from current process environment\n if key in os.environ:\n del os.environ[key]\n\n return True, f\"Environment variable {key} has been successfully deleted!\"\n except Exception as e:\n return False, f\"Error deleting environment variable: {str(e)}\"\n\n\ndef is_api_related(key: str) -> bool:\n \"\"\"Determine if an environment variable is API-related\n\n Args:\n key: Environment variable name\n\n Returns:\n bool: Whether it's API-related\n \"\"\"\n # API-related keywords\n api_keywords = [\n \"api\",\n \"key\",\n \"token\",\n \"secret\",\n \"password\",\n \"openai\",\n \"qwen\",\n \"deepseek\",\n \"google\",\n \"search\",\n \"hf\",\n \"hugging\",\n \"chunkr\",\n \"firecrawl\",\n ]\n\n # Check if it contains API-related keywords (case insensitive)\n return any(keyword in key.lower() for keyword in api_keywords)\n\n\ndef get_api_guide(key: str) -> str:\n \"\"\"Return the corresponding API guide based on the environment variable name\n\n Args:\n key: Environment variable name\n\n Returns:\n str: API guide link or description\n \"\"\"\n key_lower = key.lower()\n if \"openai\" in key_lower:\n return \"https://platform.openai.com/api-keys\"\n elif \"qwen\" in key_lower or \"dashscope\" in key_lower:\n return \"https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key\"\n elif \"deepseek\" in key_lower:\n return \"https://platform.deepseek.com/api_keys\"\n elif \"ppio\" in key_lower:\n return \"https://ppinfra.com/settings/key-management?utm_source=github_owl\"\n elif \"google\" in key_lower:\n return \"https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3\"\n elif \"search_engine_id\" in key_lower:\n return \"https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3\"\n elif \"chunkr\" in key_lower:\n return \"https://chunkr.ai/\"\n elif \"firecrawl\" in key_lower:\n return \"https://www.firecrawl.dev/\"\n elif \"novita\" in key_lower:\n return \"https://novita.ai/settings/key-management?utm_source=github_owl&utm_medium=github_readme&utm_campaign=github_link\"\n else:\n return \"\"\n\n\ndef update_env_table():\n \"\"\"Update environment variable table display, only showing API-related environment variables\"\"\"\n env_vars = load_env_vars()\n # Filter out API-related environment variables\n api_env_vars = {k: v for k, v in env_vars.items() if is_api_related(k)}\n # Convert to list format to meet Gradio Dataframe requirements\n # Format: [Variable name, Variable value, Guide link]\n result = []\n for k, v in api_env_vars.items():\n guide = get_api_guide(k)\n # If there's a guide link, create a clickable link\n guide_link = (\n f\"🔗 Get\"\n if guide\n else \"\"\n )\n result.append([k, v[0], guide_link])\n return result\n\n\ndef save_env_table_changes(data):\n \"\"\"Save changes to the environment variable table\n\n Args:\n data: Dataframe data, possibly a pandas DataFrame object\n\n Returns:\n str: Operation status information, containing HTML-formatted status message\n \"\"\"\n try:\n logging.info(\n f\"Starting to process environment variable table data, type: {type(data)}\"\n )\n\n # Get all current environment variables\n current_env_vars = load_env_vars()\n processed_keys = set() # Record processed keys to detect deleted variables\n\n # Process pandas DataFrame object\n import pandas as pd\n\n if isinstance(data, pd.DataFrame):\n # Get column name information\n columns = data.columns.tolist()\n logging.info(f\"DataFrame column names: {columns}\")\n\n # Iterate through each row of the DataFrame\n for index, row in data.iterrows():\n # Use column names to access data\n ", "suffix_code": "\n # Process other formats\n elif isinstance(data, dict):\n logging.info(f\"Dictionary format data keys: {list(data.keys())}\")\n # If dictionary format, try different keys\n if \"data\" in data:\n rows = data[\"data\"]\n elif \"values\" in data:\n rows = data[\"values\"]\n elif \"value\" in data:\n rows = data[\"value\"]\n else:\n # Try using dictionary directly as row data\n rows = []\n for key, value in data.items():\n if key not in [\"headers\", \"types\", \"columns\"]:\n rows.append([key, value])\n\n if isinstance(rows, list):\n for row in rows:\n if isinstance(row, list) and len(row) >= 2:\n key, value = row[0], row[1]\n if key and str(key).strip():\n add_env_var(key, str(value))\n processed_keys.add(key)\n elif isinstance(data, list):\n # 列表格式\n for row in data:\n if isinstance(row, list) and len(row) >= 2:\n key, value = row[0], row[1]\n if key and str(key).strip():\n add_env_var(key, str(value))\n processed_keys.add(key)\n else:\n logging.error(f\"Unknown data format: {type(data)}\")\n return f\"❌ Save failed: Unknown data format {type(data)}\"\n\n # Process deleted variables - check if there are variables in current environment not appearing in the table\n api_related_keys = {k for k in current_env_vars.keys() if is_api_related(k)}\n keys_to_delete = api_related_keys - processed_keys\n\n # Delete variables no longer in the table\n for key in keys_to_delete:\n logging.info(f\"Deleting environment variable: {key}\")\n delete_env_var(key)\n\n return \"✅ Environment variables have been successfully saved\"\n except Exception as e:\n import traceback\n\n error_details = traceback.format_exc()\n logging.error(f\"Error saving environment variables: {str(e)}\\n{error_details}\")\n return f\"❌ Save failed: {str(e)}\"\n\n\ndef get_env_var_value(key):\n \"\"\"Get the actual value of an environment variable\n\n Priority: Frontend configuration > .env file > System environment variables\n \"\"\"\n # Check frontend configured environment variables\n if key in WEB_FRONTEND_ENV_VARS:\n return WEB_FRONTEND_ENV_VARS[key]\n\n # Check system environment variables (including those loaded from .env)\n return os.environ.get(key, \"\")\n\n\ndef create_ui():\n \"\"\"Create enhanced Gradio interface\"\"\"\n\n def clear_log_file():\n \"\"\"Clear log file content\"\"\"\n try:\n if LOG_FILE and os.path.exists(LOG_FILE):\n # Clear log file content instead of deleting the file\n open(LOG_FILE, \"w\").close()\n logging.info(\"Log file has been cleared\")\n # Clear log queue\n while not LOG_QUEUE.empty():\n try:\n LOG_QUEUE.get_nowait()\n except queue.Empty:\n break\n return \"\"\n else:\n return \"\"\n except Exception as e:\n logging.error(f\"Error clearing log file: {str(e)}\")\n return \"\"\n\n # Create a real-time log update function\n def process_with_live_logs(question, module_name):\n \"\"\"Process questions and update logs in real-time\"\"\"\n global CURRENT_PROCESS\n\n # Clear log file\n clear_log_file()\n\n # Create a background thread to process the question\n result_queue = queue.Queue()\n\n def process_in_background():\n try:\n result = run_owl(question, module_name)\n result_queue.put(result)\n except Exception as e:\n result_queue.put(\n (f\"Error occurred: {str(e)}\", \"0\", f\"❌ Error: {str(e)}\")\n )\n\n # Start background processing thread\n bg_thread = threading.Thread(target=process_in_background)\n CURRENT_PROCESS = bg_thread # Record current process\n bg_thread.start()\n\n # While waiting for processing to complete, update logs once per second\n while bg_thread.is_alive():\n # Update conversation record display\n logs2 = get_latest_logs(100, LOG_QUEUE)\n\n # Always update status\n yield (\n \"0\",\n \" Processing...\",\n logs2,\n )\n\n time.sleep(1)\n\n # Processing complete, get results\n if not result_queue.empty():\n result = result_queue.get()\n answer, token_count, status = result\n\n # Final update of conversation record\n logs2 = get_latest_logs(100, LOG_QUEUE)\n\n # Set different indicators based on status\n if \"Error\" in status:\n status_with_indicator = (\n f\" {status}\"\n )\n else:\n status_with_indicator = (\n f\" {status}\"\n )\n\n yield token_count, status_with_indicator, logs2\n else:\n logs2 = get_latest_logs(100, LOG_QUEUE)\n yield (\n \"0\",\n \" Terminated\",\n logs2,\n )\n\n with gr.Blocks(title=\"OWL\", theme=gr.themes.Soft(primary_hue=\"blue\")) as app:\n gr.Markdown(\n \"\"\"\n # 🦉 OWL Multi-Agent Collaboration System\n\n Advanced multi-agent collaboration system developed based on the CAMEL framework, designed to solve complex problems through agent collaboration.\n\n Models and tools can be customized by modifying local scripts.\n \n This web app is currently in beta development. It is provided for demonstration and testing purposes only and is not yet recommended for production use.\n \"\"\"\n )\n\n # Add custom CSS\n gr.HTML(\"\"\"\n \n \"\"\")\n\n with gr.Row():\n with gr.Column(scale=0.5):\n question_input = gr.Textbox(\n lines=5,\n placeholder=\"Please enter your question...\",\n label=\"Question\",\n elem_id=\"question_input\",\n show_copy_button=True,\n value=\"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\",\n )\n\n # Enhanced module selection dropdown\n # Only includes modules defined in MODULE_DESCRIPTIONS\n module_dropdown = gr.Dropdown(\n choices=list(MODULE_DESCRIPTIONS.keys()),\n value=\"run\",\n label=\"Select Function Module\",\n interactive=True,\n )\n\n # Module description text box\n module_description = gr.Textbox(\n value=MODULE_DESCRIPTIONS[\"run\"],\n label=\"Module Description\",\n interactive=False,\n elem_classes=\"module-info\",\n )\n\n with gr.Row():\n run_button = gr.Button(\n \"Run\", variant=\"primary\", elem_classes=\"primary\"\n )\n\n status_output = gr.HTML(\n value=\" Ready\",\n label=\"Status\",\n )\n token_count_output = gr.Textbox(\n label=\"Token Count\", interactive=False, elem_classes=\"token-count\"\n )\n\n # Example questions\n examples = [\n \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\",\n \"Browse Amazon and find a product that is attractive to programmers. Please provide the product name and price\",\n \"Write a hello world python file and save it locally\",\n ]\n\n gr.Examples(examples=examples, inputs=question_input)\n\n gr.HTML(\"\"\"\n
\n

About OWL Multi-Agent Collaboration System

\n

OWL is an advanced multi-agent collaboration system developed based on the CAMEL framework, designed to solve complex problems through agent collaboration.

\n

© 2025 CAMEL-AI.org. Based on Apache License 2.0 open source license

\n

GitHub

\n
\n \"\"\")\n\n with gr.Tabs(): # Set conversation record as the default selected tab\n with gr.TabItem(\"Conversation Record\"):\n # Add conversation record display area\n with gr.Group():\n log_display2 = gr.Markdown(\n value=\"No conversation records yet.\",\n elem_classes=\"log-display\",\n )\n\n with gr.Row():\n refresh_logs_button2 = gr.Button(\"Refresh Record\")\n auto_refresh_checkbox2 = gr.Checkbox(\n label=\"Auto Refresh\", value=True, interactive=True\n )\n clear_logs_button2 = gr.Button(\n \"Clear Record\", variant=\"secondary\"\n )\n\n with gr.TabItem(\"Environment Variable Management\", id=\"env-settings\"):\n with gr.Group(elem_classes=\"env-manager-container\"):\n gr.Markdown(\"\"\"\n ## Environment Variable Management\n \n Set model API keys and other service credentials here. This information will be saved in a local `.env` file, ensuring your API keys are securely stored and not uploaded to the network. Correctly setting API keys is crucial for the functionality of the OWL system. Environment variables can be flexibly configured according to tool requirements.\n \"\"\")\n\n # Main content divided into two-column layout\n with gr.Row():\n # Left column: Environment variable management controls\n with gr.Column(scale=3):\n with gr.Group(elem_classes=\"env-controls\"):\n # Environment variable table - set to interactive for direct editing\n gr.Markdown(\"\"\"\n
\n Tip: Please make sure to run cp .env_template .env to create a local .env file, and flexibly configure the required environment variables according to the running module\n
\n \"\"\")\n\n # Enhanced environment variable table, supporting adding and deleting rows\n env_table = gr.Dataframe(\n headers=[\n \"Variable Name\",\n \"Value\",\n \"Retrieval Guide\",\n ],\n datatype=[\n \"str\",\n \"str\",\n \"html\",\n ], # Set the last column as HTML type to support links\n row_count=10, # Increase row count to allow adding new variables\n col_count=(3, \"fixed\"),\n value=update_env_table,\n label=\"API Keys and Environment Variables\",\n interactive=True, # Set as interactive, allowing direct editing\n elem_classes=\"env-table\",\n )\n\n # Operation instructions\n gr.Markdown(\n \"\"\"\n
\n Operation Guide:\n \n
\n \"\"\",\n elem_classes=\"env-instructions\",\n )\n\n # Environment variable operation buttons\n with gr.Row(elem_classes=\"env-buttons\"):\n save_env_button = gr.Button(\n \"💾 Save Changes\",\n variant=\"primary\",\n elem_classes=\"env-button\",\n )\n refresh_button = gr.Button(\n \"🔄 Refresh List\", elem_classes=\"env-button\"\n )\n\n # Status display\n env_status = gr.HTML(\n label=\"Operation Status\",\n value=\"\",\n elem_classes=\"env-status\",\n )\n\n # 连接事件处理函数\n save_env_button.click(\n fn=save_env_table_changes,\n inputs=[env_table],\n outputs=[env_status],\n ).then(fn=update_env_table, outputs=[env_table])\n\n refresh_button.click(fn=update_env_table, outputs=[env_table])\n\n # Set up event handling\n run_button.click(\n fn=process_with_live_logs,\n inputs=[question_input, module_dropdown],\n outputs=[token_count_output, status_output, log_display2],\n )\n\n # Module selection updates description\n module_dropdown.change(\n fn=update_module_description,\n inputs=module_dropdown,\n outputs=module_description,\n )\n\n # Conversation record related event handling\n refresh_logs_button2.click(\n fn=lambda: get_latest_logs(100, LOG_QUEUE), outputs=[log_display2]\n )\n\n clear_logs_button2.click(fn=clear_log_file, outputs=[log_display2])\n\n # Auto refresh control\n def toggle_auto_refresh(enabled):\n if enabled:\n return gr.update(every=3)\n else:\n return gr.update(every=0)\n\n auto_refresh_checkbox2.change(\n fn=toggle_auto_refresh,\n inputs=[auto_refresh_checkbox2],\n outputs=[log_display2],\n )\n\n # No longer automatically refresh logs by default\n\n return app\n\n\n# Main function\ndef main():\n try:\n # Initialize logging system\n global LOG_FILE\n LOG_FILE = setup_logging()\n logging.info(\"OWL Web application started\")\n\n # Start log reading thread\n log_thread = threading.Thread(\n target=log_reader_thread, args=(LOG_FILE,), daemon=True\n )\n log_thread.start()\n logging.info(\"Log reading thread started\")\n\n # Initialize .env file (if it doesn't exist)\n init_env_file()\n app = create_ui()\n\n app.queue()\n app.launch(\n share=False,\n favicon_path=os.path.join(\n os.path.dirname(__file__), \"assets\", \"owl-favicon.ico\"\n ),\n )\n except Exception as e:\n logging.error(f\"Error occurred while starting the application: {str(e)}\")\n print(f\"Error occurred while starting the application: {str(e)}\")\n import traceback\n\n traceback.print_exc()\n\n finally:\n # Ensure log thread stops\n STOP_LOG_THREAD.set()\n STOP_REQUESTED.set()\n logging.info(\"Application closed\")\n\n\nif __name__ == \"__main__\":\n main()\n", "middle_code": "if len(columns) >= 3:\n key = row[0] if isinstance(row, pd.Series) else row.iloc[0]\n value = row[1] if isinstance(row, pd.Series) else row.iloc[1]\n if (\n key and str(key).strip()\n ): \n logging.info(\n f\"Processing environment variable: {key} = {value}\"\n )\n add_env_var(key, str(value))\n processed_keys.add(key)", "code_description": null, "fill_type": "BLOCK_TYPE", "language_type": "python", "sub_task_type": "if_statement"}, "context_code": [["/owl/community_usecase/OWL Interview Preparation Assistant/logging_utils.py", "import os\nimport logging\nimport time\nimport functools\nimport inspect\nimport re\nfrom typing import Dict, Any, List, Tuple, Callable, Optional\nimport queue\n\n# Create a singleton log queue that can be shared between modules\nclass LogQueueSingleton:\n _instance = None\n \n @classmethod\n def get_instance(cls):\n if cls._instance is None:\n cls._instance = queue.Queue()\n return cls._instance\n\n# Custom logging wrapper for tools\ndef log_tool_usage(func):\n \"\"\"\n Decorator to log when a tool is being used.\n \"\"\"\n @functools.wraps(func)\n async def wrapper(*args, **kwargs):\n tool_name = func.__name__\n logging.info(f\"🔧 TOOL TRIGGERED: {tool_name}\")\n try:\n # Sanitize arguments to avoid logging sensitive info\n safe_args = sanitize_args(args)\n safe_kwargs = {k: sanitize_value(v) for k, v in kwargs.items()}\n logging.info(f\"🔍 TOOL ARGS: {tool_name} called with {len(safe_kwargs)} parameters\")\n \n result = await func(*args, **kwargs)\n \n # Log completion but not the actual result content (might be large or sensitive)\n logging.info(f\"✅ TOOL COMPLETED: {tool_name}\")\n return result\n except Exception as e:\n logging.error(f\"❌ TOOL ERROR: {tool_name} - {str(e)}\")\n raise\n return wrapper\n\n# Non-async version for synchronous functions\ndef log_tool_usage_sync(func):\n \"\"\"\n Decorator to log when a synchronous tool is being used.\n \"\"\"\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n tool_name = func.__name__\n logging.info(f\"🔧 TOOL TRIGGERED: {tool_name}\")\n try:\n # Sanitize arguments to avoid logging sensitive info\n safe_args = sanitize_args(args)\n safe_kwargs = {k: sanitize_value(v) for k, v in kwargs.items()}\n logging.info(f\"🔍 TOOL ARGS: {tool_name} called with {len(safe_kwargs)} parameters\")\n \n result = func(*args, **kwargs)\n \n # Log completion but not the actual result content (might be large or sensitive)\n logging.info(f\"✅ TOOL COMPLETED: {tool_name}\")\n return result\n except Exception as e:\n logging.error(f\"❌ TOOL ERROR: {tool_name} - {str(e)}\")\n raise\n return wrapper\n\ndef sanitize_args(args):\n \"\"\"Sanitize arguments for logging to avoid sensitive data.\"\"\"\n safe_args = []\n for arg in args:\n safe_args.append(sanitize_value(arg))\n return safe_args\n\ndef sanitize_value(value):\n \"\"\"Sanitize a value for logging.\"\"\"\n if isinstance(value, str):\n if len(value) > 50:\n return value[:47] + \"...\"\n return value\n elif isinstance(value, (list, tuple)):\n return f\"{type(value).__name__} with {len(value)} items\"\n elif isinstance(value, dict):\n return f\"dict with {len(value)} items\"\n else:\n return f\"{type(value).__name__}\"\n\nclass LoggingToolkitWrapper:\n \"\"\"\n Wrapper class to add logging to toolkit methods.\n \"\"\"\n def __init__(self, toolkit):\n self.toolkit = toolkit\n self.toolkit_name = toolkit.__class__.__name__\n logging.info(f\"📦 TOOLKIT INITIALIZED: {self.toolkit_name}\")\n \n def __getattr__(self, name):\n attr = getattr(self.toolkit, name)\n \n if callable(attr) and not name.startswith('_'):\n if inspect.iscoroutinefunction(attr):\n # It's an async function, wrap it with our async decorator\n return log_tool_usage(attr)\n else:\n # For non-async functions\n @functools.wraps(attr)\n def wrapper(*args, **kwargs):\n logging.info(f\"🔧 TOOL TRIGGERED: {self.toolkit_name}.{name}\")\n try:\n # Sanitize arguments to avoid logging sensitive info\n safe_args = sanitize_args(args)\n safe_kwargs = {k: sanitize_value(v) for k, v in kwargs.items()}\n logging.info(f\"🔍 TOOL ARGS: {name} called with {len(safe_kwargs)} parameters\")\n \n result = attr(*args, **kwargs)\n \n logging.info(f\"✅ TOOL COMPLETED: {self.toolkit_name}.{name}\")\n return result\n except Exception as e:\n logging.error(f\"❌ TOOL ERROR: {self.toolkit_name}.{name} - {str(e)}\")\n raise\n return wrapper\n \n return attr\n\ndef wrap_toolkits(toolkits_list):\n \"\"\"\n Wrap a list of toolkits with logging functionality.\n \"\"\"\n wrapped_toolkits = []\n for toolkit in toolkits_list:\n wrapped_toolkits.append(LoggingToolkitWrapper(toolkit))\n return wrapped_toolkits\n# Find this function in logging_utils.py and replace it with this corrected version\n\n# Enhanced run_society function with logging\ndef enhanced_run_society(society, verbose=True):\n \"\"\"\n Enhanced wrapper around the OWL run_society function with detailed logging.\n \"\"\"\n from owl.utils import run_society as original_run_society\n \n # Log the society setup\n user_role = getattr(society, 'user_role_name', 'User')\n assistant_role = getattr(society, 'assistant_role_name', 'Assistant')\n \n logging.info(f\"🚀 STARTING AGENT SOCIETY: {user_role} & {assistant_role}\")\n logging.info(f\"📝 TASK: {society.task_prompt[:100]}...\")\n \n # Log agent initialization\n logging.info(f\"🤖 INITIALIZING AGENT: {assistant_role}\")\n \n # Add hooks to log message exchanges if possible\n original_send_message = None\n if hasattr(society, 'assistant_agent') and hasattr(society.assistant_agent, 'send_message'):\n original_send_message = society.assistant_agent.send_message\n \n @functools.wraps(original_send_message)\n def logged_send_message(*args, **kwargs):\n logging.info(f\"💬 AGENT MESSAGE: {assistant_role} is processing...\")\n result = original_send_message(*args, **kwargs)\n logging.info(f\"📨 AGENT RESPONSE RECEIVED from {assistant_role}\")\n return result\n \n society.assistant_agent.send_message = logged_send_message\n \n # Try to log tool usage if possible\n if hasattr(society, 'assistant_agent') and hasattr(society.assistant_agent, 'tools'):\n tools = getattr(society.assistant_agent, 'tools', [])\n logging.info(f\"🧰 AGENT HAS {len(tools)} TOOLS AVAILABLE\")\n \n # Attempt to wrap each tool with logging\n for i, tool in enumerate(tools):\n if callable(tool):\n tool_name = getattr(tool, '__name__', f\"tool_{i}\")\n logging.info(f\"🔧 TOOL AVAILABLE: {tool_name}\")\n \n # Run the original function\n start_time = time.time()\n try:\n logging.info(f\"⏳ RUNNING SOCIETY...\")\n # Remove the verbose parameter from the call to original_run_society\n answer, chat_history, token_count = original_run_society(society)\n end_time = time.time()\n duration = end_time - start_time\n \n # Log prompt and completion tokens separately if available\n if isinstance(token_count, dict):\n prompt_tokens = token_count.get('prompt_token_count', 0)\n completion_tokens = token_count.get('completion_token_count', 0)\n logging.info(f\"💰 TOKEN USAGE: Prompt={prompt_tokens}, Completion={completion_tokens}, Total={prompt_tokens + completion_tokens}\")\n else:\n logging.info(f\"💰 TOKEN USAGE: {token_count}\")\n \n logging.info(f\"✅ AGENT SOCIETY COMPLETED: Duration {duration:.2f}s\")\n \n return answer, chat_history, token_count\n except Exception as e:\n logging.error(f\"❌ AGENT SOCIETY ERROR: {str(e)}\")\n raise\n finally:\n # Restore original method if we modified it\n if original_send_message and hasattr(society, 'assistant_agent'):\n society.assistant_agent.send_message = original_send_message\n \n \n\n# Function to sanitize logs to avoid exposing sensitive information\ndef sanitize_log(log_message):\n \"\"\"\n Sanitize log messages to avoid exposing sensitive information like IPs.\n \"\"\"\n # Simple IP address pattern matching\n ip_pattern = r'\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b'\n sanitized = re.sub(ip_pattern, '[REDACTED_IP]', log_message)\n \n # Redact API keys (common patterns)\n api_key_pattern = r'(api[_-]?key|apikey|key|token)[\"\\']?\\s*[:=]\\s*[\"\\']?([a-zA-Z0-9]{20,})[\"\\']?'\n sanitized = re.sub(api_key_pattern, r'\\1: [REDACTED_API_KEY]', sanitized, flags=re.IGNORECASE)\n \n # Redact URLs with authentication information\n url_auth_pattern = r'(https?://)([^:@/]+:[^@/]+@)([^\\s/]+)'\n sanitized = re.sub(url_auth_pattern, r'\\1[REDACTED_AUTH]@\\3', sanitized)\n \n return sanitized\n\n# Enhanced StreamlitLogHandler that sanitizes logs\nclass EnhancedStreamlitLogHandler(logging.Handler):\n def __init__(self, log_queue):\n super().__init__()\n self.log_queue = log_queue\n self.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))\n \n def emit(self, record):\n log_entry = self.format(record)\n # Sanitize the log to remove sensitive information\n sanitized_log = sanitize_log(log_entry)\n self.log_queue.put(sanitized_log)\n\n# Add logging to specific OWL functions if possible\n# Add this updated function to logging_utils.py\n\n# Add logging to specific OWL functions if possible\ndef patch_owl_logging():\n \"\"\"Try to patch specific OWL functions to add logging.\"\"\"\n try:\n from owl import utils\n \n # If run_society exists in utils, patch it to log\n if hasattr(utils, 'run_society'):\n original_run = utils.run_society\n \n def logged_run_society(*args, **kwargs):\n logging.info(\"🦉 OWL run_society called\")\n try:\n result = original_run(*args, **kwargs)\n logging.info(\"🦉 OWL run_society completed\")\n return result\n except Exception as e:\n logging.error(f\"🦉 OWL run_society error: {str(e)}\")\n raise\n \n # Replace the original function\n utils.run_society = logged_run_society\n logging.info(\"🦉 OWL run_society patched with logging\")\n \n return True\n except ImportError:\n logging.warning(\"⚠️ Could not patch OWL logging - module not found\")\n return False\n except Exception as e:\n logging.warning(f\"⚠️ Error patching OWL logging: {str(e)}\")\n return False"], ["/owl/community_usecase/a_share_investment_agent_camel/src/utils/logging_utils.py", "\"\"\"\n日志工具模块\n\"\"\"\nimport logging\nimport os\nfrom datetime import datetime\nfrom typing import Optional\n\n\ndef setup_logger(name: str, log_level: int = logging.INFO, log_dir: str = \"logs\") -> logging.Logger:\n \"\"\"\n 设置日志记录器\n \n Args:\n name: 日志记录器名称\n log_level: 日志级别\n log_dir: 日志目录\n \n Returns:\n logging.Logger: 配置好的日志记录器\n \"\"\"\n # 确保日志目录存在\n os.makedirs(log_dir, exist_ok=True)\n \n # 获取日志记录器\n logger = logging.getLogger(name)\n \n # 如果已配置,直接返回\n if logger.handlers:\n return logger\n \n # 设置日志级别\n logger.setLevel(log_level)\n \n # 创建文件处理器\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n log_file = f\"{log_dir}/{name}_{timestamp}.log\"\n file_handler = logging.FileHandler(log_file, encoding=\"utf-8\")\n file_handler.setLevel(log_level)\n \n # 创建控制台处理器\n console_handler = logging.StreamHandler()\n console_handler.setLevel(log_level)\n \n # 设置格式化器\n formatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n file_handler.setFormatter(formatter)\n console_handler.setFormatter(formatter)\n \n # 添加处理器\n logger.addHandler(file_handler)\n logger.addHandler(console_handler)\n \n return logger\n\n\nclass OutputLogger:\n \"\"\"\n 输出日志记录器,用于重定向标准输出\n \"\"\"\n def __init__(self, filename: Optional[str] = None):\n \"\"\"\n 初始化输出日志记录器\n \n Args:\n filename: 日志文件名,默认为自动生成\n \"\"\"\n # 确保日志目录存在\n os.makedirs(\"logs\", exist_ok=True)\n \n # 设置日志文件\n if not filename:\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n filename = f\"logs/output_{timestamp}.log\"\n \n self.terminal = open(filename, \"a\", encoding=\"utf-8\")\n self.terminal.write(f\"=== 日志开始于 {datetime.now()} ===\\n\")\n self.stdout = None\n \n def write(self, message):\n \"\"\"写入消息到终端和日志文件\"\"\"\n if self.stdout:\n self.stdout.write(message)\n self.terminal.write(message)\n self.terminal.flush()\n \n def flush(self):\n \"\"\"刷新日志\"\"\"\n if self.stdout:\n self.stdout.flush()\n self.terminal.flush()\n \n def close(self):\n \"\"\"关闭日志文件\"\"\"\n self.terminal.write(f\"=== 日志结束于 {datetime.now()} ===\\n\")\n self.terminal.close()\n \n def __del__(self):\n \"\"\"析构函数,确保关闭日志文件\"\"\"\n try:\n self.close()\n except:\n pass "], ["/owl/owl/webapp_jp.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# 正しいモジュールパスからインポート\nfrom utils import run_society\nimport os\nimport gradio as gr\nimport time\nimport json\nimport logging\nimport datetime\nfrom typing import Tuple\nimport importlib\nfrom dotenv import load_dotenv, set_key, find_dotenv, unset_key\nimport threading\nimport queue\nimport re\n\nos.environ[\"PYTHONIOENCODING\"] = \"utf-8\"\n\n\n# ロギングシステムを設定\ndef setup_logging():\n \"\"\"ログをファイル、メモリキュー、およびコンソールに出力するようにロギングシステムを設定\"\"\"\n # logsディレクトリを作成(存在しない場合)\n logs_dir = os.path.join(os.path.dirname(__file__), \"logs\")\n os.makedirs(logs_dir, exist_ok=True)\n\n # ログファイル名を生成(現在の日付を使用)\n current_date = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n log_file = os.path.join(logs_dir, f\"gradio_log_{current_date}.txt\")\n\n # ルートロガーを設定(すべてのログをキャプチャ)\n root_logger = logging.getLogger()\n\n # 重複ログを避けるために既存のハンドラをクリア\n for handler in root_logger.handlers[:]:\n root_logger.removeHandler(handler)\n\n root_logger.setLevel(logging.INFO)\n\n # ファイルハンドラを作成\n file_handler = logging.FileHandler(log_file, encoding=\"utf-8\", mode=\"a\")\n file_handler.setLevel(logging.INFO)\n\n # コンソールハンドラを作成\n console_handler = logging.StreamHandler()\n console_handler.setLevel(logging.INFO)\n\n # フォーマッタを作成\n formatter = logging.Formatter(\n \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n )\n file_handler.setFormatter(formatter)\n console_handler.setFormatter(formatter)\n\n # Add handlers to root logger\n root_logger.addHandler(file_handler)\n root_logger.addHandler(console_handler)\n\n logging.info(\"ログシステムが初期化されました、ログファイル: %s\", log_file)\n return log_file\n\n\n# グローバル変数\nLOG_FILE = None\nLOG_QUEUE: queue.Queue = queue.Queue() # ログキュー\nSTOP_LOG_THREAD = threading.Event()\nCURRENT_PROCESS = None # 現在実行中のプロセスを追跡するために使用\nSTOP_REQUESTED = threading.Event() # 停止が要求されたかどうかをマークするために使用\n\n\n# ログの読み取りと更新の関数\ndef log_reader_thread(log_file):\n \"\"\"継続的にログファイルを読み取り、新しい行をキューに追加するバックグラウンドスレッド\"\"\"\n try:\n with open(log_file, \"r\", encoding=\"utf-8\") as f:\n # ファイルの末尾に移動\n f.seek(0, 2)\n\n while not STOP_LOG_THREAD.is_set():\n line = f.readline()\n if line:\n LOG_QUEUE.put(line) # 会話記録キューに追加\n else:\n # 新しい行がない場合は短時間待機\n time.sleep(0.1)\n except Exception as e:\n logging.error(f\"ログリーダースレッドエラー: {str(e)}\")\n\n\ndef get_latest_logs(max_lines=100, queue_source=None):\n \"\"\"キューから最新のログ行を取得するか、キューが空の場合はファイルから直接読み取る\n\n 引数:\n max_lines: 返す最大行数\n queue_source: 使用するキューを指定、デフォルトはLOG_QUEUE\n\n 戻り値:\n str: ログ内容\n \"\"\"\n logs = []\n log_queue = queue_source if queue_source else LOG_QUEUE\n\n # 元のキューから削除せずに処理できるように、ログを保存する一時キューを作成\n temp_queue = queue.Queue()\n temp_logs = []\n\n try:\n # キューから利用可能なすべてのログ行を取得\n while not log_queue.empty() and len(temp_logs) < max_lines:\n log = log_queue.get_nowait()\n temp_logs.append(log)\n temp_queue.put(log) # ログを一時キューに戻す\n except queue.Empty:\n pass\n\n # 会話記録を処理\n logs = temp_logs\n\n # 新しいログがないか、十分なログがない場合は、ファイルから直接最後の数行を読み取る\n if len(logs) < max_lines and LOG_FILE and os.path.exists(LOG_FILE):\n try:\n with open(LOG_FILE, \"r\", encoding=\"utf-8\") as f:\n all_lines = f.readlines()\n # キューにすでにいくつかのログがある場合は、必要な残りの行だけを読み取る\n remaining_lines = max_lines - len(logs)\n file_logs = (\n all_lines[-remaining_lines:]\n if len(all_lines) > remaining_lines\n else all_lines\n )\n\n # ファイルログをキューログの前に追加\n logs = file_logs + logs\n except Exception as e:\n error_msg = f\"ログファイルの読み取りエラー: {str(e)}\"\n logging.error(error_msg)\n if not logs: # ログがない場合のみエラーメッセージを追加\n logs = [error_msg]\n\n # まだログがない場合は、プロンプトメッセージを返す\n if not logs:\n return \"初期化中...\"\n\n # ログをフィルタリングし、'camel.agents.chat_agent - INFO'を含むログのみを保持\n filtered_logs = []\n for log in logs:\n if \"camel.agents.chat_agent - INFO\" in log:\n filtered_logs.append(log)\n\n # フィルタリング後にログがない場合は、プロンプトメッセージを返す\n if not filtered_logs:\n return \"まだ会話記録はありません。\"\n\n # Process log content, extract the latest user and assistant messages\n simplified_logs = []\n\n # Use a set to track messages that have already been processed, to avoid duplicates\n processed_messages = set()\n\n def process_message(role, content):\n # Create a unique identifier to track messages\n msg_id = f\"{role}:{content}\"\n if msg_id in processed_messages:\n return None\n\n processed_messages.add(msg_id)\n content = content.replace(\"\\\\n\", \"\\n\")\n lines = [line.strip() for line in content.split(\"\\n\")]\n content = \"\\n\".join(lines)\n\n role_emoji = \"🙋\" if role.lower() == \"user\" else \"🤖\"\n role_ja = \"ユーザー\" if role.lower() == \"user\" else \"アシスタント\"\n return f\"\"\"### {role_emoji} {role_ja}エージェント\n\n{content}\"\"\"\n\n for log in filtered_logs:\n formatted_messages = []\n # Try to extract message array\n messages_match = re.search(\n r\"Model (.*?), index (\\d+), processed these messages: (\\[.*\\])\", log\n )\n\n if messages_match:\n try:\n messages = json.loads(messages_match.group(3))\n for msg in messages:\n if msg.get(\"role\") in [\"user\", \"assistant\"]:\n formatted_msg = process_message(\n msg.get(\"role\"), msg.get(\"content\", \"\")\n )\n if formatted_msg:\n formatted_messages.append(formatted_msg)\n except json.JSONDecodeError:\n pass\n\n # If JSON parsing fails or no message array is found, try to extract conversation content directly\n if not formatted_messages:\n user_pattern = re.compile(r\"\\{'role': 'user', 'content': '(.*?)'\\}\")\n assistant_pattern = re.compile(\n r\"\\{'role': 'assistant', 'content': '(.*?)'\\}\"\n )\n\n for content in user_pattern.findall(log):\n formatted_msg = process_message(\"user\", content)\n if formatted_msg:\n formatted_messages.append(formatted_msg)\n\n for content in assistant_pattern.findall(log):\n formatted_msg = process_message(\"assistant\", content)\n if formatted_msg:\n formatted_messages.append(formatted_msg)\n\n if formatted_messages:\n simplified_logs.append(\"\\n\\n\".join(formatted_messages))\n\n # Format log output, ensure appropriate separation between each conversation record\n formatted_logs = []\n for i, log in enumerate(simplified_logs):\n # Remove excess whitespace characters from beginning and end\n log = log.strip()\n\n formatted_logs.append(log)\n\n # Ensure each conversation record ends with a newline\n if not log.endswith(\"\\n\"):\n formatted_logs.append(\"\\n\")\n\n return \"\\n\".join(formatted_logs)\n\n\n# モジュールの説明を含む辞書\nMODULE_DESCRIPTIONS = {\n \"run\": \"デフォルトモード: OpenAIモデルのデフォルトエージェント協力モードを使用し、ほとんどのタスクに適しています。\",\n \"run_mini\": \"最小限の設定でOpenAIモデルを使用してタスクを処理します\",\n \"run_deepseek_zh\": \"中国語タスクを処理するためにdeepseekモデルを使用します\",\n \"run_openai_compatible_model\": \"OpenAI互換モデルを使用してタスクを処理します\",\n \"run_ollama\": \"ローカルのollamaモデルを使用してタスクを処理します\",\n \"run_qwen_mini_zh\": \"最小限の設定でqwenモデルを使用してタスクを処理します\",\n \"run_qwen_zh\": \"qwenモデルを使用して中国語タスクを処理します\",\n \"run_azure_openai\": \"Azure OpenAIモデルを使用してタスクを処理します\",\n \"run_groq\": \"groqモデルを使用してタスクを処理します\",\n \"run_together_ai\": \"together aiモデルを使用してタスクを処理します\",\n}\n\n\n# デフォルトの環境変数テンプレート\nDEFAULT_ENV_TEMPLATE = \"\"\"#===========================================\n# モデル & API \n# (参照: https://docs.camel-ai.org/key_modules/models.html#)\n#===========================================\n\n# OPENAI API (https://platform.openai.com/api-keys)\nOPENAI_API_KEY='あなたのキー'\n# OPENAI_API_BASE_URL=\"\"\n\n# Azure OpenAI API\n# AZURE_OPENAI_BASE_URL=\"\"\n# AZURE_API_VERSION=\"\"\n# AZURE_OPENAI_API_KEY=\"\"\n# AZURE_DEPLOYMENT_NAME=\"\"\n\n\n# Qwen API (https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key)\nQWEN_API_KEY='あなたのキー'\n\n# DeepSeek API (https://platform.deepseek.com/api_keys)\nDEEPSEEK_API_KEY='あなたのキー'\n\n#===========================================\n# ツール & サービス API\n#===========================================\n\n# Google Search API (https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3)\nGOOGLE_API_KEY='あなたのキー'\nSEARCH_ENGINE_ID='あなたのID'\n\n# Chunkr API (https://chunkr.ai/)\nCHUNKR_API_KEY='あなたのキー'\n\n# Firecrawl API (https://www.firecrawl.dev/)\nFIRECRAWL_API_KEY='あなたのキー'\n#FIRECRAWL_API_URL=\"https://api.firecrawl.dev\"\n\"\"\"\n\n\ndef validate_input(question: str) -> bool:\n \"\"\"ユーザー入力が有効かどうかを検証\n\n 引数:\n question: ユーザーの質問\n\n 戻り値:\n bool: 入力が有効かどうか\n \"\"\"\n # 入力が空またはスペースのみかどうかをチェック\n if not question or question.strip() == \"\":\n return False\n return True\n\n\ndef run_owl(question: str, example_module: str) -> Tuple[str, str, str]:\n \"\"\"OWLシステムを実行して結果を返す\n\n 引数:\n question: ユーザーの質問\n example_module: インポートする例モジュール名(例:\"run_terminal_zh\"や\"run_deep\")\n\n 戻り値:\n Tuple[...]: 回答、トークン数、ステータス\n \"\"\"\n global CURRENT_PROCESS\n\n # Validate input\n if not validate_input(question):\n logging.warning(\"ユーザーが無効な入力を送信しました\")\n return (\n \"有効な質問を入力してください\",\n \"0\",\n \"❌ エラー: 無効な入力質問\",\n )\n\n try:\n # Ensure environment variables are loaded\n load_dotenv(find_dotenv(), override=True)\n logging.info(f\"質問を処理中: '{question}', モジュール使用: {example_module}\")\n\n # Check if the module is in MODULE_DESCRIPTIONS\n if example_module not in MODULE_DESCRIPTIONS:\n logging.error(\n f\"ユーザーがサポートされていないモジュールを選択しました: {example_module}\"\n )\n return (\n f\"選択されたモジュール '{example_module}' はサポートされていません\",\n \"0\",\n \"❌ エラー: サポートされていないモジュール\",\n )\n\n # Dynamically import target module\n module_path = f\"examples.{example_module}\"\n try:\n logging.info(f\"モジュールをインポート中: {module_path}\")\n module = importlib.import_module(module_path)\n except ImportError as ie:\n logging.error(f\"モジュール {module_path} をインポートできません: {str(ie)}\")\n return (\n f\"モジュールをインポートできません: {module_path}\",\n \"0\",\n f\"❌ エラー: モジュール {example_module} が存在しないか、読み込めません - {str(ie)}\",\n )\n except Exception as e:\n logging.error(\n f\"モジュール {module_path} のインポート中にエラーが発生しました: {str(e)}\"\n )\n return (\n f\"モジュールのインポート中にエラーが発生しました: {module_path}\",\n \"0\",\n f\"❌ エラー: {str(e)}\",\n )\n\n # Check if it contains the construct_society function\n if not hasattr(module, \"construct_society\"):\n logging.error(\n f\"construct_society 関数がモジュール {module_path} に見つかりません\"\n )\n return (\n f\"construct_society 関数がモジュール {module_path} に見つかりません\",\n \"0\",\n \"❌ エラー: モジュールインターフェースが互換性がありません\",\n )\n\n # Build society simulation\n try:\n logging.info(\"社会シミュレーションを構築中...\")\n society = module.construct_society(question)\n\n except Exception as e:\n logging.error(\n f\"社会シミュレーションの構築中にエラーが発生しました: {str(e)}\"\n )\n return (\n f\"社会シミュレーションの構築中にエラーが発生しました: {str(e)}\",\n \"0\",\n f\"❌ エラー: 構築に失敗しました - {str(e)}\",\n )\n\n # Run society simulation\n try:\n logging.info(\"社会シミュレーションを実行中...\")\n answer, chat_history, token_info = run_society(society)\n logging.info(\"社会シミュレーションが完了しました\")\n except Exception as e:\n logging.error(\n f\"社会シミュレーションの実行中にエラーが発生しました: {str(e)}\"\n )\n return (\n f\"社会シミュレーションの実行中にエラーが発生しました: {str(e)}\",\n \"0\",\n f\"❌ エラー: 実行に失敗しました - {str(e)}\",\n )\n\n # Safely get token count\n if not isinstance(token_info, dict):\n token_info = {}\n\n completion_tokens = token_info.get(\"completion_token_count\", 0)\n prompt_tokens = token_info.get(\"prompt_token_count\", 0)\n total_tokens = completion_tokens + prompt_tokens\n\n logging.info(\n f\"処理が完了しました、トークン使用量: 完了={completion_tokens}, プロンプト={prompt_tokens}, 合計={total_tokens}\"\n )\n\n return (\n answer,\n f\"完了トークン: {completion_tokens:,} | プロンプトトークン: {prompt_tokens:,} | 合計: {total_tokens:,}\",\n \"✅ 正常に完了しました\",\n )\n\n except Exception as e:\n logging.error(f\"質問の処理中に予期しないエラーが発生しました: {str(e)}\")\n return (f\"エラーが発生しました: {str(e)}\", \"0\", f\"❌ エラー: {str(e)}\")\n\n\ndef update_module_description(module_name: str) -> str:\n \"\"\"選択されたモジュールの説明を返す\"\"\"\n return MODULE_DESCRIPTIONS.get(module_name, \"説明はありません\")\n\n\n# フロントエンドから設定された環境変数を保存\nWEB_FRONTEND_ENV_VARS: dict[str, str] = {}\n\n\ndef init_env_file():\n \"\"\".envファイルが存在しない場合に初期化する\"\"\"\n dotenv_path = find_dotenv()\n if not dotenv_path:\n with open(\".env\", \"w\") as f:\n f.write(DEFAULT_ENV_TEMPLATE)\n dotenv_path = find_dotenv()\n return dotenv_path\n\n\ndef load_env_vars():\n \"\"\"環境変数を読み込み、辞書形式で返す\n\n 戻り値:\n dict: 環境変数辞書、各値は値とソースを含むタプル(value, source)\n \"\"\"\n dotenv_path = init_env_file()\n load_dotenv(dotenv_path, override=True)\n\n # .envファイルから環境変数を読み込む\n env_file_vars = {}\n with open(dotenv_path, \"r\") as f:\n for line in f:\n line = line.strip()\n if line and not line.startswith(\"#\"):\n if \"=\" in line:\n key, value = line.split(\"=\", 1)\n env_file_vars[key.strip()] = value.strip().strip(\"\\\"'\")\n\n # システム環境変数から取得\n system_env_vars = {\n k: v\n for k, v in os.environ.items()\n if k not in env_file_vars and k not in WEB_FRONTEND_ENV_VARS\n }\n\n # 環境変数をマージしてソースをマーク\n env_vars = {}\n\n # システム環境変数を追加(最低優先度)\n for key, value in system_env_vars.items():\n env_vars[key] = (value, \"システム\")\n\n # .envファイル環境変数を追加(中程度の優先度)\n for key, value in env_file_vars.items():\n env_vars[key] = (value, \".envファイル\")\n\n # フロントエンドで設定された環境変数を追加(最高優先度)\n for key, value in WEB_FRONTEND_ENV_VARS.items():\n env_vars[key] = (value, \"フロントエンド設定\")\n # オペレーティングシステムの環境変数も更新されていることを確認\n os.environ[key] = value\n\n return env_vars\n\n\ndef save_env_vars(env_vars):\n \"\"\"環境変数を.envファイルに保存\n\n 引数:\n env_vars: 辞書、キーは環境変数名、値は文字列または(value, source)タプル\n \"\"\"\n try:\n dotenv_path = init_env_file()\n\n # Save each environment variable\n for key, value_data in env_vars.items():\n if key and key.strip(): # Ensure key is not empty\n # Handle case where value might be a tuple\n if isinstance(value_data, tuple):\n value = value_data[0]\n else:\n value = value_data\n\n set_key(dotenv_path, key.strip(), value.strip())\n\n # Reload environment variables to ensure they take effect\n load_dotenv(dotenv_path, override=True)\n\n return True, \"環境変数が正常に保存されました!\"\n except Exception as e:\n return False, f\"環境変数の保存中にエラーが発生しました: {str(e)}\"\n\n\ndef add_env_var(key, value, from_frontend=True):\n \"\"\"単一の環境変数を追加または更新\n\n 引数:\n key: 環境変数名\n value: 環境変数値\n from_frontend: フロントエンド設定からかどうか、デフォルトはTrue\n \"\"\"\n try:\n if not key or not key.strip():\n return False, \"変数名は空にできません\"\n\n key = key.strip()\n value = value.strip()\n\n # If from frontend, add to frontend environment variable dictionary\n if from_frontend:\n WEB_FRONTEND_ENV_VARS[key] = value\n # Directly update system environment variables\n os.environ[key] = value\n\n # Also update .env file\n dotenv_path = init_env_file()\n set_key(dotenv_path, key, value)\n load_dotenv(dotenv_path, override=True)\n\n return True, f\"環境変数 {key} が正常に追加/更新されました!\"\n except Exception as e:\n return False, f\"環境変数の追加中にエラーが発生しました: {str(e)}\"\n\n\ndef delete_env_var(key):\n \"\"\"環境変数を削除\"\"\"\n try:\n if not key or not key.strip():\n return False, \"変数名は空にできません\"\n\n key = key.strip()\n\n # Delete from .env file\n dotenv_path = init_env_file()\n unset_key(dotenv_path, key)\n\n # Delete from frontend environment variable dictionary\n if key in WEB_FRONTEND_ENV_VARS:\n del WEB_FRONTEND_ENV_VARS[key]\n\n # Also delete from current process environment\n if key in os.environ:\n del os.environ[key]\n\n return True, f\"環境変数 {key} が正常に削除されました!\"\n except Exception as e:\n return False, f\"環境変数の削除中にエラーが発生しました: {str(e)}\"\n\n\ndef is_api_related(key: str) -> bool:\n \"\"\"環境変数がAPI関連かどうかを判断\n\n 引数:\n key: 環境変数名\n\n 戻り値:\n bool: API関連かどうか\n \"\"\"\n # API関連キーワード\n api_keywords = [\n \"api\",\n \"key\",\n \"token\",\n \"secret\",\n \"password\",\n \"openai\",\n \"qwen\",\n \"deepseek\",\n \"google\",\n \"search\",\n \"hf\",\n \"hugging\",\n \"chunkr\",\n \"firecrawl\",\n ]\n\n # API関連キーワードが含まれているか確認(大文字小文字を区別しない)\n return any(keyword in key.lower() for keyword in api_keywords)\n\n\ndef get_api_guide(key: str) -> str:\n \"\"\"環境変数名に基づいて対応するAPIガイドを返す\n\n 引数:\n key: 環境変数名\n\n 戻り値:\n str: APIガイドリンクまたは説明\n \"\"\"\n key_lower = key.lower()\n if \"openai\" in key_lower:\n return \"https://platform.openai.com/api-keys\"\n elif \"qwen\" in key_lower or \"dashscope\" in key_lower:\n return \"https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key\"\n elif \"deepseek\" in key_lower:\n return \"https://platform.deepseek.com/api_keys\"\n elif \"google\" in key_lower:\n return \"https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3\"\n elif \"search_engine_id\" in key_lower:\n return \"https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3\"\n elif \"chunkr\" in key_lower:\n return \"https://chunkr.ai/\"\n elif \"firecrawl\" in key_lower:\n return \"https://www.firecrawl.dev/\"\n else:\n return \"\"\n\n\ndef update_env_table():\n \"\"\"環境変数テーブル表示を更新し、API関連の環境変数のみを表示\"\"\"\n env_vars = load_env_vars()\n # Filter out API-related environment variables\n api_env_vars = {k: v for k, v in env_vars.items() if is_api_related(k)}\n # Convert to list format to meet Gradio Dataframe requirements\n # Format: [Variable name, Variable value, Guide link]\n result = []\n for k, v in api_env_vars.items():\n guide = get_api_guide(k)\n # If there's a guide link, create a clickable link\n guide_link = (\n f\"🔗 取得\"\n if guide\n else \"\"\n )\n result.append([k, v[0], guide_link])\n return result\n\n\ndef save_env_table_changes(data):\n \"\"\"環境変数テーブルへの変更を保存\n\n 引数:\n data: データフレームデータ、おそらくpandas DataFrameオブジェクト\n\n 戻り値:\n str: 操作ステータス情報、HTML形式のステータスメッセージを含む\n \"\"\"\n try:\n logging.info(f\"環境変数テーブルデータの処理を開始します、タイプ: {type(data)}\")\n\n # Get all current environment variables\n current_env_vars = load_env_vars()\n processed_keys = set() # Record processed keys to detect deleted variables\n\n # Process pandas DataFrame object\n import pandas as pd\n\n if isinstance(data, pd.DataFrame):\n # Get column name information\n columns = data.columns.tolist()\n logging.info(f\"DataFrameの列名: {columns}\")\n\n # Iterate through each row of the DataFrame\n for index, row in data.iterrows():\n # Use column names to access data\n if len(columns) >= 3:\n # Get variable name and value (column 0 is name, column 1 is value)\n key = row[0] if isinstance(row, pd.Series) else row.iloc[0]\n value = row[1] if isinstance(row, pd.Series) else row.iloc[1]\n\n # Check if it's an empty row or deleted variable\n if (\n key and str(key).strip()\n ): # If key name is not empty, add or update\n logging.info(f\"環境変数の処理: {key} = {value}\")\n add_env_var(key, str(value))\n processed_keys.add(key)\n # Process other formats\n elif isinstance(data, dict):\n logging.info(f\"辞書形式データのキー: {list(data.keys())}\")\n # If dictionary format, try different keys\n if \"data\" in data:\n rows = data[\"data\"]\n elif \"values\" in data:\n rows = data[\"values\"]\n elif \"value\" in data:\n rows = data[\"value\"]\n else:\n # Try using dictionary directly as row data\n rows = []\n for key, value in data.items():\n if key not in [\"headers\", \"types\", \"columns\"]:\n rows.append([key, value])\n\n if isinstance(rows, list):\n for row in rows:\n if isinstance(row, list) and len(row) >= 2:\n key, value = row[0], row[1]\n if key and str(key).strip():\n add_env_var(key, str(value))\n processed_keys.add(key)\n elif isinstance(data, list):\n # 列表格式\n for row in data:\n if isinstance(row, list) and len(row) >= 2:\n key, value = row[0], row[1]\n if key and str(key).strip():\n add_env_var(key, str(value))\n processed_keys.add(key)\n else:\n logging.error(f\"不明なデータ形式: {type(data)}\")\n return f\"❌ 保存に失敗しました: 不明なデータ形式 {type(data)}\"\n\n # Process deleted variables - check if there are variables in current environment not appearing in the table\n api_related_keys = {k for k in current_env_vars.keys() if is_api_related(k)}\n keys_to_delete = api_related_keys - processed_keys\n\n # Delete variables no longer in the table\n for key in keys_to_delete:\n logging.info(f\"環境変数の削除: {key}\")\n delete_env_var(key)\n\n return \"✅ 環境変数が正常に保存されました\"\n except Exception as e:\n import traceback\n\n error_details = traceback.format_exc()\n logging.error(\n f\"環境変数の保存中にエラーが発生しました: {str(e)}\\n{error_details}\"\n )\n return f\"❌ 保存に失敗しました: {str(e)}\"\n\n\ndef get_env_var_value(key):\n \"\"\"環境変数の実際の値を取得\n\n 優先順位: フロントエンド設定 > .envファイル > システム環境変数\n \"\"\"\n # Check frontend configured environment variables\n if key in WEB_FRONTEND_ENV_VARS:\n return WEB_FRONTEND_ENV_VARS[key]\n\n # Check system environment variables (including those loaded from .env)\n return os.environ.get(key, \"\")\n\n\ndef create_ui():\n \"\"\"拡張されたGradioインターフェースを作成\"\"\"\n\n def clear_log_file():\n \"\"\"ログファイルの内容をクリア\"\"\"\n try:\n if LOG_FILE and os.path.exists(LOG_FILE):\n # Clear log file content instead of deleting the file\n open(LOG_FILE, \"w\").close()\n logging.info(\"ログファイルがクリアされました\")\n # Clear log queue\n while not LOG_QUEUE.empty():\n try:\n LOG_QUEUE.get_nowait()\n except queue.Empty:\n break\n return \"\"\n else:\n return \"\"\n except Exception as e:\n logging.error(f\"ログファイルのクリア中にエラーが発生しました: {str(e)}\")\n return \"\"\n\n # リアルタイムログ更新関数を作成\n def process_with_live_logs(question, module_name):\n \"\"\"質問を処理し、リアルタイムでログを更新\"\"\"\n global CURRENT_PROCESS\n\n # Clear log file\n clear_log_file()\n\n # 質問を処理するバックグラウンドスレッドを作成\n result_queue = queue.Queue()\n\n def process_in_background():\n try:\n result = run_owl(question, module_name)\n result_queue.put(result)\n except Exception as e:\n result_queue.put(\n (f\"エラーが発生しました: {str(e)}\", \"0\", f\"❌ エラー: {str(e)}\")\n )\n\n # バックグラウンド処理スレッドを開始\n bg_thread = threading.Thread(target=process_in_background)\n CURRENT_PROCESS = bg_thread # 現在のプロセスを記録\n bg_thread.start()\n\n # 処理が完了するのを待つ間、1秒ごとにログを更新\n while bg_thread.is_alive():\n # 会話記録表示を更新\n logs2 = get_latest_logs(100, LOG_QUEUE)\n\n # Always update status\n yield (\n \"0\",\n \" 処理中...\",\n logs2,\n )\n\n time.sleep(1)\n\n # Processing complete, get results\n if not result_queue.empty():\n result = result_queue.get()\n answer, token_count, status = result\n\n # Final update of conversation record\n logs2 = get_latest_logs(100, LOG_QUEUE)\n\n # Set different indicators based on status\n if \"エラー\" in status:\n status_with_indicator = (\n f\" {status}\"\n )\n else:\n status_with_indicator = (\n f\" {status}\"\n )\n\n yield token_count, status_with_indicator, logs2\n else:\n logs2 = get_latest_logs(100, LOG_QUEUE)\n yield (\n \"0\",\n \" 終了しました\",\n logs2,\n )\n\n with gr.Blocks(title=\"OWL\", theme=gr.themes.Soft(primary_hue=\"blue\")) as app:\n gr.Markdown(\n \"\"\"\n # 🦉 OWL マルチエージェント協力システム\n\n CAMELフレームワークをベースに開発された高度なマルチエージェント協力システムで、エージェント協力を通じて複雑な問題を解決するように設計されています。\n\n モデルやツールはローカルスクリプトを変更することでカスタマイズできます。\n \n このウェブアプリは現在ベータ開発中です。デモンストレーションとテスト目的のみで提供されており、本番環境での使用はまだ推奨されていません。\n \"\"\"\n )\n\n # Add custom CSS\n gr.HTML(\"\"\"\n \n \"\"\")\n\n with gr.Row():\n with gr.Column(scale=0.5):\n question_input = gr.Textbox(\n lines=5,\n placeholder=\"質問を入力してください...\",\n label=\"質問\",\n elem_id=\"question_input\",\n show_copy_button=True,\n value=\"Googleで検索して、camel-aiのcamelフレームワークのGitHubスター数、フォーク数などを要約し、その数値をplotパッケージを使ってPythonファイルに書き込み、ローカルに保存して、生成したPythonファイルを実行してください。\",\n )\n\n # Enhanced module selection dropdown\n # Only includes modules defined in MODULE_DESCRIPTIONS\n module_dropdown = gr.Dropdown(\n choices=list(MODULE_DESCRIPTIONS.keys()),\n value=\"run\",\n label=\"機能モジュールを選択\",\n interactive=True,\n )\n\n # Module description text box\n module_description = gr.Textbox(\n value=MODULE_DESCRIPTIONS[\"run\"],\n label=\"モジュールの説明\",\n interactive=False,\n elem_classes=\"module-info\",\n )\n\n with gr.Row():\n run_button = gr.Button(\n \"実行\", variant=\"primary\", elem_classes=\"primary\"\n )\n\n status_output = gr.HTML(\n value=\" 準備完了\",\n label=\"ステータス\",\n )\n token_count_output = gr.Textbox(\n label=\"トークン数\", interactive=False, elem_classes=\"token-count\"\n )\n\n # Example questions\n examples = [\n \"Googleで検索して、camel-aiのcamelフレームワークのGitHubスター数、フォーク数などを要約し、その数値をplotパッケージを使ってPythonファイルに書き込み、ローカルに保存して、生成したPythonファイルを実行してください。\",\n \"Amazonを閲覧して、プログラマーに魅力的な商品を見つけてください。商品名と価格を提供してください\",\n \"Hello worldを表示するPythonファイルを作成し、ローカルに保存してください\",\n ]\n\n gr.Examples(examples=examples, inputs=question_input)\n\n gr.HTML(\"\"\"\n
\n

OWLマルチエージェント協力システムについて

\n

OWLはCAMELフレームワークをベースに開発された高度なマルチエージェント協力システムで、エージェント協力を通じて複雑な問題を解決するように設計されています。

\n

© 2025 CAMEL-AI.org. Apache License 2.0オープンソースライセンスに基づいています

\n

GitHub

\n
\n \"\"\")\n\n with gr.Tabs(): # Set conversation record as the default selected tab\n with gr.TabItem(\"会話記録\"):\n # Add conversation record display area\n with gr.Group():\n log_display2 = gr.Markdown(\n value=\"まだ会話記録はありません。\",\n elem_classes=\"log-display\",\n )\n\n with gr.Row():\n refresh_logs_button2 = gr.Button(\"記録を更新\")\n auto_refresh_checkbox2 = gr.Checkbox(\n label=\"自動更新\", value=True, interactive=True\n )\n clear_logs_button2 = gr.Button(\n \"記録をクリア\", variant=\"secondary\"\n )\n\n with gr.TabItem(\"環境変数管理\", id=\"env-settings\"):\n with gr.Group(elem_classes=\"env-manager-container\"):\n gr.Markdown(\"\"\"\n ## 環境変数管理\n \n ここでモデルAPIキーやその他のサービス認証情報を設定します。この情報はローカルの`.env`ファイルに保存され、APIキーが安全に保存され、ネットワークにアップロードされないことを保証します。APIキーを正しく設定することは、OWLシステムの機能にとって非常に重要です。環境変数はツールの要件に応じて柔軟に設定できます。\n \"\"\")\n\n # Main content divided into two-column layout\n with gr.Row():\n # Left column: Environment variable management controls\n with gr.Column(scale=3):\n with gr.Group(elem_classes=\"env-controls\"):\n # Environment variable table - set to interactive for direct editing\n gr.Markdown(\"\"\"\n
\n ヒント: cp .env_template .env を実行してローカルの.envファイルを作成し、実行モジュールに応じて必要な環境変数を柔軟に設定してください\n
\n \"\"\")\n\n # Enhanced environment variable table, supporting adding and deleting rows\n env_table = gr.Dataframe(\n headers=[\n \"変数名\",\n \"値\",\n \"取得ガイド\",\n ],\n datatype=[\n \"str\",\n \"str\",\n \"html\",\n ], # Set the last column as HTML type to support links\n row_count=10, # Increase row count to allow adding new variables\n col_count=(3, \"fixed\"),\n value=update_env_table,\n label=\"APIキーと環境変数\",\n interactive=True, # Set as interactive, allowing direct editing\n elem_classes=\"env-table\",\n )\n\n # Operation instructions\n gr.Markdown(\n \"\"\"\n
\n 操作ガイド:\n \n
\n \"\"\",\n elem_classes=\"env-instructions\",\n )\n\n # Environment variable operation buttons\n with gr.Row(elem_classes=\"env-buttons\"):\n save_env_button = gr.Button(\n \"💾 変更を保存\",\n variant=\"primary\",\n elem_classes=\"env-button\",\n )\n refresh_button = gr.Button(\n \"🔄 リストを更新\", elem_classes=\"env-button\"\n )\n\n # Status display\n env_status = gr.HTML(\n label=\"操作ステータス\",\n value=\"\",\n elem_classes=\"env-status\",\n )\n\n # 連接事件処理函数\n save_env_button.click(\n fn=save_env_table_changes,\n inputs=[env_table],\n outputs=[env_status],\n ).then(fn=update_env_table, outputs=[env_table])\n\n refresh_button.click(fn=update_env_table, outputs=[env_table])\n\n # Set up event handling\n run_button.click(\n fn=process_with_live_logs,\n inputs=[question_input, module_dropdown],\n outputs=[token_count_output, status_output, log_display2],\n )\n\n # Module selection updates description\n module_dropdown.change(\n fn=update_module_description,\n inputs=module_dropdown,\n outputs=module_description,\n )\n\n # Conversation record related event handling\n refresh_logs_button2.click(\n fn=lambda: get_latest_logs(100, LOG_QUEUE), outputs=[log_display2]\n )\n\n clear_logs_button2.click(fn=clear_log_file, outputs=[log_display2])\n\n # Auto refresh control\n def toggle_auto_refresh(enabled):\n if enabled:\n return gr.update(every=3)\n else:\n return gr.update(every=0)\n\n auto_refresh_checkbox2.change(\n fn=toggle_auto_refresh,\n inputs=[auto_refresh_checkbox2],\n outputs=[log_display2],\n )\n\n # No longer automatically refresh logs by default\n\n return app\n\n\n# メイン関数\ndef main():\n try:\n # ロギングシステムを初期化\n global LOG_FILE\n LOG_FILE = setup_logging()\n logging.info(\"OWL Webアプリケーションが開始されました\")\n\n # ログ読み取りスレッドを開始\n log_thread = threading.Thread(\n target=log_reader_thread, args=(LOG_FILE,), daemon=True\n )\n log_thread.start()\n logging.info(\"ログ読み取りスレッドが開始されました\")\n\n # .envファイルを初期化(存在しない場合)\n init_env_file()\n app = create_ui()\n\n app.queue()\n app.launch(\n share=False,\n favicon_path=os.path.join(\n os.path.dirname(__file__), \"assets\", \"owl-favicon.ico\"\n ),\n )\n except Exception as e:\n logging.error(f\"アプリケーションの起動中にエラーが発生しました: {str(e)}\")\n print(f\"アプリケーションの起動中にエラーが発生しました: {str(e)}\")\n import traceback\n\n traceback.print_exc()\n\n finally:\n # ログスレッドが停止することを確認\n STOP_LOG_THREAD.set()\n STOP_REQUESTED.set()\n logging.info(\"アプリケーションが終了しました\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/owl/webapp_zh.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Import from the correct module path\nfrom utils import run_society\nimport os\nimport gradio as gr\nimport time\nimport json\nimport logging\nimport datetime\nfrom typing import Tuple\nimport importlib\nfrom dotenv import load_dotenv, set_key, find_dotenv, unset_key\nimport threading\nimport queue\nimport re # For regular expression operations\n\nos.environ[\"PYTHONIOENCODING\"] = \"utf-8\"\n\n\n# 配置日志系统\ndef setup_logging():\n \"\"\"配置日志系统,将日志输出到文件和内存队列以及控制台\"\"\"\n # 创建logs目录(如果不存在)\n logs_dir = os.path.join(os.path.dirname(__file__), \"logs\")\n os.makedirs(logs_dir, exist_ok=True)\n\n # 生成日志文件名(使用当前日期)\n current_date = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n log_file = os.path.join(logs_dir, f\"gradio_log_{current_date}.txt\")\n\n # 配置根日志记录器(捕获所有日志)\n root_logger = logging.getLogger()\n\n # 清除现有的处理器,避免重复日志\n for handler in root_logger.handlers[:]:\n root_logger.removeHandler(handler)\n\n root_logger.setLevel(logging.INFO)\n\n # 创建文件处理器\n file_handler = logging.FileHandler(log_file, encoding=\"utf-8\", mode=\"a\")\n file_handler.setLevel(logging.INFO)\n\n # 创建控制台处理器\n console_handler = logging.StreamHandler()\n console_handler.setLevel(logging.INFO)\n\n # 创建格式化器\n formatter = logging.Formatter(\n \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n )\n file_handler.setFormatter(formatter)\n console_handler.setFormatter(formatter)\n\n # 添加处理器到根日志记录器\n root_logger.addHandler(file_handler)\n root_logger.addHandler(console_handler)\n\n logging.info(\"日志系统已初始化,日志文件: %s\", log_file)\n return log_file\n\n\n# 全局变量\nLOG_FILE = None\nLOG_QUEUE: queue.Queue = queue.Queue() # 日志队列\nSTOP_LOG_THREAD = threading.Event()\nCURRENT_PROCESS = None # 用于跟踪当前运行的进程\nSTOP_REQUESTED = threading.Event() # 用于标记是否请求停止\n\n\n# 日志读取和更新函数\ndef log_reader_thread(log_file):\n \"\"\"后台线程,持续读取日志文件并将新行添加到队列中\"\"\"\n try:\n with open(log_file, \"r\", encoding=\"utf-8\") as f:\n # 移动到文件末尾\n f.seek(0, 2)\n\n while not STOP_LOG_THREAD.is_set():\n line = f.readline()\n if line:\n LOG_QUEUE.put(line) # 添加到对话记录队列\n else:\n # 没有新行,等待一小段时间\n time.sleep(0.1)\n except Exception as e:\n logging.error(f\"日志读取线程出错: {str(e)}\")\n\n\ndef get_latest_logs(max_lines=100, queue_source=None):\n \"\"\"从队列中获取最新的日志行,如果队列为空则直接从文件读取\n\n Args:\n max_lines: 最大返回行数\n queue_source: 指定使用哪个队列,默认为LOG_QUEUE\n\n Returns:\n str: 日志内容\n \"\"\"\n logs = []\n log_queue = queue_source if queue_source else LOG_QUEUE\n\n # 创建一个临时队列来存储日志,以便我们可以处理它们而不会从原始队列中删除它们\n temp_queue = queue.Queue()\n temp_logs = []\n\n try:\n # 尝试从队列中获取所有可用的日志行\n while not log_queue.empty() and len(temp_logs) < max_lines:\n log = log_queue.get_nowait()\n temp_logs.append(log)\n temp_queue.put(log) # 将日志放回临时队列\n except queue.Empty:\n pass\n\n # 处理对话记录\n logs = temp_logs\n\n # 如果没有新日志或日志不足,尝试直接从文件读取最后几行\n if len(logs) < max_lines and LOG_FILE and os.path.exists(LOG_FILE):\n try:\n with open(LOG_FILE, \"r\", encoding=\"utf-8\") as f:\n all_lines = f.readlines()\n # 如果队列中已有一些日志,只读取剩余需要的行数\n remaining_lines = max_lines - len(logs)\n file_logs = (\n all_lines[-remaining_lines:]\n if len(all_lines) > remaining_lines\n else all_lines\n )\n\n # 将文件日志添加到队列日志之前\n logs = file_logs + logs\n except Exception as e:\n error_msg = f\"读取日志文件出错: {str(e)}\"\n logging.error(error_msg)\n if not logs: # 只有在没有任何日志的情况下才添加错误消息\n logs = [error_msg]\n\n # 如果仍然没有日志,返回提示信息\n if not logs:\n return \"初始化运行中...\"\n\n # 过滤日志,只保留 camel.agents.chat_agent - INFO 的日志\n filtered_logs = []\n for log in logs:\n if \"camel.agents.chat_agent - INFO\" in log:\n filtered_logs.append(log)\n\n # 如果过滤后没有日志,返回提示信息\n if not filtered_logs:\n return \"暂无对话记录。\"\n\n # 处理日志内容,提取最新的用户和助手消息\n simplified_logs = []\n\n # 使用集合来跟踪已经处理过的消息,避免重复\n processed_messages = set()\n\n def process_message(role, content):\n # 创建一个唯一标识符来跟踪消息\n msg_id = f\"{role}:{content}\"\n if msg_id in processed_messages:\n return None\n\n processed_messages.add(msg_id)\n content = content.replace(\"\\\\n\", \"\\n\")\n lines = [line.strip() for line in content.split(\"\\n\")]\n content = \"\\n\".join(lines)\n\n role_emoji = \"🙋\" if role.lower() == \"user\" else \"🤖\"\n return f\"\"\"### {role_emoji} {role.title()} Agent\n\n{content}\"\"\"\n\n for log in filtered_logs:\n formatted_messages = []\n # 尝试提取消息数组\n messages_match = re.search(\n r\"Model (.*?), index (\\d+), processed these messages: (\\[.*\\])\", log\n )\n\n if messages_match:\n try:\n messages = json.loads(messages_match.group(3))\n for msg in messages:\n if msg.get(\"role\") in [\"user\", \"assistant\"]:\n formatted_msg = process_message(\n msg.get(\"role\"), msg.get(\"content\", \"\")\n )\n if formatted_msg:\n formatted_messages.append(formatted_msg)\n except json.JSONDecodeError:\n pass\n\n # 如果JSON解析失败或没有找到消息数组,尝试直接提取对话内容\n if not formatted_messages:\n user_pattern = re.compile(r\"\\{'role': 'user', 'content': '(.*?)'\\}\")\n assistant_pattern = re.compile(\n r\"\\{'role': 'assistant', 'content': '(.*?)'\\}\"\n )\n\n for content in user_pattern.findall(log):\n formatted_msg = process_message(\"user\", content)\n if formatted_msg:\n formatted_messages.append(formatted_msg)\n\n for content in assistant_pattern.findall(log):\n formatted_msg = process_message(\"assistant\", content)\n if formatted_msg:\n formatted_messages.append(formatted_msg)\n\n if formatted_messages:\n simplified_logs.append(\"\\n\\n\".join(formatted_messages))\n\n # 格式化日志输出,确保每个对话记录之间有适当的分隔\n formatted_logs = []\n for i, log in enumerate(simplified_logs):\n # 移除开头和结尾的多余空白字符\n log = log.strip()\n\n formatted_logs.append(log)\n\n # 确保每个对话记录以换行符结束\n if not log.endswith(\"\\n\"):\n formatted_logs.append(\"\\n\")\n\n return \"\\n\".join(formatted_logs)\n\n\n# Dictionary containing module descriptions\nMODULE_DESCRIPTIONS = {\n \"run\": \"默认模式:使用OpenAI模型的默认的智能体协作模式,适合大多数任务。\",\n \"run_mini\": \"使用使用OpenAI模型最小化配置处理任务\",\n \"run_gemini\": \"使用 Gemini模型处理任务\",\n \"run_claude\": \"使用 Claude模型处理任务\",\n \"run_deepseek_zh\": \"使用eepseek模型处理中文任务\",\n \"run_openai_compatible_model\": \"使用openai兼容模型处理任务\",\n \"run_ollama\": \"使用本地ollama模型处理任务\",\n \"run_qwen_mini_zh\": \"使用qwen模型最小化配置处理任务\",\n \"run_qwen_zh\": \"使用qwen模型处理任务\",\n \"run_azure_openai\": \"使用azure openai模型处理任务\",\n \"run_groq\": \"使用groq模型处理任务\",\n \"run_ppio\": \"使用ppio模型处理任务\",\n \"run_together_ai\": \"使用together ai模型处理任务\",\n \"run_novita_ai\": \"使用novita ai模型处理任务\",\n}\n\n\n# 默认环境变量模板\nDEFAULT_ENV_TEMPLATE = \"\"\"#===========================================\n# MODEL & API \n# (See https://docs.camel-ai.org/key_modules/models.html#)\n#===========================================\n\n# OPENAI API (https://platform.openai.com/api-keys)\nOPENAI_API_KEY='Your_Key'\n# OPENAI_API_BASE_URL=\"\"\n\n# Azure OpenAI API\n# AZURE_OPENAI_BASE_URL=\"\"\n# AZURE_API_VERSION=\"\"\n# AZURE_OPENAI_API_KEY=\"\"\n# AZURE_DEPLOYMENT_NAME=\"\"\n\n\n# Qwen API (https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key)\nQWEN_API_KEY='Your_Key'\n\n# DeepSeek API (https://platform.deepseek.com/api_keys)\nDEEPSEEK_API_KEY='Your_Key'\n\n#===========================================\n# Tools & Services API\n#===========================================\n\n# Google Search API (https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3)\nGOOGLE_API_KEY='Your_Key'\nSEARCH_ENGINE_ID='Your_ID'\n\n# Chunkr API (https://chunkr.ai/)\nCHUNKR_API_KEY='Your_Key'\n\n# Firecrawl API (https://www.firecrawl.dev/)\nFIRECRAWL_API_KEY='Your_Key'\n#FIRECRAWL_API_URL=\"https://api.firecrawl.dev\"\n\"\"\"\n\n\ndef validate_input(question: str) -> bool:\n \"\"\"验证用户输入是否有效\n\n Args:\n question: 用户问题\n\n Returns:\n bool: 输入是否有效\n \"\"\"\n # 检查输入是否为空或只包含空格\n if not question or question.strip() == \"\":\n return False\n return True\n\n\ndef run_owl(question: str, example_module: str) -> Tuple[str, str, str]:\n \"\"\"运行OWL系统并返回结果\n\n Args:\n question: 用户问题\n example_module: 要导入的示例模块名(如 \"run_terminal_zh\" 或 \"run_deep\")\n\n Returns:\n Tuple[...]: 回答、令牌计数、状态\n \"\"\"\n global CURRENT_PROCESS\n\n # 验证输入\n if not validate_input(question):\n logging.warning(\"用户提交了无效的输入\")\n return (\"请输入有效的问题\", \"0\", \"❌ 错误: 输入问题无效\")\n\n try:\n # 确保环境变量已加载\n load_dotenv(find_dotenv(), override=True)\n logging.info(f\"处理问题: '{question}', 使用模块: {example_module}\")\n\n # 检查模块是否在MODULE_DESCRIPTIONS中\n if example_module not in MODULE_DESCRIPTIONS:\n logging.error(f\"用户选择了不支持的模块: {example_module}\")\n return (\n f\"所选模块 '{example_module}' 不受支持\",\n \"0\",\n \"❌ 错误: 不支持的模块\",\n )\n\n # 动态导入目标模块\n module_path = f\"examples.{example_module}\"\n try:\n logging.info(f\"正在导入模块: {module_path}\")\n module = importlib.import_module(module_path)\n except ImportError as ie:\n logging.error(f\"无法导入模块 {module_path}: {str(ie)}\")\n return (\n f\"无法导入模块: {module_path}\",\n \"0\",\n f\"❌ 错误: 模块 {example_module} 不存在或无法加载 - {str(ie)}\",\n )\n except Exception as e:\n logging.error(f\"导入模块 {module_path} 时发生错误: {str(e)}\")\n return (f\"导入模块时发生错误: {module_path}\", \"0\", f\"❌ 错误: {str(e)}\")\n\n # 检查是否包含construct_society函数\n if not hasattr(module, \"construct_society\"):\n logging.error(f\"模块 {module_path} 中未找到 construct_society 函数\")\n return (\n f\"模块 {module_path} 中未找到 construct_society 函数\",\n \"0\",\n \"❌ 错误: 模块接口不兼容\",\n )\n\n # 构建社会模拟\n try:\n logging.info(\"正在构建社会模拟...\")\n society = module.construct_society(question)\n\n except Exception as e:\n logging.error(f\"构建社会模拟时发生错误: {str(e)}\")\n return (\n f\"构建社会模拟时发生错误: {str(e)}\",\n \"0\",\n f\"❌ 错误: 构建失败 - {str(e)}\",\n )\n\n # 运行社会模拟\n try:\n logging.info(\"正在运行社会模拟...\")\n answer, chat_history, token_info = run_society(society)\n logging.info(\"社会模拟运行完成\")\n except Exception as e:\n logging.error(f\"运行社会模拟时发生错误: {str(e)}\")\n return (\n f\"运行社会模拟时发生错误: {str(e)}\",\n \"0\",\n f\"❌ 错误: 运行失败 - {str(e)}\",\n )\n\n # 安全地获取令牌计数\n if not isinstance(token_info, dict):\n token_info = {}\n\n completion_tokens = token_info.get(\"completion_token_count\", 0)\n prompt_tokens = token_info.get(\"prompt_token_count\", 0)\n total_tokens = completion_tokens + prompt_tokens\n\n logging.info(\n f\"处理完成,令牌使用: 完成={completion_tokens}, 提示={prompt_tokens}, 总计={total_tokens}\"\n )\n\n return (\n answer,\n f\"完成令牌: {completion_tokens:,} | 提示令牌: {prompt_tokens:,} | 总计: {total_tokens:,}\",\n \"✅ 成功完成\",\n )\n\n except Exception as e:\n logging.error(f\"处理问题时发生未捕获的错误: {str(e)}\")\n return (f\"发生错误: {str(e)}\", \"0\", f\"❌ 错误: {str(e)}\")\n\n\ndef update_module_description(module_name: str) -> str:\n \"\"\"返回所选模块的描述\"\"\"\n return MODULE_DESCRIPTIONS.get(module_name, \"无可用描述\")\n\n\n# 存储前端配置的环境变量\nWEB_FRONTEND_ENV_VARS: dict[str, str] = {}\n\n\ndef init_env_file():\n \"\"\"初始化.env文件如果不存在\"\"\"\n dotenv_path = find_dotenv()\n if not dotenv_path:\n with open(\".env\", \"w\") as f:\n f.write(DEFAULT_ENV_TEMPLATE)\n dotenv_path = find_dotenv()\n return dotenv_path\n\n\ndef load_env_vars():\n \"\"\"加载环境变量并返回字典格式\n\n Returns:\n dict: 环境变量字典,每个值为一个包含值和来源的元组 (value, source)\n \"\"\"\n dotenv_path = init_env_file()\n load_dotenv(dotenv_path, override=True)\n\n # 从.env文件读取环境变量\n env_file_vars = {}\n with open(dotenv_path, \"r\") as f:\n for line in f:\n line = line.strip()\n if line and not line.startswith(\"#\"):\n if \"=\" in line:\n key, value = line.split(\"=\", 1)\n env_file_vars[key.strip()] = value.strip().strip(\"\\\"'\")\n\n # 从系统环境变量中获取\n system_env_vars = {\n k: v\n for k, v in os.environ.items()\n if k not in env_file_vars and k not in WEB_FRONTEND_ENV_VARS\n }\n\n # 合并环境变量,并标记来源\n env_vars = {}\n\n # 添加系统环境变量(最低优先级)\n for key, value in system_env_vars.items():\n env_vars[key] = (value, \"系统\")\n\n # 添加.env文件环境变量(中等优先级)\n for key, value in env_file_vars.items():\n env_vars[key] = (value, \".env文件\")\n\n # 添加前端配置的环境变量(最高优先级)\n for key, value in WEB_FRONTEND_ENV_VARS.items():\n env_vars[key] = (value, \"前端配置\")\n # 确保操作系统环境变量也被更新\n os.environ[key] = value\n\n return env_vars\n\n\ndef save_env_vars(env_vars):\n \"\"\"保存环境变量到.env文件\n\n Args:\n env_vars: 字典,键为环境变量名,值可以是字符串或(值,来源)元组\n \"\"\"\n try:\n dotenv_path = init_env_file()\n\n # 保存每个环境变量\n for key, value_data in env_vars.items():\n if key and key.strip(): # 确保键不为空\n # 处理值可能是元组的情况\n if isinstance(value_data, tuple):\n value = value_data[0]\n else:\n value = value_data\n\n set_key(dotenv_path, key.strip(), value.strip())\n\n # 重新加载环境变量以确保生效\n load_dotenv(dotenv_path, override=True)\n\n return True, \"环境变量已成功保存!\"\n except Exception as e:\n return False, f\"保存环境变量时出错: {str(e)}\"\n\n\ndef add_env_var(key, value, from_frontend=True):\n \"\"\"添加或更新单个环境变量\n\n Args:\n key: 环境变量名\n value: 环境变量值\n from_frontend: 是否来自前端配置,默认为True\n \"\"\"\n try:\n if not key or not key.strip():\n return False, \"变量名不能为空\"\n\n key = key.strip()\n value = value.strip()\n\n # 如果来自前端,则添加到前端环境变量字典\n if from_frontend:\n WEB_FRONTEND_ENV_VARS[key] = value\n # 直接更新系统环境变量\n os.environ[key] = value\n\n # 同时更新.env文件\n dotenv_path = init_env_file()\n set_key(dotenv_path, key, value)\n load_dotenv(dotenv_path, override=True)\n\n return True, f\"环境变量 {key} 已成功添加/更新!\"\n except Exception as e:\n return False, f\"添加环境变量时出错: {str(e)}\"\n\n\ndef delete_env_var(key):\n \"\"\"删除环境变量\"\"\"\n try:\n if not key or not key.strip():\n return False, \"变量名不能为空\"\n\n key = key.strip()\n\n # 从.env文件中删除\n dotenv_path = init_env_file()\n unset_key(dotenv_path, key)\n\n # 从前端环境变量字典中删除\n if key in WEB_FRONTEND_ENV_VARS:\n del WEB_FRONTEND_ENV_VARS[key]\n\n # 从当前进程环境中也删除\n if key in os.environ:\n del os.environ[key]\n\n return True, f\"环境变量 {key} 已成功删除!\"\n except Exception as e:\n return False, f\"删除环境变量时出错: {str(e)}\"\n\n\ndef is_api_related(key: str) -> bool:\n \"\"\"判断环境变量是否与API相关\n\n Args:\n key: 环境变量名\n\n Returns:\n bool: 是否与API相关\n \"\"\"\n # API相关的关键词\n api_keywords = [\n \"api\",\n \"key\",\n \"token\",\n \"secret\",\n \"password\",\n \"openai\",\n \"qwen\",\n \"deepseek\",\n \"google\",\n \"search\",\n \"hf\",\n \"hugging\",\n \"chunkr\",\n \"firecrawl\",\n ]\n\n # 检查是否包含API相关关键词(不区分大小写)\n return any(keyword in key.lower() for keyword in api_keywords)\n\n\ndef get_api_guide(key: str) -> str:\n \"\"\"根据环境变量名返回对应的API获取指南\n\n Args:\n key: 环境变量名\n\n Returns:\n str: API获取指南链接或说明\n \"\"\"\n key_lower = key.lower()\n if \"openai\" in key_lower:\n return \"https://platform.openai.com/api-keys\"\n elif \"qwen\" in key_lower or \"dashscope\" in key_lower:\n return \"https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key\"\n elif \"deepseek\" in key_lower:\n return \"https://platform.deepseek.com/api_keys\"\n elif \"ppio\" in key_lower:\n return \"https://ppinfra.com/settings/key-management?utm_source=github_owl\"\n elif \"google\" in key_lower:\n return \"https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3\"\n elif \"search_engine_id\" in key_lower:\n return \"https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3\"\n elif \"chunkr\" in key_lower:\n return \"https://chunkr.ai/\"\n elif \"firecrawl\" in key_lower:\n return \"https://www.firecrawl.dev/\"\n elif \"novita\" in key_lower:\n return \"https://novita.ai/settings/key-management?utm_source=github_owl&utm_medium=github_readme&utm_campaign=github_link\"\n else:\n return \"\"\n\n\ndef update_env_table():\n \"\"\"更新环境变量表格显示,只显示API相关的环境变量\"\"\"\n env_vars = load_env_vars()\n # 过滤出API相关的环境变量\n api_env_vars = {k: v for k, v in env_vars.items() if is_api_related(k)}\n # 转换为列表格式,以符合Gradio Dataframe的要求\n # 格式: [变量名, 变量值, 获取指南链接]\n result = []\n for k, v in api_env_vars.items():\n guide = get_api_guide(k)\n # 如果有指南链接,创建一个可点击的链接\n guide_link = (\n f\"🔗 获取\"\n if guide\n else \"\"\n )\n result.append([k, v[0], guide_link])\n return result\n\n\ndef save_env_table_changes(data):\n \"\"\"保存环境变量表格的更改\n\n Args:\n data: Dataframe数据,可能是pandas DataFrame对象\n\n Returns:\n str: 操作状态信息,包含HTML格式的状态消息\n \"\"\"\n try:\n logging.info(f\"开始处理环境变量表格数据,类型: {type(data)}\")\n\n # 获取当前所有环境变量\n current_env_vars = load_env_vars()\n processed_keys = set() # 记录已处理的键,用于检测删除的变量\n\n # 处理pandas DataFrame对象\n import pandas as pd\n\n if isinstance(data, pd.DataFrame):\n # 获取列名信息\n columns = data.columns.tolist()\n logging.info(f\"DataFrame列名: {columns}\")\n\n # 遍历DataFrame的每一行\n for index, row in data.iterrows():\n # 使用列名访问数据\n if len(columns) >= 3:\n # 获取变量名和值 (第0列是变量名,第1列是值)\n key = row[0] if isinstance(row, pd.Series) else row.iloc[0]\n value = row[1] if isinstance(row, pd.Series) else row.iloc[1]\n\n # 检查是否为空行或已删除的变量\n if key and str(key).strip(): # 如果键名不为空,则添加或更新\n logging.info(f\"处理环境变量: {key} = {value}\")\n add_env_var(key, str(value))\n processed_keys.add(key)\n # 处理其他格式\n elif isinstance(data, dict):\n logging.info(f\"字典格式数据的键: {list(data.keys())}\")\n # 如果是字典格式,尝试不同的键\n if \"data\" in data:\n rows = data[\"data\"]\n elif \"values\" in data:\n rows = data[\"values\"]\n elif \"value\" in data:\n rows = data[\"value\"]\n else:\n # 尝试直接使用字典作为行数据\n rows = []\n for key, value in data.items():\n if key not in [\"headers\", \"types\", \"columns\"]:\n rows.append([key, value])\n\n if isinstance(rows, list):\n for row in rows:\n if isinstance(row, list) and len(row) >= 2:\n key, value = row[0], row[1]\n if key and str(key).strip():\n add_env_var(key, str(value))\n processed_keys.add(key)\n elif isinstance(data, list):\n # 列表格式\n for row in data:\n if isinstance(row, list) and len(row) >= 2:\n key, value = row[0], row[1]\n if key and str(key).strip():\n add_env_var(key, str(value))\n processed_keys.add(key)\n else:\n logging.error(f\"未知的数据格式: {type(data)}\")\n return f\"❌ 保存失败: 未知的数据格式 {type(data)}\"\n\n # 处理删除的变量 - 检查当前环境变量中是否有未在表格中出现的变量\n api_related_keys = {k for k in current_env_vars.keys() if is_api_related(k)}\n keys_to_delete = api_related_keys - processed_keys\n\n # 删除不再表格中的变量\n for key in keys_to_delete:\n logging.info(f\"删除环境变量: {key}\")\n delete_env_var(key)\n\n return \"✅ 环境变量已成功保存\"\n except Exception as e:\n import traceback\n\n error_details = traceback.format_exc()\n logging.error(f\"保存环境变量时出错: {str(e)}\\n{error_details}\")\n return f\"❌ 保存失败: {str(e)}\"\n\n\ndef get_env_var_value(key):\n \"\"\"获取环境变量的实际值\n\n 优先级:前端配置 > .env文件 > 系统环境变量\n \"\"\"\n # 检查前端配置的环境变量\n if key in WEB_FRONTEND_ENV_VARS:\n return WEB_FRONTEND_ENV_VARS[key]\n\n # 检查系统环境变量(包括从.env加载的)\n return os.environ.get(key, \"\")\n\n\ndef create_ui():\n \"\"\"创建增强版Gradio界面\"\"\"\n\n def clear_log_file():\n \"\"\"清空日志文件内容\"\"\"\n try:\n if LOG_FILE and os.path.exists(LOG_FILE):\n # 清空日志文件内容而不是删除文件\n open(LOG_FILE, \"w\").close()\n logging.info(\"日志文件已清空\")\n # 清空日志队列\n while not LOG_QUEUE.empty():\n try:\n LOG_QUEUE.get_nowait()\n except queue.Empty:\n break\n return \"\"\n else:\n return \"\"\n except Exception as e:\n logging.error(f\"清空日志文件时出错: {str(e)}\")\n return \"\"\n\n # 创建一个实时日志更新函数\n def process_with_live_logs(question, module_name):\n \"\"\"处理问题并实时更新日志\"\"\"\n global CURRENT_PROCESS\n\n # 清空日志文件\n clear_log_file()\n\n # 创建一个后台线程来处理问题\n result_queue = queue.Queue()\n\n def process_in_background():\n try:\n result = run_owl(question, module_name)\n result_queue.put(result)\n except Exception as e:\n result_queue.put((f\"发生错误: {str(e)}\", \"0\", f\"❌ 错误: {str(e)}\"))\n\n # 启动后台处理线程\n bg_thread = threading.Thread(target=process_in_background)\n CURRENT_PROCESS = bg_thread # 记录当前进程\n bg_thread.start()\n\n # 在等待处理完成的同时,每秒更新一次日志\n while bg_thread.is_alive():\n # 更新对话记录显示\n logs2 = get_latest_logs(100, LOG_QUEUE)\n\n # 始终更新状态\n yield (\n \"0\",\n \" 处理中...\",\n logs2,\n )\n\n time.sleep(1)\n\n # 处理完成,获取结果\n if not result_queue.empty():\n result = result_queue.get()\n answer, token_count, status = result\n\n # 最后一次更新对话记录\n logs2 = get_latest_logs(100, LOG_QUEUE)\n\n # 根据状态设置不同的指示器\n if \"错误\" in status:\n status_with_indicator = (\n f\" {status}\"\n )\n else:\n status_with_indicator = (\n f\" {status}\"\n )\n\n yield token_count, status_with_indicator, logs2\n else:\n logs2 = get_latest_logs(100, LOG_QUEUE)\n yield (\n \"0\",\n \" 已终止\",\n logs2,\n )\n\n with gr.Blocks(theme=gr.themes.Soft(primary_hue=\"blue\")) as app:\n gr.Markdown(\n \"\"\"\n # 🦉 OWL 多智能体协作系统\n\n 基于CAMEL框架开发的先进多智能体协作系统,旨在通过智能体协作解决复杂问题。\n\n 可以通过修改本地脚本自定义模型和工具。\n \n 本网页应用目前处于测试阶段,仅供演示和测试使用,尚未推荐用于生产环境。\n \"\"\"\n )\n\n # 添加自定义CSS\n gr.HTML(\"\"\"\n \n \"\"\")\n\n with gr.Row():\n with gr.Column(scale=0.5):\n question_input = gr.Textbox(\n lines=5,\n placeholder=\"请输入您的问题...\",\n label=\"问题\",\n elem_id=\"question_input\",\n show_copy_button=True,\n value=\"打开百度搜索,总结一下camel-ai的camel框架的github star、fork数目等,并把数字用plot包写成python文件保存到本地,并运行生成的python文件。\",\n )\n\n # 增强版模块选择下拉菜单\n # 只包含MODULE_DESCRIPTIONS中定义的模块\n module_dropdown = gr.Dropdown(\n choices=list(MODULE_DESCRIPTIONS.keys()),\n value=\"run_qwen_zh\",\n label=\"选择功能模块\",\n interactive=True,\n )\n\n # 模块描述文本框\n module_description = gr.Textbox(\n value=MODULE_DESCRIPTIONS[\"run_qwen_zh\"],\n label=\"模块描述\",\n interactive=False,\n elem_classes=\"module-info\",\n )\n\n with gr.Row():\n run_button = gr.Button(\n \"运行\", variant=\"primary\", elem_classes=\"primary\"\n )\n\n status_output = gr.HTML(\n value=\" 已就绪\",\n label=\"状态\",\n )\n token_count_output = gr.Textbox(\n label=\"令牌计数\", interactive=False, elem_classes=\"token-count\"\n )\n\n # 示例问题\n examples = [\n \"打开百度搜索,总结一下camel-ai的camel框架的github star、fork数目等,并把数字用plot包写成python文件保存到本地,并运行生成的python文件。\",\n \"浏览亚马逊并找出一款对程序员有吸引力的产品。请提供产品名称和价格\",\n \"写一个hello world的python文件,保存到本地\",\n ]\n\n gr.Examples(examples=examples, inputs=question_input)\n\n gr.HTML(\"\"\"\n
\n

关于 OWL 多智能体协作系统

\n

OWL 是一个基于CAMEL框架开发的先进多智能体协作系统,旨在通过智能体协作解决复杂问题。

\n

© 2025 CAMEL-AI.org. 基于Apache License 2.0开源协议

\n

GitHub

\n
\n \"\"\")\n\n with gr.Tabs(): # 设置对话记录为默认选中的标签页\n with gr.TabItem(\"对话记录\"):\n # 添加对话记录显示区域\n with gr.Group():\n log_display2 = gr.Markdown(\n value=\"暂无对话记录。\",\n elem_classes=\"log-display\",\n )\n\n with gr.Row():\n refresh_logs_button2 = gr.Button(\"刷新记录\")\n auto_refresh_checkbox2 = gr.Checkbox(\n label=\"自动刷新\", value=True, interactive=True\n )\n clear_logs_button2 = gr.Button(\"清空记录\", variant=\"secondary\")\n\n with gr.TabItem(\"环境变量管理\", id=\"env-settings\"):\n with gr.Group(elem_classes=\"env-manager-container\"):\n gr.Markdown(\"\"\"\n ## 环境变量管理\n \n 在此处设置模型API密钥和其他服务凭证。这些信息将保存在本地的`.env`文件中,确保您的API密钥安全存储且不会上传到网络。正确设置API密钥对于OWL系统的功能至关重要, 可以按找工具需求灵活配置环境变量。\n \"\"\")\n\n # 主要内容分为两列布局\n with gr.Row():\n # 左侧列:环境变量管理控件\n with gr.Column(scale=3):\n with gr.Group(elem_classes=\"env-controls\"):\n # 环境变量表格 - 设置为可交互以直接编辑\n gr.Markdown(\"\"\"\n
\n 提示: 请确保运行cp .env_template .env创建本地.env文件,根据运行模块灵活配置所需环境变量\n
\n \"\"\")\n\n # 增强版环境变量表格,支持添加和删除行\n env_table = gr.Dataframe(\n headers=[\"变量名\", \"值\", \"获取指南\"],\n datatype=[\n \"str\",\n \"str\",\n \"html\",\n ], # 将最后一列设置为html类型以支持链接\n row_count=10, # 增加行数,以便添加新变量\n col_count=(3, \"fixed\"),\n value=update_env_table,\n label=\"API密钥和环境变量\",\n interactive=True, # 设置为可交互,允许直接编辑\n elem_classes=\"env-table\",\n )\n\n # 操作说明\n gr.Markdown(\n \"\"\"\n
\n 操作指南:\n \n
\n \"\"\",\n elem_classes=\"env-instructions\",\n )\n\n # 环境变量操作按钮\n with gr.Row(elem_classes=\"env-buttons\"):\n save_env_button = gr.Button(\n \"💾 保存更改\",\n variant=\"primary\",\n elem_classes=\"env-button\",\n )\n refresh_button = gr.Button(\n \"🔄 刷新列表\", elem_classes=\"env-button\"\n )\n\n # 状态显示\n env_status = gr.HTML(\n label=\"操作状态\",\n value=\"\",\n elem_classes=\"env-status\",\n )\n\n # 连接事件处理函数\n save_env_button.click(\n fn=save_env_table_changes,\n inputs=[env_table],\n outputs=[env_status],\n ).then(fn=update_env_table, outputs=[env_table])\n\n refresh_button.click(fn=update_env_table, outputs=[env_table])\n\n # 设置事件处理\n run_button.click(\n fn=process_with_live_logs,\n inputs=[question_input, module_dropdown],\n outputs=[token_count_output, status_output, log_display2],\n )\n\n # 模块选择更新描述\n module_dropdown.change(\n fn=update_module_description,\n inputs=module_dropdown,\n outputs=module_description,\n )\n\n # 对话记录相关事件处理\n refresh_logs_button2.click(\n fn=lambda: get_latest_logs(100, LOG_QUEUE), outputs=[log_display2]\n )\n\n clear_logs_button2.click(fn=clear_log_file, outputs=[log_display2])\n\n # 自动刷新控制\n def toggle_auto_refresh(enabled):\n if enabled:\n return gr.update(every=3)\n else:\n return gr.update(every=0)\n\n auto_refresh_checkbox2.change(\n fn=toggle_auto_refresh,\n inputs=[auto_refresh_checkbox2],\n outputs=[log_display2],\n )\n\n # 不再默认自动刷新日志\n\n return app\n\n\n# 主函数\ndef main():\n try:\n # 初始化日志系统\n global LOG_FILE\n LOG_FILE = setup_logging()\n logging.info(\"OWL Web应用程序启动\")\n\n # 启动日志读取线程\n log_thread = threading.Thread(\n target=log_reader_thread, args=(LOG_FILE,), daemon=True\n )\n log_thread.start()\n logging.info(\"日志读取线程已启动\")\n\n # 初始化.env文件(如果不存在)\n init_env_file()\n app = create_ui()\n\n app.queue()\n app.launch(share=False)\n except Exception as e:\n logging.error(f\"启动应用程序时发生错误: {str(e)}\")\n print(f\"启动应用程序时发生错误: {str(e)}\")\n import traceback\n\n traceback.print_exc()\n\n finally:\n # 确保日志线程停止\n STOP_LOG_THREAD.set()\n STOP_REQUESTED.set()\n logging.info(\"应用程序关闭\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/owl/webapp_backup.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Import from the correct module path\nfrom utils import run_society\nimport os\nimport gradio as gr\nfrom typing import Tuple, List, Dict\nimport importlib\nfrom dotenv import load_dotenv, set_key, find_dotenv, unset_key\n\nos.environ[\"PYTHONIOENCODING\"] = \"utf-8\"\n\n# Enhanced CSS with navigation bar and additional styling\ncustom_css = \"\"\"\n:root {\n --primary-color: #4a89dc;\n --secondary-color: #5d9cec;\n --accent-color: #7baaf7;\n --light-bg: #f8f9fa;\n --border-color: #e4e9f0;\n --text-muted: #8a9aae;\n}\n\n.container {\n max-width: 1200px;\n margin: 0 auto;\n}\n\n.navbar {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 15px 30px;\n background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));\n color: white;\n border-radius: 10px 10px 0 0;\n margin-bottom: 0;\n box-shadow: 0 2px 10px rgba(74, 137, 220, 0.15);\n}\n\n.navbar-logo {\n display: flex;\n align-items: center;\n gap: 10px;\n font-size: 1.5em;\n font-weight: bold;\n}\n\n.navbar-menu {\n display: flex;\n gap: 20px;\n}\n\n/* Navbar styles moved to a more specific section below */\n\n.header {\n text-align: center;\n margin-bottom: 20px;\n background: linear-gradient(180deg, var(--secondary-color), var(--accent-color));\n color: white;\n padding: 40px 20px;\n border-radius: 0 0 10px 10px;\n box-shadow: 0 4px 6px rgba(93, 156, 236, 0.12);\n}\n\n.module-info {\n background-color: var(--light-bg);\n border-left: 5px solid var(--primary-color);\n padding: 10px 15px;\n margin-top: 10px;\n border-radius: 5px;\n font-size: 0.9em;\n}\n\n.answer-box {\n background-color: var(--light-bg);\n border-left: 5px solid var(--secondary-color);\n padding: 15px;\n margin-bottom: 20px;\n border-radius: 5px;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);\n}\n\n.token-count {\n background-color: #e9ecef;\n padding: 10px;\n border-radius: 5px;\n text-align: center;\n font-weight: bold;\n margin-bottom: 20px;\n}\n\n.chat-container {\n border: 1px solid var(--border-color);\n border-radius: 5px;\n max-height: 500px;\n overflow-y: auto;\n margin-bottom: 20px;\n}\n\n.footer {\n text-align: center;\n margin-top: 20px;\n color: var(--text-muted);\n font-size: 0.9em;\n padding: 20px;\n border-top: 1px solid var(--border-color);\n}\n\n.features-section {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 20px;\n margin: 20px 0;\n}\n\n@media (max-width: 1200px) {\n .features-section {\n grid-template-columns: repeat(2, 1fr);\n }\n}\n\n@media (max-width: 768px) {\n .features-section {\n grid-template-columns: 1fr;\n }\n}\n\n.feature-card {\n background-color: white;\n border-radius: 8px;\n padding: 20px;\n box-shadow: 0 2px 8px rgba(74, 137, 220, 0.08);\n transition: transform 0.3s, box-shadow 0.3s;\n height: 100%;\n display: flex;\n flex-direction: column;\n border: 1px solid rgba(228, 233, 240, 0.6);\n}\n\n.feature-card:hover {\n transform: translateY(-5px);\n box-shadow: 0 5px 15px rgba(74, 137, 220, 0.15);\n border-color: rgba(93, 156, 236, 0.3);\n}\n\n.feature-icon {\n font-size: 2em;\n color: var(--primary-color);\n margin-bottom: 10px;\n text-shadow: 0 1px 2px rgba(74, 137, 220, 0.1);\n}\n\n.feature-card h3 {\n margin-top: 10px;\n margin-bottom: 10px;\n}\n\n.feature-card p {\n flex-grow: 1;\n font-size: 0.95em;\n line-height: 1.5;\n}\n\n/* Navbar link styles - ensuring consistent colors */\n.navbar-menu a {\n color: #ffffff !important;\n text-decoration: none;\n padding: 5px 10px;\n border-radius: 5px;\n transition: background-color 0.3s, color 0.3s;\n font-weight: 500;\n text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);\n}\n\n.navbar-menu a:hover {\n background-color: rgba(255, 255, 255, 0.15);\n color: #ffffff !important;\n}\n\n/* Improved button and input styles */\nbutton.primary {\n background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));\n transition: all 0.3s;\n}\n\nbutton.primary:hover {\n background: linear-gradient(90deg, var(--secondary-color), var(--primary-color));\n transform: translateY(-2px);\n box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);\n}\n\n.env-section {\n background-color: var(--light-bg);\n border-radius: 8px;\n padding: 20px;\n margin: 20px 0;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);\n}\n\n.env-table {\n width: 100%;\n border-collapse: collapse;\n margin-top: 15px;\n}\n\n.env-table th, .env-table td {\n padding: 10px;\n border: 1px solid var(--border-color);\n}\n\n.env-table th {\n background-color: var(--primary-color);\n color: white;\n text-align: left;\n}\n\n.env-table tr:nth-child(even) {\n background-color: rgba(0, 0, 0, 0.02);\n}\n\n.env-actions {\n display: flex;\n gap: 10px;\n}\n\n.env-var-input {\n margin-bottom: 15px;\n}\n\n.env-save-status {\n margin-top: 15px;\n padding: 10px;\n border-radius: 5px;\n}\n\n.success {\n background-color: #d4edda;\n color: #155724;\n border: 1px solid #c3e6cb;\n}\n\n.error {\n background-color: #f8d7da;\n color: #721c24;\n border: 1px solid #f5c6cb;\n}\n\"\"\"\n\n# Dictionary containing module descriptions\nMODULE_DESCRIPTIONS = {\n \"run\": \"默认模式:使用OpenAI模型的默认的智能体协作模式,适合大多数任务。\",\n \"run_mini\": \"使用使用OpenAI模型最小化配置处理任务\",\n \"run_deepseek_zh\": \"使用deepseek模型处理中文任务\",\n \"run_terminal_zh\": \"终端模式:可执行命令行操作,支持网络搜索、文件处理等功能。适合需要系统交互的任务,使用OpenAI模型\",\n \"run_gaia_roleplaying\": \"GAIA基准测试实现,用于评估Agent能力\",\n \"run_openai_compatible_model\": \"使用openai兼容模型处理任务\",\n \"run_ollama\": \"使用本地ollama模型处理任务\",\n \"run_qwen_mini_zh\": \"使用qwen模型最小化配置处理任务\",\n \"run_qwen_zh\": \"使用qwen模型处理任务\",\n}\n\n# 默认环境变量模板\nDEFAULT_ENV_TEMPLATE = \"\"\"# MODEL & API (See https://docs.camel-ai.org/key_modules/models.html#)\n\n# OPENAI API\n# OPENAI_API_KEY= \"\"\n# OPENAI_API_BASE_URL=\"\"\n\n# Qwen API (https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key)\n# QWEN_API_KEY=\"\"\n\n# DeepSeek API (https://platform.deepseek.com/api_keys)\n# DEEPSEEK_API_KEY=\"\"\n\n#===========================================\n# Tools & Services API\n#===========================================\n\n# Google Search API (https://developers.google.com/custom-search/v1/overview)\nGOOGLE_API_KEY=\"\"\nSEARCH_ENGINE_ID=\"\"\n\n# Hugging Face API (https://huggingface.co/join)\nHF_TOKEN=\"\"\n\n# Chunkr API (https://chunkr.ai/)\nCHUNKR_API_KEY=\"\"\n\n# Firecrawl API (https://www.firecrawl.dev/)\nFIRECRAWL_API_KEY=\"\"\n#FIRECRAWL_API_URL=\"https://api.firecrawl.dev\"\n\"\"\"\n\n\ndef format_chat_history(chat_history: List[Dict[str, str]]) -> List[List[str]]:\n \"\"\"将聊天历史格式化为Gradio聊天组件可接受的格式\n\n Args:\n chat_history: 原始聊天历史\n\n Returns:\n List[List[str]]: 格式化后的聊天历史\n \"\"\"\n formatted_history = []\n for message in chat_history:\n user_msg = message.get(\"user\", \"\")\n assistant_msg = message.get(\"assistant\", \"\")\n\n if user_msg:\n formatted_history.append([user_msg, None])\n if assistant_msg and formatted_history:\n formatted_history[-1][1] = assistant_msg\n elif assistant_msg:\n formatted_history.append([None, assistant_msg])\n\n return formatted_history\n\n\ndef validate_input(question: str) -> bool:\n \"\"\"验证用户输入是否有效\n\n Args:\n question: 用户问题\n\n Returns:\n bool: 输入是否有效\n \"\"\"\n # 检查输入是否为空或只包含空格\n if not question or question.strip() == \"\":\n return False\n return True\n\n\ndef run_owl(\n question: str, example_module: str\n) -> Tuple[str, List[List[str]], str, str]:\n \"\"\"运行OWL系统并返回结果\n\n Args:\n question: 用户问题\n example_module: 要导入的示例模块名(如 \"run_terminal_zh\" 或 \"run_deep\")\n\n Returns:\n Tuple[...]: 回答、聊天历史、令牌计数、状态\n \"\"\"\n # 验证输入\n if not validate_input(question):\n return (\"请输入有效的问题\", [], \"0\", \"❌ 错误: 输入无效\")\n\n try:\n # 确保环境变量已加载\n load_dotenv(find_dotenv(), override=True)\n # 检查模块是否在MODULE_DESCRIPTIONS中\n if example_module not in MODULE_DESCRIPTIONS:\n return (\n f\"所选模块 '{example_module}' 不受支持\",\n [],\n \"0\",\n \"❌ 错误: 不支持的模块\",\n )\n\n # 动态导入目标模块\n module_path = f\"owl.examples.{example_module}\"\n try:\n module = importlib.import_module(module_path)\n except ImportError as ie:\n return (\n f\"无法导入模块: {module_path}\",\n [],\n \"0\",\n f\"❌ 错误: 模块 {example_module} 不存在或无法加载 - {str(ie)}\",\n )\n except Exception as e:\n return (f\"导入模块时发生错误: {module_path}\", [], \"0\", f\"❌ 错误: {str(e)}\")\n\n # 检查是否包含construct_society函数\n if not hasattr(module, \"construct_society\"):\n return (\n f\"模块 {module_path} 中未找到 construct_society 函数\",\n [],\n \"0\",\n \"❌ 错误: 模块接口不兼容\",\n )\n\n # 构建社会模拟\n try:\n society = module.construct_society(question)\n except Exception as e:\n return (\n f\"构建社会模拟时发生错误: {str(e)}\",\n [],\n \"0\",\n f\"❌ 错误: 构建失败 - {str(e)}\",\n )\n\n # 运行社会模拟\n try:\n answer, chat_history, token_info = run_society(society)\n except Exception as e:\n return (\n f\"运行社会模拟时发生错误: {str(e)}\",\n [],\n \"0\",\n f\"❌ 错误: 运行失败 - {str(e)}\",\n )\n\n # 格式化聊天历史\n try:\n formatted_chat_history = format_chat_history(chat_history)\n except Exception:\n # 如果格式化失败,返回空历史记录但继续处理\n formatted_chat_history = []\n\n # 安全地获取令牌计数\n if not isinstance(token_info, dict):\n token_info = {}\n\n completion_tokens = token_info.get(\"completion_token_count\", 0)\n prompt_tokens = token_info.get(\"prompt_token_count\", 0)\n total_tokens = completion_tokens + prompt_tokens\n\n return (\n answer,\n formatted_chat_history,\n f\"完成令牌: {completion_tokens:,} | 提示令牌: {prompt_tokens:,} | 总计: {total_tokens:,}\",\n \"✅ 成功完成\",\n )\n\n except Exception as e:\n return (f\"发生错误: {str(e)}\", [], \"0\", f\"❌ 错误: {str(e)}\")\n\n\ndef update_module_description(module_name: str) -> str:\n \"\"\"返回所选模块的描述\"\"\"\n return MODULE_DESCRIPTIONS.get(module_name, \"无可用描述\")\n\n\n# 环境变量管理功能\ndef init_env_file():\n \"\"\"初始化.env文件如果不存在\"\"\"\n dotenv_path = find_dotenv()\n if not dotenv_path:\n with open(\".env\", \"w\") as f:\n f.write(DEFAULT_ENV_TEMPLATE)\n dotenv_path = find_dotenv()\n return dotenv_path\n\n\ndef load_env_vars():\n \"\"\"加载环境变量并返回字典格式\"\"\"\n dotenv_path = init_env_file()\n load_dotenv(dotenv_path, override=True)\n\n env_vars = {}\n with open(dotenv_path, \"r\") as f:\n for line in f:\n line = line.strip()\n if line and not line.startswith(\"#\"):\n if \"=\" in line:\n key, value = line.split(\"=\", 1)\n env_vars[key.strip()] = value.strip().strip(\"\\\"'\")\n\n return env_vars\n\n\ndef save_env_vars(env_vars):\n \"\"\"保存环境变量到.env文件\"\"\"\n try:\n dotenv_path = init_env_file()\n\n # 保存每个环境变量\n for key, value in env_vars.items():\n if key and key.strip(): # 确保键不为空\n set_key(dotenv_path, key.strip(), value.strip())\n\n # 重新加载环境变量以确保生效\n load_dotenv(dotenv_path, override=True)\n\n return True, \"环境变量已成功保存!\"\n except Exception as e:\n return False, f\"保存环境变量时出错: {str(e)}\"\n\n\ndef add_env_var(key, value):\n \"\"\"添加或更新单个环境变量\"\"\"\n try:\n if not key or not key.strip():\n return False, \"变量名不能为空\"\n\n dotenv_path = init_env_file()\n set_key(dotenv_path, key.strip(), value.strip())\n load_dotenv(dotenv_path, override=True)\n\n return True, f\"环境变量 {key} 已成功添加/更新!\"\n except Exception as e:\n return False, f\"添加环境变量时出错: {str(e)}\"\n\n\ndef delete_env_var(key):\n \"\"\"删除环境变量\"\"\"\n try:\n if not key or not key.strip():\n return False, \"变量名不能为空\"\n\n dotenv_path = init_env_file()\n unset_key(dotenv_path, key.strip())\n\n # 从当前进程环境中也删除\n if key in os.environ:\n del os.environ[key]\n\n return True, f\"环境变量 {key} 已成功删除!\"\n except Exception as e:\n return False, f\"删除环境变量时出错: {str(e)}\"\n\n\ndef mask_sensitive_value(key: str, value: str) -> str:\n \"\"\"对敏感信息进行掩码处理\n\n Args:\n key: 环境变量名\n value: 环境变量值\n\n Returns:\n str: 处理后的值\n \"\"\"\n # 定义需要掩码的敏感关键词\n sensitive_keywords = [\"key\", \"token\", \"secret\", \"password\", \"api\"]\n\n # 检查是否包含敏感关键词(不区分大小写)\n is_sensitive = any(keyword in key.lower() for keyword in sensitive_keywords)\n\n if is_sensitive and value:\n # 如果是敏感信息且有值,则显示掩码\n return \"*\" * 8\n return value\n\n\ndef update_env_table():\n \"\"\"更新环境变量表格显示,对敏感信息进行掩码处理\"\"\"\n env_vars = load_env_vars()\n # 对敏感值进行掩码处理\n masked_env_vars = [[k, mask_sensitive_value(k, v)] for k, v in env_vars.items()]\n return masked_env_vars\n\n\ndef create_ui():\n \"\"\"创建增强版Gradio界面\"\"\"\n with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue=\"blue\")) as app:\n with gr.Column(elem_classes=\"container\"):\n gr.HTML(\"\"\"\n
\n
\n 🦉 OWL 多智能体协作系统\n
\n
\n 首页\n 环境设置\n 加入交流群\n OWL文档\n CAMEL框架\n CAMEL-AI官网\n
\n
\n
\n \n

我们的愿景是彻底改变AI代理协作解决现实世界任务的方式。通过利用动态代理交互,OWL能够在多个领域实现更自然、高效和稳健的任务自动化。

\n
\n \"\"\")\n\n with gr.Row(elem_id=\"features\"):\n gr.HTML(\"\"\"\n
\n
\n
🔍
\n

实时信息检索

\n

利用维基百科、谷歌搜索和其他在线资源获取最新信息。

\n
\n
\n
📹
\n

多模态处理

\n

支持处理互联网或本地的视频、图像和音频数据。

\n
\n
\n
🌐
\n

浏览器自动化

\n

使用Playwright框架模拟浏览器交互,实现网页操作自动化。

\n
\n
\n
📄
\n

文档解析

\n

从各种文档格式中提取内容,并转换为易于处理的格式。

\n
\n
\n
💻
\n

代码执行

\n

使用解释器编写和运行Python代码,实现自动化数据处理。

\n
\n
\n
🧰
\n

内置工具包

\n

提供丰富的工具包,支持搜索、数据分析、代码执行等多种功能。

\n
\n
\n
🔑
\n

环境变量管理

\n

便捷管理API密钥和环境配置,安全存储敏感信息。

\n
\n
\n \"\"\")\n\n with gr.Row():\n with gr.Column(scale=2):\n question_input = gr.Textbox(\n lines=5,\n placeholder=\"请输入您的问题...\",\n label=\"问题\",\n elem_id=\"question_input\",\n show_copy_button=True,\n )\n\n # 增强版模块选择下拉菜单\n # 只包含MODULE_DESCRIPTIONS中定义的模块\n module_dropdown = gr.Dropdown(\n choices=list(MODULE_DESCRIPTIONS.keys()),\n value=\"run_terminal_zh\",\n label=\"选择功能模块\",\n interactive=True,\n )\n\n # 模块描述文本框\n module_description = gr.Textbox(\n value=MODULE_DESCRIPTIONS[\"run_terminal_zh\"],\n label=\"模块描述\",\n interactive=False,\n elem_classes=\"module-info\",\n )\n\n run_button = gr.Button(\n \"运行\", variant=\"primary\", elem_classes=\"primary\"\n )\n\n with gr.Column(scale=1):\n gr.Markdown(\"\"\"\n ### 使用指南\n \n 1. **选择适合的模块**:根据您的任务需求选择合适的功能模块\n 2. **详细描述您的需求**:在输入框中清晰描述您的问题或任务\n 3. **启动智能处理**:点击\"运行\"按钮开始多智能体协作处理\n 4. **查看结果**:在下方标签页查看回答和完整对话历史\n \n > **高级提示**: 对于复杂任务,可以尝试指定具体步骤和预期结果\n \"\"\")\n\n status_output = gr.Textbox(label=\"状态\", interactive=False)\n\n with gr.Tabs():\n with gr.TabItem(\"回答\"):\n answer_output = gr.Textbox(\n label=\"回答\", lines=10, elem_classes=\"answer-box\"\n )\n\n with gr.TabItem(\"对话历史\"):\n chat_output = gr.Chatbot(\n label=\"完整对话记录\", elem_classes=\"chat-container\", height=500\n )\n\n token_count_output = gr.Textbox(\n label=\"令牌计数\", interactive=False, elem_classes=\"token-count\"\n )\n\n # 示例问题\n examples = [\n \"打开百度搜索,总结一下camel-ai的camel框架的github star、fork数目等,并把数字用plot包写成python文件保存到本地,用本地终端执行python文件显示图出来给我\",\n \"请分析GitHub上CAMEL-AI项目的最新统计数据。找出该项目的星标数量、贡献者数量和最近的活跃度。\",\n \"浏览亚马逊并找出一款对程序员有吸引力的产品。请提供产品名称和价格\",\n \"写一个hello world的python文件,保存到本地\",\n ]\n\n gr.Examples(examples=examples, inputs=question_input)\n # 新增: 环境变量管理选项卡\n with gr.TabItem(\"环境变量管理\", id=\"env-settings\"):\n gr.Markdown(\"\"\"\n ## 环境变量管理\n \n 在此处设置模型API密钥和其他服务凭证。这些信息将保存在本地的`.env`文件中,确保您的API密钥安全存储且不会上传到网络。\n \"\"\")\n\n # 环境变量表格\n env_table = gr.Dataframe(\n headers=[\"变量名\", \"值\"],\n datatype=[\"str\", \"str\"],\n row_count=10,\n col_count=(2, \"fixed\"),\n value=update_env_table,\n label=\"当前环境变量\",\n interactive=False,\n )\n\n with gr.Row():\n with gr.Column(scale=1):\n new_env_key = gr.Textbox(\n label=\"变量名\", placeholder=\"例如: OPENAI_API_KEY\"\n )\n with gr.Column(scale=2):\n new_env_value = gr.Textbox(\n label=\"值\", placeholder=\"输入API密钥或其他配置值\"\n )\n\n with gr.Row():\n add_env_button = gr.Button(\"添加/更新变量\", variant=\"primary\")\n refresh_button = gr.Button(\"刷新变量列表\")\n delete_env_button = gr.Button(\"删除选定变量\", variant=\"stop\")\n\n env_status = gr.Textbox(label=\"状态\", interactive=False)\n\n # 变量选择器(用于删除)\n env_var_to_delete = gr.Dropdown(\n choices=[], label=\"选择要删除的变量\", interactive=True\n )\n\n # 更新变量选择器的选项\n def update_delete_dropdown():\n env_vars = load_env_vars()\n return gr.Dropdown.update(choices=list(env_vars.keys()))\n\n # 连接事件处理函数\n add_env_button.click(\n fn=lambda k, v: add_env_var(k, v),\n inputs=[new_env_key, new_env_value],\n outputs=[env_status],\n ).then(fn=update_env_table, outputs=[env_table]).then(\n fn=update_delete_dropdown, outputs=[env_var_to_delete]\n ).then(\n fn=lambda: (\"\", \"\"), # 修改为返回两个空字符串的元组\n outputs=[new_env_key, new_env_value],\n )\n\n refresh_button.click(fn=update_env_table, outputs=[env_table]).then(\n fn=update_delete_dropdown, outputs=[env_var_to_delete]\n )\n\n delete_env_button.click(\n fn=lambda k: delete_env_var(k),\n inputs=[env_var_to_delete],\n outputs=[env_status],\n ).then(fn=update_env_table, outputs=[env_table]).then(\n fn=update_delete_dropdown, outputs=[env_var_to_delete]\n )\n\n gr.HTML(\"\"\"\n
\n

关于 OWL 多智能体协作系统

\n

OWL 是一个基于CAMEL框架开发的先进多智能体协作系统,旨在通过智能体协作解决复杂问题。

\n

© 2025 CAMEL-AI.org. 基于Apache License 2.0开源协议

\n

GitHub

\n
\n \"\"\")\n\n # 设置事件处理\n run_button.click(\n fn=run_owl,\n inputs=[question_input, module_dropdown],\n outputs=[answer_output, chat_output, token_count_output, status_output],\n )\n\n # 模块选择更新描述\n module_dropdown.change(\n fn=update_module_description,\n inputs=module_dropdown,\n outputs=module_description,\n )\n\n return app\n\n\n# 主函数\ndef main():\n try:\n # 初始化.env文件(如果不存在)\n init_env_file()\n app = create_ui()\n app.launch(share=False)\n except Exception as e:\n print(f\"启动应用程序时发生错误: {str(e)}\")\n import traceback\n\n traceback.print_exc()\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/OWL Interview Preparation Assistant/app.py", "#app.py\nimport os\nimport streamlit as st\nimport logging\nimport queue\nimport time\nimport sys\n\n# Add parent directory to path for OWL imports\nsys.path.append('../')\n\ntry:\n from main import research_company, generate_interview_questions, create_interview_prep_plan\nexcept ImportError as e:\n st.error(f\"Error importing functions: {e}\")\n st.stop()\n\n# Setup logging with queue to capture logs for display\nlog_queue = queue.Queue()\n\nclass StreamlitLogHandler(logging.Handler):\n def __init__(self, log_queue):\n super().__init__()\n self.log_queue = log_queue\n self.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\n def emit(self, record):\n log_entry = self.format(record)\n self.log_queue.put(log_entry)\n\n# Configure root logger\nroot_logger = logging.getLogger()\nroot_logger.setLevel(logging.INFO)\nfor handler in root_logger.handlers[:]:\n root_logger.removeHandler(handler)\nroot_logger.addHandler(StreamlitLogHandler(log_queue))\nroot_logger.addHandler(logging.StreamHandler()) # Also log to console\n\n# Configure Streamlit page\nst.set_page_config(\n page_title=\"Interview Prep Assistant(With OWL 🦉)\", \n page_icon=\"🦉\",\n layout=\"wide\"\n)\n\n# Custom CSS\nst.markdown(\"\"\"\n\n\"\"\", unsafe_allow_html=True)\n\ndef display_conversation(chat_history):\n \"\"\"Display the conversation history in a structured format\"\"\"\n if not chat_history:\n st.info(\"No conversation available\")\n return\n \n st.markdown(\"
\", unsafe_allow_html=True)\n \n for idx, message in enumerate(chat_history):\n round_num = idx + 1\n st.markdown(f\"
Round {round_num}
\", unsafe_allow_html=True)\n \n # Display user message\n if \"user\" in message and message[\"user\"]:\n st.markdown(f\"
🧑‍💼 Job Seeker:
{message['user']}
\", unsafe_allow_html=True)\n \n # Display assistant message\n if \"assistant\" in message and message[\"assistant\"]:\n assistant_content = message[\"assistant\"]\n # Remove any note about truncation for cleaner display\n if \"[Note: This conversation was limited\" in assistant_content:\n assistant_content = assistant_content.replace(\"[Note: This conversation was limited to maintain response quality. The complete thought process is available in the logs.]\", \"\")\n \n st.markdown(f\"
🦉 Interview Coach:
{assistant_content}
\", unsafe_allow_html=True)\n \n # Display tool calls if any\n if \"tool_calls\" in message and message[\"tool_calls\"]:\n for tool in message[\"tool_calls\"]:\n tool_name = tool.get('name', 'Unknown Tool')\n st.markdown(f\"
🔧 Tool Used: {tool_name}
\", unsafe_allow_html=True)\n \n st.markdown(\"
\", unsafe_allow_html=True)\n\ndef display_metrics(duration, token_count, num_rounds):\n \"\"\"Display metrics in a visually appealing format\"\"\"\n st.markdown(\"
\", unsafe_allow_html=True)\n \n # Time taken\n st.markdown(f\"\"\"\n
\n
{duration:.1f}s
\n
Execution Time
\n
\n \"\"\", unsafe_allow_html=True)\n \n # Token usage\n completion_tokens = token_count.get('completion_token_count', 0)\n prompt_tokens = token_count.get('prompt_token_count', 0)\n total_tokens = completion_tokens + prompt_tokens\n \n st.markdown(f\"\"\"\n
\n
{total_tokens:,}
\n
Total Tokens
\n
\n \"\"\", unsafe_allow_html=True)\n \n # Conversation rounds\n st.markdown(f\"\"\"\n
\n
{num_rounds}
\n
Conversation Rounds
\n
\n \"\"\", unsafe_allow_html=True)\n \n st.markdown(\"
\", unsafe_allow_html=True)\n\ndef get_logs():\n \"\"\"Retrieve logs from the queue\"\"\"\n logs = []\n while not log_queue.empty():\n try:\n logs.append(log_queue.get_nowait())\n except queue.Empty:\n break\n return logs\n\ndef main():\n # Header\n st.markdown(\"

🦉 Interview Preparation Assistant

\", unsafe_allow_html=True)\n st.markdown(\"

Powered by multi-agent AI collaboration

\", unsafe_allow_html=True)\n \n # Input section\n with st.container():\n col1, col2 = st.columns(2)\n with col1:\n job_role = st.text_input(\"Job Role\", \"Machine Learning Engineer\")\n with col2:\n company_name = st.text_input(\"Company Name\", \"Google\")\n \n # Main functionality tabs\n tab1, tab2, tab3, tab4 = st.tabs([\"Company Research\", \"Interview Questions\", \"Preparation Plan\", \"System Logs\"])\n \n # Tab 1: Company Research\n with tab1:\n st.header(\"🔍 Company Research\")\n st.write(\"Get detailed insights about the company to help with your interview preparation.\")\n \n if st.button(\"Research Company\", use_container_width=True):\n with st.spinner():\n # Display running indicator\n status = st.empty()\n status.markdown(\"
🔄 Researching company information...
\", unsafe_allow_html=True)\n \n # Progress bar\n progress = st.progress(0)\n \n # Progress callback\n def update_progress(current_round, max_rounds):\n progress_value = min(current_round / max_rounds, 0.95)\n progress.progress(progress_value)\n status.markdown(f\"
🔄 Processing conversation round {current_round}/{max_rounds}...
\", unsafe_allow_html=True)\n \n # Execute research\n try:\n start_time = time.time()\n result = research_company(\n company_name=company_name,\n detailed=True, # Always use detailed mode\n limited_searches=False, # Don't limit searches\n progress_callback=update_progress\n )\n duration = time.time() - start_time\n \n # Update progress to complete\n progress.progress(1.0)\n status.markdown(\"
✅ Research completed!
\", unsafe_allow_html=True)\n \n # Display metrics\n display_metrics(\n duration=duration,\n token_count=result[\"token_count\"],\n num_rounds=len(result[\"chat_history\"])\n )\n \n # Display final answer\n st.subheader(\"📝 Research Results\")\n st.markdown(f\"
{result['answer']}
\", unsafe_allow_html=True)\n \n # Display conversation\n st.subheader(\"💬 Conversation Process\")\n display_conversation(result[\"chat_history\"])\n \n except Exception as e:\n st.error(f\"Error: {str(e)}\")\n logging.exception(\"Error in company research\")\n \n # Tab 2: Interview Questions\n with tab2:\n st.header(\"❓ Interview Questions\")\n st.write(\"Generate tailored interview questions for your target role and company.\")\n \n # Question type selector (adds interactivity but doesn't change behavior for now)\n question_type = st.radio(\n \"Question Type\",\n [\"Technical\", \"Behavioral\", \"Company-Specific\", \"All\"],\n horizontal=True\n )\n \n if st.button(\"Generate Questions\", use_container_width=True):\n with st.spinner():\n # Display running indicator\n status = st.empty()\n status.markdown(\"
🔄 Creating interview questions...
\", unsafe_allow_html=True)\n \n # Progress bar\n progress = st.progress(0)\n \n # Progress callback\n def update_progress(current_round, max_rounds):\n progress_value = min(current_round / max_rounds, 0.95)\n progress.progress(progress_value)\n status.markdown(f\"
🔄 Processing conversation round {current_round}/{max_rounds}...
\", unsafe_allow_html=True)\n \n # Execute question generation\n try:\n start_time = time.time()\n result = generate_interview_questions(\n job_role=job_role,\n company_name=company_name,\n detailed=True, # Always use detailed mode\n limited_searches=False, # Don't limit searches\n progress_callback=update_progress\n )\n duration = time.time() - start_time\n \n # Update progress to complete\n progress.progress(1.0)\n status.markdown(\"
✅ Questions generated!
\", unsafe_allow_html=True)\n \n # Display metrics\n display_metrics(\n duration=duration,\n token_count=result[\"token_count\"],\n num_rounds=len(result[\"chat_history\"])\n )\n \n # Display final answer\n st.subheader(\"📝 Generated Questions\")\n st.markdown(f\"
{result['answer']}
\", unsafe_allow_html=True)\n \n # Display conversation\n st.subheader(\"💬 Conversation Process\")\n display_conversation(result[\"chat_history\"])\n \n except Exception as e:\n st.error(f\"Error: {str(e)}\")\n logging.exception(\"Error in question generation\")\n \n # Tab 3: Preparation Plan\n with tab3:\n st.header(\"📋 Interview Preparation Plan\")\n st.write(\"Create a comprehensive step-by-step plan to prepare for your interview.\")\n \n if st.button(\"Create Preparation Plan\", use_container_width=True):\n with st.spinner():\n # Display running indicator\n status = st.empty()\n status.markdown(\"
🔄 Creating preparation plan...
\", unsafe_allow_html=True)\n \n # Progress bar\n progress = st.progress(0)\n \n # Progress callback\n def update_progress(current_round, max_rounds):\n progress_value = min(current_round / max_rounds, 0.95)\n progress.progress(progress_value)\n status.markdown(f\"
🔄 Processing conversation round {current_round}/{max_rounds}...
\", unsafe_allow_html=True)\n \n # Execute plan creation\n try:\n start_time = time.time()\n result = create_interview_prep_plan(\n job_role=job_role,\n company_name=company_name,\n detailed=True, # Always use detailed mode\n limited_searches=False, # Don't limit searches\n progress_callback=update_progress\n )\n duration = time.time() - start_time\n \n # Update progress to complete\n progress.progress(1.0)\n status.markdown(\"
✅ Plan created!
\", unsafe_allow_html=True)\n \n # Display metrics\n display_metrics(\n duration=duration,\n token_count=result[\"token_count\"],\n num_rounds=len(result[\"chat_history\"])\n )\n \n # Display final answer\n st.subheader(\"📝 Preparation Plan\")\n st.markdown(f\"
{result['answer']}
\", unsafe_allow_html=True)\n \n # Display conversation\n st.subheader(\"💬 Conversation Process\")\n display_conversation(result[\"chat_history\"])\n \n except Exception as e:\n st.error(f\"Error: {str(e)}\")\n logging.exception(\"Error in preparation plan creation\")\n \n # Tab 4: System Logs\n with tab4:\n st.header(\"🔧 System Logs\")\n st.write(\"View detailed system logs for debugging.\")\n \n logs_container = st.empty()\n \n # Get and display logs\n logs = get_logs()\n if logs:\n logs_container.code(\"\\n\".join(logs))\n else:\n logs_container.info(\"No logs available yet.\")\n \n # Manual refresh button\n if st.button(\"Refresh Logs\"):\n logs = get_logs()\n if logs:\n logs_container.code(\"\\n\".join(logs))\n else:\n logs_container.info(\"No logs available yet.\")\n \n # Auto-refresh toggle\n auto_refresh = st.checkbox(\"Auto-refresh logs\", value=True)\n if auto_refresh:\n st.markdown(\n \"\"\"\n \n \"\"\",\n unsafe_allow_html=True\n )\n\nif __name__ == \"__main__\":\n try:\n logging.info(\"Starting Interview Preparation Assistant application\")\n main()\n except Exception as e:\n st.error(f\"Application error: {str(e)}\")\n logging.exception(\"Application error\")"], ["/owl/owl/utils/gaia.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport sys\n\nsys.path.append(\"../\")\n\nimport json\nimport random\nimport re\nimport string\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Literal, Optional, Union, Tuple\n\nfrom tqdm import tqdm\nfrom camel.benchmarks import BaseBenchmark\nfrom camel.tasks import Task\nfrom camel.logger import get_logger\n\nfrom .common import extract_pattern\nfrom .enhanced_role_playing import run_society, OwlGAIARolePlaying\n\nlogger = get_logger(__name__)\n\n\nclass GAIABenchmark(BaseBenchmark):\n r\"\"\"GAIA Benchmark adapted from `\"GAIA: a benchmark for General AI\n Assistants\"\n `_.\n\n Args:\n data_dir (str): The directory to save the data.\n save_to (str): The file to save the results.\n processes (int, optional): The number of processes to use.\n (default: :obj:`1`)\n \"\"\"\n\n def __init__(\n self,\n data_dir: str,\n save_to: str,\n processes: int = 1,\n ):\n r\"\"\"Initialize the GAIA benchmark.\n\n Args:\n data_dir (str): The directory to save the data.\n save_to (str): The file to save the results.\n processes (int, optional): The number of processes to use for\n parallel processing. (default: :obj:`1`)\n \"\"\"\n super().__init__(\"gaia\", data_dir, save_to, processes)\n\n def download(self):\n r\"\"\"Download the GAIA dataset.\"\"\"\n from huggingface_hub import snapshot_download\n\n snapshot_download(\n repo_id=\"gaia-benchmark/GAIA\",\n repo_type=\"dataset\",\n local_dir=self.data_dir,\n local_dir_use_symlinks=True,\n )\n\n def _check_task_completed(self, task_id: str) -> bool:\n for data in self._results:\n if data[\"task_id\"] == task_id:\n return True\n return False\n\n def dump_tasks(self, save_path: str, datas):\n constructed_data = []\n for idx, data in enumerate(datas):\n tmp_dict = {\n \"idx\": idx,\n \"task_id\": data[\"task_id\"],\n \"Question\": data[\"Question\"],\n \"Level\": data[\"Level\"],\n \"Final answer\": data[\"Final answer\"],\n \"Annotation Metadata\": data[\"Annotator Metadata\"],\n }\n\n constructed_data.append(tmp_dict)\n with open(save_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(constructed_data, f, indent=4)\n f.close()\n\n print(f\"Successfully dumped tasks to {save_path}\")\n\n def load(self, force_download=False):\n r\"\"\"Load the GAIA dataset.\n\n Args:\n force_download (bool, optional): Whether to\n force download the data.\n \"\"\"\n if force_download:\n logger.info(\"Force downloading data.\")\n self.download()\n\n # Define validation and test directories\n valid_dir = self.data_dir / \"2023/validation\"\n test_dir = self.data_dir / \"2023/test\"\n\n # Check if directories exist; if not, download the data\n if not valid_dir.is_dir() or not test_dir.is_dir():\n logger.info(\"Data not found. Downloading data.\")\n self.download()\n\n # Load metadata for both validation and test datasets\n for path, label in zip([valid_dir, test_dir], [\"valid\", \"test\"]):\n self._data[label] = []\n with open(path / \"metadata.jsonl\", \"r\") as f:\n lines = f.readlines()\n for line in lines:\n data = json.loads(line)\n if data[\"task_id\"] == \"0-0-0-0-0\":\n continue\n if data[\"file_name\"]:\n data[\"file_name\"] = path / data[\"file_name\"]\n self._data[label].append(data)\n return self\n\n @property\n def train(self):\n r\"\"\"Get the training set.\"\"\"\n raise NotImplementedError(\"GAIA does not have a training set.\")\n\n def run(\n self,\n user_role_name: str,\n assistant_role_name: str,\n user_agent_kwargs: dict,\n assistant_agent_kwargs: dict,\n on: Literal[\"train\", \"valid\", \"test\"],\n level: Union[int, List[int], Literal[\"all\"]],\n randomize: bool = False,\n subset: Optional[int] = None,\n idx: Optional[List[int]] = None,\n save_result: bool = False,\n ) -> Dict[str, Any]:\n # Validate inputs\n if on not in [\"valid\", \"test\"]:\n raise ValueError(\n f\"Invalid value for `on`: {on}, expected 'valid' or 'test'.\"\n )\n\n levels = (\n [1, 2, 3]\n if level == \"all\"\n else [level]\n if isinstance(level, int)\n else level\n )\n if not all(isinstance(level, int) and level in [1, 2, 3] for level in levels):\n raise ValueError(\n f\"Invalid value for `level`: {level}, expected 1, 2, 3 \" \"or 'all'.\"\n )\n logger.info(f\"Running benchmark on {on} set at levels {levels}.\")\n datas = [data for data in self._data[on] if data[\"Level\"] in levels]\n # Shuffle and subset data if necessary\n if randomize:\n random.shuffle(datas)\n if subset:\n datas = datas[:subset]\n\n if idx is not None:\n # pick only the tasks with the specified idx\n if len(idx) != 0:\n datas = [datas[i] for i in idx]\n\n logger.info(f\"Number of tasks: {len(datas)}\")\n\n self._results = []\n\n if save_result:\n try:\n with open(self.save_to, \"r\", encoding=\"utf-8\") as f:\n self._results = json.load(f)\n f.close()\n except Exception as e:\n logger.warning(e)\n # raise FileNotFoundError(f\"{self.save_to} does not exist.\")\n datas = [\n data for data in datas if not self._check_task_completed(data[\"task_id\"])\n ]\n logger.info(f\"Number of tasks to be processed: {len(datas)}\")\n # Process tasks\n for task in tqdm(datas, desc=\"Running\"):\n if_prepared_task, info = self._prepare_task(task)\n if not if_prepared_task:\n _result_info = {\n \"task_id\": task[\"task_id\"],\n \"question\": task[\"Question\"],\n \"level\": task[\"Level\"],\n \"model_answer\": None,\n \"ground_truth\": None,\n \"score\": 0,\n \"history\": None,\n }\n self._results.append(_result_info)\n continue\n try:\n logger.info(f\"Task Question: {task['Question']}\")\n logger.info(f\"Required tools: {task['Annotator Metadata']['Tools']}\")\n\n task_kwargs = {\n \"task_prompt\": task[\"Question\"],\n \"with_task_specify\": False,\n }\n\n society = OwlGAIARolePlaying(\n **task_kwargs,\n user_role_name=user_role_name,\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=assistant_role_name,\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n raw_answer, chat_history, token_info = run_society(society)\n try:\n answer = extract_pattern(raw_answer, \"final_answer\")\n except Exception as e:\n logger.error(\n f\"Error in extracting final answer from text {raw_answer}: {e}\"\n )\n answer = None\n\n logger.info(\n f\"Model answer: {answer}, Ground truth: {task['Final answer']}\"\n )\n\n _result_info = {\n \"task_id\": task[\"task_id\"],\n \"question\": task[\"Question\"]\n + \"Please decompose the task into several sub-tasks and find the answer step-by-step.\",\n \"level\": task[\"Level\"],\n \"model_answer\": answer,\n \"ground_truth\": task[\"Final answer\"],\n \"score\": self.question_scorer(answer, task[\"Final answer\"]),\n \"token_info\": token_info,\n \"history\": chat_history,\n }\n self._results.append(_result_info)\n\n except Exception as e:\n logger.error(f\"Error in processing task: {e}\")\n\n if save_result:\n with open(self.save_to, \"w\") as f:\n json.dump(self._results, f, indent=4, ensure_ascii=False)\n f.close()\n\n return self._generate_summary()\n\n def _prepare_task(self, task: Dict[str, Any]) -> Tuple[bool, str]:\n r\"\"\"Prepare the task by validating and enriching its data.\"\"\"\n if task[\"file_name\"]:\n if isinstance(task[\"file_name\"], Path):\n task[\"file_name\"] = str(task[\"file_name\"])\n\n file_path = Path(task[\"file_name\"])\n if not file_path.exists():\n logger.info(f\"Skipping task because file not found: {file_path}\")\n return False, f\"Skipping task because file not found: {file_path}\"\n if file_path.suffix in [\".pdf\", \".docx\", \".doc\", \".txt\"]:\n task[\"Question\"] += (\n f\" Here are the necessary document files: {file_path}\"\n )\n\n elif file_path.suffix in [\".jpg\", \".jpeg\", \".png\"]:\n task[\"Question\"] += f\" Here are the necessary image files: {file_path}\"\n\n elif file_path.suffix in [\".xlsx\", \"xls\", \".csv\"]:\n task[\"Question\"] += (\n f\" Here are the necessary table files: {file_path}, for processing excel file, you can write python code and leverage excel toolkit to process the file step-by-step and get the information.\"\n )\n\n elif file_path.suffix in [\".py\"]:\n task[\"Question\"] += f\" Here are the necessary python files: {file_path}\"\n\n else:\n task[\"Question\"] += f\" Here are the necessary files: {file_path}\"\n\n return True, None\n\n def _create_task(self, task: Dict[str, Any]) -> Task:\n r\"\"\"Create a user message from a task.\n\n Args:\n task (Dict[str, Any]): The task to create the message from.\n\n Returns:\n Task: The task created from the input.\n \"\"\"\n return Task(id=str(task[\"task_id\"]), content=task[\"Question\"])\n\n def _generate_summary(self) -> Dict[str, Any]:\n r\"\"\"Generate and return a summary of the benchmark results.\"\"\"\n correct = sum(result[\"score\"] for result in self._results)\n return {\n \"total\": len(self._results),\n \"correct\": correct,\n \"results\": self._results,\n \"accuracy\": correct / len(self._results) if len(self._results) > 0 else 0,\n }\n\n def question_scorer(self, model_answer: str, ground_truth: str) -> bool:\n r\"\"\"Scorer for the GAIA benchmark.\n https://huggingface.co/spaces/gaia-benchmark/leaderboard/blob/main/\n scorer.py\n\n Args:\n model_answer (str): The model answer.\n ground_truth (str): The ground truth answer.\n\n Returns:\n bool: The score of the model\n \"\"\"\n\n def is_float(element: Any) -> bool:\n try:\n float(element)\n return True\n except ValueError:\n return False\n\n if is_float(ground_truth):\n logger.info(f\"Evaluating {model_answer} as a number.\")\n normalized_answer = self.normalize_number_str(model_answer)\n return normalized_answer == float(ground_truth)\n\n elif any(char in ground_truth for char in [\",\", \";\"]):\n logger.info(f\"Evaluating {model_answer} as a comma separated list.\")\n gt_elems = self.split_string(ground_truth)\n ma_elems = self.split_string(model_answer)\n\n if len(gt_elems) != len(ma_elems):\n logger.warning(\n \"Answer lists have different lengths, returning False.\",\n UserWarning,\n )\n return False\n\n comparisons = []\n for ma_elem, gt_elem in zip(ma_elems, gt_elems):\n if is_float(gt_elem):\n normalized_ma_elem = self.normalize_number_str(ma_elem)\n comparisons.append(normalized_ma_elem == float(gt_elem))\n else:\n ma_elem = self.normalize_str(ma_elem, remove_punct=False)\n gt_elem = self.normalize_str(gt_elem, remove_punct=False)\n comparisons.append(ma_elem == gt_elem)\n return all(comparisons)\n else:\n logger.info(f\"Evaluating {model_answer} as a string.\")\n ma_elem = self.normalize_str(model_answer)\n gt_elem = self.normalize_str(ground_truth)\n return ma_elem == gt_elem\n\n def normalize_number_str(self, number_str: str) -> float:\n for char in [\"$\", \"%\", \",\"]:\n number_str = number_str.replace(char, \"\")\n try:\n return float(number_str)\n except ValueError:\n logger.error(f\"String {number_str} cannot be normalized to number str.\")\n return float(\"inf\")\n\n def split_string(self, s: str, char_list: Optional[List[str]] = None) -> list[str]:\n r\"\"\"Split a string based on a list of characters.\n\n Args:\n s (str): The string to split.\n char_list (Optional[List[str]], optional): T\n he list of characters to split on.\n (default: :obj:`None`)\n \"\"\"\n if char_list is None:\n char_list = [\",\", \";\"]\n pattern = f\"[{''.join(char_list)}]\"\n return re.split(pattern, s)\n\n def normalize_str(self, input_str, remove_punct=True) -> str:\n r\"\"\"Normalize a string.\n\n Args:\n input_str: The input string to normalize.\n remove_punct: Whether to remove punctuation.\n\n Returns:\n str: The normalized string.\n \"\"\"\n no_spaces = re.sub(r\"\\s\", \"\", input_str)\n if remove_punct:\n translator = str.maketrans(\"\", \"\", string.punctuation)\n return no_spaces.lower().translate(translator)\n else:\n return no_spaces.lower()\n"], ["/owl/community_usecase/OWL Interview Preparation Assistant/main.py", "#main.py\nimport os\nimport logging\nimport time\nfrom typing import Dict, Any, Callable, Optional\nfrom pathlib import Path\nimport sys\n\n# Add parent directory to path for OWL imports\nsys.path.append('../')\nfrom dotenv import load_dotenv\nimport numpy as np # Explicitly import numpy to avoid 'numpy' errors\nfrom camel.models import ModelFactory\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.toolkits import (\n SearchToolkit, \n BrowserToolkit, \n CodeExecutionToolkit\n)\nfrom camel.societies import RolePlaying\nfrom camel.configs import ChatGPTConfig\nfrom owl.utils import run_society # Official run_society with round_limit support\n\n# Import prompt templates\nfrom config.prompts import (\n get_system_prompt, \n get_company_research_prompt, \n get_question_generator_prompt,\n get_preparation_plan_prompt\n)\n\n# Set up logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger(__name__)\n\n# Load environment variables\nload_dotenv()\n\n# Create the output directory for interview preparation materials\nINTERVIEW_PREP_DIR = \"./interview_prep\"\nos.makedirs(INTERVIEW_PREP_DIR, exist_ok=True)\n\ndef run_society_with_strict_limit(society, round_limit=5, progress_callback=None):\n \"\"\"Wrapper around run_society to ensure round limit is strictly enforced\n \n This implementation hijacks the step method to force termination after a specific number of rounds.\n \"\"\"\n # Track rounds manually\n round_count = 0\n \n # Save original step function\n original_step = society.step\n \n # Override the step method\n def limited_step(*args, **kwargs):\n nonlocal round_count\n round_count += 1\n \n # Report progress if callback is provided\n if progress_callback and callable(progress_callback):\n progress_callback(round_count, round_limit)\n \n # Force termination after reaching the round limit\n if round_count >= round_limit:\n logger.info(f\"Reached round limit of {round_limit}, forcibly terminating.\")\n # Force a TASK_DONE in the user response to trigger termination\n result = original_step(*args, **kwargs)\n if len(result) >= 2 and hasattr(result[1], 'msgs') and result[1].msgs and len(result[1].msgs) > 0:\n result[1].msgs[0].content += \"\\n\\nTASK_DONE\"\n result[1].terminated = True\n return result\n \n return original_step(*args, **kwargs)\n \n # Replace the step method\n society.step = limited_step\n \n try:\n # Run the conversation with the standard run_society function\n answer, chat_history, token_count = run_society(society, round_limit=round_limit)\n \n # Add a note about the conversation being truncated\n if len(chat_history) > 0 and \"truncated_note\" not in chat_history[-1]:\n chat_history[-1][\"truncated_note\"] = True\n if \"assistant\" in chat_history[-1]:\n chat_history[-1][\"assistant\"] += \"\\n\\n[Note: This conversation was limited to maintain response quality.]\"\n \n return answer, chat_history, token_count\n \n finally:\n # Restore the original step method\n society.step = original_step\n\ndef construct_interview_assistant(\n job_description: str, \n company_name: str,\n detailed: bool = True,\n limited_searches: bool = True\n) -> RolePlaying:\n \"\"\"\n Construct a specialized interview preparation assistant using OWL.\n \"\"\"\n # Select model based on environment variables\n if os.environ.get(\"OPENROUTER_API_KEY\"):\n logger.info(\"Using OpenRouter with Gemini model\")\n model = ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n api_key=os.environ.get(\"OPENROUTER_API_KEY\"),\n model_type=\"google/gemini-2.0-flash-001\",\n url=\"https://openrouter.ai/api/v1\",\n model_config_dict={\n \"temperature\": 0.6,\n \"max_tokens\": 4000, # Reduced from 10000 to avoid exceeding limits\n # Do NOT use context_length - it's not a valid API parameter\n }\n )\n elif os.environ.get(\"OPENAI_API_KEY\"):\n logger.info(\"Using OpenAI model (GPT-4)\")\n config = ChatGPTConfig(\n temperature=0.3,\n max_tokens=4000\n )\n model = ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict=config.as_dict()\n )\n else:\n raise ValueError(\"Either OPENAI_API_KEY or OPENROUTER_API_KEY must be set\")\n \n # Configure toolkits - Remove FileWriteToolkit as requested\n essential_tools = [\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_wiki,\n # Removed the FileWriteToolkit as requested\n ]\n \n if os.environ.get(\"GOOGLE_API_KEY\") and os.environ.get(\"SEARCH_ENGINE_ID\"):\n essential_tools.append(SearchToolkit().search_google)\n \n if detailed:\n tools = [\n *essential_tools,\n *BrowserToolkit(\n headless=True,\n web_agent_model=model,\n planning_agent_model=model,\n ).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n ]\n logger.info(\"Using full toolset for comprehensive results (detailed=True)\")\n else:\n tools = essential_tools\n logger.info(\"Using essential toolset for faster results (detailed=False)\")\n \n user_agent_kwargs = {\"model\": model}\n assistant_agent_kwargs = {\"model\": model, \"tools\": tools}\n \n # Build enhanced prompt asking for full, detailed output\n base_prompt = get_system_prompt()\n enhanced_prompt = f\"\"\"{base_prompt}\nTask: Help me prepare for an interview at {company_name} for the position of {job_description}.\nRequirements:\n1. Provide a highly detailed, extremely comprehensive response (aim for at least 2000+ words).\n2. Structure the output with clear sections, actionable insights, examples, and code where relevant.\n3. Tailor the content specifically to {company_name} and the {job_description} role.\n4. Do NOT truncate or summarize—provide the full explanation directly.\n\"\"\"\n \n task_kwargs = {\n \"task_prompt\": enhanced_prompt,\n \"with_task_specify\": False,\n }\n \n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"job_seeker\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"interview_coach\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n \n # Try to set memory parameters to reduce context size\n try:\n # Try to access the context creator if it exists\n if hasattr(society, '_context_creator') and hasattr(society._context_creator, 'max_tokens'):\n society._context_creator.max_tokens = 4000\n # Alternative approach through kwargs if available\n elif hasattr(society, '_context_creator_kwargs'):\n society._context_creator_kwargs = {\"max_tokens\": 4000}\n except AttributeError:\n logger.warning(\"Could not directly set memory parameters. Using default values.\")\n \n return society\n\ndef research_company(\n company_name: str, \n detailed: bool = True, \n limited_searches: bool = True,\n progress_callback: Optional[Callable] = None\n) -> Dict[str, Any]:\n start_time = time.time()\n logging.info(f\"Beginning company research for {company_name}\")\n base_prompt = get_company_research_prompt(company_name)\n enhanced_prompt = f\"\"\"{base_prompt}\n\nPlease provide the most detailed, in-depth report possible, with no summarization or truncation.\nYour response must include extensive coverage, code samples (if relevant), and be at least 2000 words long.\n\"\"\"\n society = construct_interview_assistant(\"\", company_name, detailed=detailed, limited_searches=limited_searches)\n society.task_prompt = enhanced_prompt\n \n # Use our strict wrapper function to enforce limit at exactly 5 rounds\n answer, chat_history, token_count = run_society_with_strict_limit(\n society, \n round_limit=5,\n progress_callback=progress_callback\n )\n \n duration = time.time() - start_time\n logging.info(f\"Completed company research for {company_name} in {duration:.2f} seconds\")\n \n # Find any files that may have been generated\n generated_files = [str(file) for file in Path(INTERVIEW_PREP_DIR).glob(\"*\") if file.is_file()]\n \n return {\n \"answer\": answer,\n \"chat_history\": chat_history,\n \"token_count\": token_count,\n \"generated_files\": generated_files,\n \"duration_seconds\": duration\n }\n\ndef generate_interview_questions(\n job_role: str, \n company_name: str, \n detailed: bool = True, \n limited_searches: bool = True,\n progress_callback: Optional[Callable] = None\n) -> Dict[str, Any]:\n start_time = time.time()\n logging.info(f\"Starting question generation for {job_role} at {company_name} (detailed={detailed})\")\n \n try:\n # Ensure numpy is available to prevent 'numpy' errors\n import numpy as np\n \n base_prompt = get_question_generator_prompt(job_role, company_name)\n enhanced_prompt = f\"\"\"{base_prompt}\n\nPlease provide at least 50 highly specific questions with code examples, multiple solution approaches, \nand extremely thorough explanations. Aim for 3000+ words, with no truncation or summarization.\n\"\"\"\n society = construct_interview_assistant(job_role, company_name, detailed=detailed, limited_searches=limited_searches)\n society.task_prompt = enhanced_prompt\n \n # Use our wrapper function to strictly enforce a limit of 5 rounds\n answer, chat_history, token_count = run_society_with_strict_limit(\n society, \n round_limit=5,\n progress_callback=progress_callback\n )\n \n duration = time.time() - start_time\n logging.info(f\"Completed question generation for {job_role} at {company_name} in {duration:.2f} seconds\")\n \n # Find any files that were generated\n generated_files = [str(file) for file in Path(INTERVIEW_PREP_DIR).glob(\"*\") if file.is_file()]\n \n return {\n \"answer\": answer,\n \"chat_history\": chat_history,\n \"token_count\": token_count,\n \"generated_files\": generated_files,\n \"duration_seconds\": duration\n }\n \n except Exception as e:\n logging.error(f\"Error in question generation: {str(e)}\", exc_info=True)\n raise\n\ndef create_interview_prep_plan(\n job_role: str, \n company_name: str, \n detailed: bool = True, \n limited_searches: bool = True,\n progress_callback: Optional[Callable] = None\n) -> Dict[str, Any]:\n start_time = time.time()\n logging.info(f\"Starting preparation plan creation for {job_role} at {company_name} (detailed={detailed})\")\n \n try:\n base_prompt = get_preparation_plan_prompt(job_role, company_name)\n enhanced_prompt = f\"\"\"{base_prompt}\n\nPlease provide a highly thorough, step-by-step preparation plan with multiple days of tasks, \ndetailed technical reviews, code examples where applicable, and at least 2000 words total. \nNo truncation or summaries—include the full content.\n\"\"\"\n society = construct_interview_assistant(job_role, company_name, detailed=detailed, limited_searches=limited_searches)\n society.task_prompt = enhanced_prompt\n \n # Use our wrapper function with strict limit of 5 rounds\n answer, chat_history, token_count = run_society_with_strict_limit(\n society, \n round_limit=5,\n progress_callback=progress_callback\n )\n \n duration = time.time() - start_time\n logging.info(f\"Completed preparation plan creation in {duration:.2f} seconds\")\n \n # Find any files that were generated\n generated_files = [str(file) for file in Path(INTERVIEW_PREP_DIR).glob(\"*\") if file.is_file()]\n \n return {\n \"answer\": answer,\n \"chat_history\": chat_history,\n \"token_count\": token_count,\n \"generated_files\": generated_files,\n \"duration_seconds\": duration\n }\n \n except Exception as e:\n logging.error(f\"Error in preparation plan creation: {str(e)}\", exc_info=True)\n raise\n\nif __name__ == \"__main__\":\n job_role = \"Machine Learning Engineer\"\n company_name = \"Google\"\n result = create_interview_prep_plan(job_role, company_name, detailed=True)\n print(f\"Answer: {result['answer']}\")\n print(f\"Generated files: {result['generated_files']}\")\n print(f\"Execution time: {result['duration_seconds']:.2f} seconds\")\n print(f\"Conversation rounds: {len(result['chat_history'])}\")"], ["/owl/community_usecase/stock-analysis/run.py", "# Stock Analysis Agent with AI Agents, using OWL 🦉\n# This is a stock analysis system based on OWL multi-agent technology\n# The system contains two core components:\n# 1. Stock Analysis Assistant - Provides comprehensive stock investment advice and analysis\n# 2. SEC Financial Data Analysis Assistant - Focuses on analyzing SEC files and financial statements\n# The system uses the 🦉(OWL) framework to coordinate multiple AI agents to complete complex stock analysis tasks\n\nfrom argparse import Namespace\nfrom typing import Any, List, Optional, Dict, Callable\nimport time\n\nimport os\nimport logging\nimport json\nimport argparse\n\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.types import ModelPlatformType,ModelType\nfrom colorama import Fore, Style\n\nfrom camel.toolkits import (\n SearchToolkit,\n FileWriteToolkit\n)\nfrom camel.societies import RolePlaying\nfrom camel.logger import set_log_level, get_logger\nfrom agent.sec_agent import get_sec_summary_for_company_tool\nfrom prompts import get_system_prompt\nfrom owl.utils import run_society\nfrom pathlib import Path\n\n# Load environment variables from .env file\nload_dotenv()\n\n# Create the log directory for debugging and logging purposes\nLOG_DIR = \"./log\"\nos.makedirs(LOG_DIR, exist_ok=True)\n\n# Create the output directory for interview preparation materials\nREPORT_DIR = \"./output\"\nos.makedirs(REPORT_DIR, exist_ok=True)\n\nset_log_level(level=\"INFO\")\nlogger = get_logger(__name__)\nfile_handler = logging.FileHandler(LOG_DIR+\"/stock_analysis.log\")\nfile_handler.setLevel(logging.DEBUG)\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nfile_handler.setFormatter(formatter)\nlogger.addHandler(file_handler)\n\nroot_logger = logging.getLogger()\nroot_logger.addHandler(file_handler)\n\n\ndef run_society_with_strict_limit(society, round_limit=5, progress_callback=None) -> tuple[str, List[dict[Any, Any]], dict[Any, Any]]:\n \"\"\"Wrapper around run_society to ensure round limit is strictly enforced\n \n This implementation hijacks the step method to force termination after a specific number of rounds.\n \"\"\"\n # Track rounds manually\n round_count = 0\n \n # Save original step function\n original_step = society.step\n \n # Override the step method\n def limited_step(*args, **kwargs):\n nonlocal round_count\n round_count += 1\n \n # Report progress if callback is provided\n if progress_callback and callable(progress_callback):\n progress_callback(round_count, round_limit)\n \n # Force termination after reaching the round limit\n if round_count >= round_limit:\n logger.info(f\"Reached round limit of {round_limit}, forcibly terminating.\")\n # Force a TASK_DONE in the user response to trigger termination\n result = original_step(*args, **kwargs)\n if len(result) >= 2 and hasattr(result[1], 'msgs') and result[1].msgs and len(result[1].msgs) > 0:\n result[1].msgs[0].content += \"\\n\\nTASK_DONE\"\n result[1].terminated = True\n return result\n \n return original_step(*args, **kwargs)\n \n # Replace the step method\n society.step = limited_step\n \n try:\n # Run the conversation with the standard run_society function\n answer, chat_history, token_count = run_society(society, round_limit=round_limit)\n \n # Add a note about the conversation being truncated\n if len(chat_history) > 0 and \"truncated_note\" not in chat_history[-1]:\n chat_history[-1][\"truncated_note\"] = True\n if \"assistant\" in chat_history[-1]:\n chat_history[-1][\"assistant\"] += \"\\n\\n[Note: This conversation was limited to maintain response quality.]\"\n \n return answer, chat_history, token_count\n \n finally:\n # Restore the original step method\n society.step = original_step\n\n\ndef construct_stock_analysis_society( company_name: str) -> RolePlaying:\n \"\"\"Construct a society of agents for the stock analysis.\n\n Args:\n task (str): Analyze relevant stock information and output a report.\n\n Returns:\n RolePlaying: A configured society of agents for the stock analysis.\n \"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.DEEPSEEK,\n model_type=ModelType.DEEPSEEK_CHAT,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.DEEPSEEK,\n model_type=ModelType.DEEPSEEK_CHAT,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n tools = [\n *FileWriteToolkit(output_dir=REPORT_DIR).get_tools(),\n SearchToolkit().search_baidu,\n get_sec_summary_for_company_tool\n \n ]\n\n if os.environ.get(\"GOOGLE_API_KEY\") and os.environ.get(\"SEARCH_ENGINE_ID\"):\n tools.append(SearchToolkit().search_google)\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Build enhanced prompt asking for full, detailed output\n base_prompt = get_system_prompt()\n enhanced_prompt = f\"\"\"{base_prompt}\nTask: Generate a comprehensive investment analysis report for {company_name}.\nRequirements:\n1. Research and collect company information:\n - Use search tools to gather general company background, industry position, and recent news\n - Utilize SEC tools to obtain financial statements and regulatory filings\n - Analyze key financial metrics and performance indicators\n\n2. Generate a detailed markdown report with the following sections:\n - Company Overview and Business Model\n - Industry Analysis and Market Position\n - Financial Analysis (last 3-5 years)\n * Revenue and Profit Trends\n * Balance Sheet Analysis\n * Cash Flow Analysis\n * Key Financial Ratios\n - Risk Assessment\n - Investment Recommendation\n\n3. Report Format Requirements:\n - Write in professional markdown format\n - Include data tables and key metrics\n - Minimum 2000 words comprehensive analysis\n - You MUST use the write_to_file tool to save the report as '{company_name}_investment_analysis.md'\n - Confirm the file has been written successfully before completing the task\n\"\"\"\n\n task_kwargs = {\n \"task_prompt\": enhanced_prompt,\n \"with_task_specify\": False,\n }\n\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"financial_analyst\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"investment_advisor\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\ndef save_chat_history(chat_history: List[dict[Any, Any]], company_name: str) -> None:\n \"\"\"Analyze chat history and extract tool call information.\"\"\"\n\n # 保存聊天历史记录到文件\n chat_history_file = os.path.join(LOG_DIR, f\"{company_name}_chat_history.json\")\n with open(chat_history_file, \"w\", encoding=\"utf-8\") as f:\n json.dump(chat_history, f, ensure_ascii=False, indent=2)\n\n print(f\"{Fore.GREEN}Records saved to {chat_history_file}{Style.RESET_ALL}\")\n\ndef parse_arguments() -> Namespace:\n \"\"\"Parse command line arguments\"\"\"\n parser = argparse.ArgumentParser(description='Stock Analysis Agent')\n parser.add_argument('--company', type=str, default=\"Google\", help='Company name to analyze')\n parser.add_argument('--use-agentops', action='store_true', help='Enable AgentOps tracking')\n parser.add_argument('--rounds', type=int, default=5, help='Maximum conversation rounds')\n return parser.parse_args()\n\ndef init_agentops(use_agentops) -> bool:\n \"\"\"Initialize AgentOps tracking (if enabled)\"\"\"\n if not use_agentops:\n return False\n \n import agentops\n agentops_api_key = os.getenv(\"AGENTOPS_API_KEY\")\n if agentops_api_key:\n agentops.init(agentops_api_key, default_tags=[\"Stock Analysis Agent using owl\"])\n print(f\"{Fore.GREEN}AgentOps tracking enabled{Style.RESET_ALL}\")\n return True\n else:\n print(f\"{Fore.YELLOW}Warning: AGENTOPS_API_KEY not set, AgentOps tracking disabled{Style.RESET_ALL}\")\n return False\n\ndef generate_stock_investment_report(\n company_name: str,\n round_limit: int = 5, \n progress_callback: Optional[Callable] = None\n) -> Dict[str, Any]:\n start_time = time.time()\n logging.info(f\"Starting stock investment report generation for {company_name})\")\n\n society = construct_stock_analysis_society(company_name=company_name)\n \n # Use our wrapper function to strictly enforce the round limit\n answer, chat_history, token_count = run_society_with_strict_limit(\n society, \n round_limit=round_limit,\n progress_callback=progress_callback\n )\n \n duration = time.time() - start_time\n logging.info(f\"Completed stock investment report generation for {company_name} in {duration:.2f} seconds\")\n \n # Find any files that were generated\n generated_files = [str(file) for file in Path(REPORT_DIR).glob(\"*\") if file.is_file()]\n \n return {\n \"answer\": answer,\n \"chat_history\": chat_history,\n \"token_count\": token_count,\n \"generated_files\": generated_files,\n \"duration_seconds\": duration\n }\n\nif __name__ == \"__main__\":\n # Parse command line arguments\n args = parse_arguments()\n \n # Initialize AgentOps (if needed)\n agentops_enabled = init_agentops(args.use_agentops)\n \n company_name = args.company\n max_rounds = args.rounds\n \n print(f\"{Fore.CYAN}=> Generating stock investment report for {company_name}...{Style.RESET_ALL}\")\n result = generate_stock_investment_report(company_name, round_limit=max_rounds)\n \n print(f\"{Fore.CYAN}=> Stock investment report generation completed!{Style.RESET_ALL}\")\n # Record tool usage history\n save_chat_history(chat_history=result['chat_history'], company_name=company_name)\n\n print(f\"{Fore.YELLOW}Answer: {Style.RESET_ALL}{result['answer']}\\n\")\n print(f\"{Fore.BLUE}Generated files: {Style.RESET_ALL}{result['generated_files']}\")\n print(f\"{Fore.MAGENTA}Token Count: {Style.RESET_ALL}{result['token_count']}\")\n print(f\"{Fore.GREEN}Execution time: {Style.RESET_ALL}{result['duration_seconds']:.2f} seconds\")\n"], ["/owl/owl/utils/document_toolkit.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\nfrom camel.loaders import UnstructuredIO\nfrom camel.toolkits.base import BaseToolkit\nfrom camel.toolkits.function_tool import FunctionTool\nfrom camel.toolkits import ImageAnalysisToolkit, ExcelToolkit\nfrom camel.utils import retry_on_error\nfrom camel.logger import get_logger\nfrom camel.models import BaseModelBackend\nfrom chunkr_ai import Chunkr\nimport requests\nimport mimetypes\nimport json\nfrom typing import List, Optional, Tuple, Literal\nfrom urllib.parse import urlparse\nimport os\nimport subprocess\nimport xmltodict\nimport nest_asyncio\nimport traceback\n\nnest_asyncio.apply()\n\nlogger = get_logger(__name__)\n\n\nclass DocumentProcessingToolkit(BaseToolkit):\n r\"\"\"A class representing a toolkit for processing document and return the content of the document.\n\n This class provides method for processing docx, pdf, pptx, etc. It cannot process excel files.\n \"\"\"\n\n def __init__(\n self, cache_dir: Optional[str] = None, model: Optional[BaseModelBackend] = None\n ):\n self.image_tool = ImageAnalysisToolkit(model=model)\n # self.audio_tool = AudioAnalysisToolkit()\n self.excel_tool = ExcelToolkit()\n\n self.cache_dir = \"tmp/\"\n if cache_dir:\n self.cache_dir = cache_dir\n\n self.uio = UnstructuredIO()\n\n @retry_on_error()\n def extract_document_content(self, document_path: str) -> Tuple[bool, str]:\n r\"\"\"Extract the content of a given document (or url) and return the processed text.\n It may filter out some information, resulting in inaccurate content.\n\n Args:\n document_path (str): The path of the document to be processed, either a local path or a URL. It can process image, audio files, zip files and webpages, etc.\n\n Returns:\n Tuple[bool, str]: A tuple containing a boolean indicating whether the document was processed successfully, and the content of the document (if success).\n \"\"\"\n\n logger.debug(\n f\"Calling extract_document_content function with document_path=`{document_path}`\"\n )\n\n if any(document_path.endswith(ext) for ext in [\".jpg\", \".jpeg\", \".png\"]):\n res = self.image_tool.ask_question_about_image(\n document_path, \"Please make a detailed caption about the image.\"\n )\n return True, res\n\n # if any(document_path.endswith(ext) for ext in ['.mp3', '.wav']):\n # res = self.audio_tool.ask_question_about_audio(document_path, \"Please transcribe the audio content to text.\")\n # return True, res\n\n if any(document_path.endswith(ext) for ext in [\"xls\", \"xlsx\"]):\n res = self.excel_tool.extract_excel_content(document_path)\n return True, res\n\n if any(document_path.endswith(ext) for ext in [\"zip\"]):\n extracted_files = self._unzip_file(document_path)\n return True, f\"The extracted files are: {extracted_files}\"\n\n if any(document_path.endswith(ext) for ext in [\"json\", \"jsonl\", \"jsonld\"]):\n with open(document_path, \"r\", encoding=\"utf-8\") as f:\n content = json.load(f)\n f.close()\n return True, content\n\n if any(document_path.endswith(ext) for ext in [\"py\"]):\n with open(document_path, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n f.close()\n return True, content\n\n if any(document_path.endswith(ext) for ext in [\"xml\"]):\n data = None\n with open(document_path, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n f.close()\n\n try:\n data = xmltodict.parse(content)\n logger.debug(f\"The extracted xml data is: {data}\")\n return True, data\n\n except Exception:\n logger.debug(f\"The raw xml data is: {content}\")\n return True, content\n\n if self._is_webpage(document_path):\n try:\n extracted_text = self._extract_webpage_content(document_path)\n return True, extracted_text\n except Exception:\n try:\n elements = self.uio.parse_file_or_url(document_path)\n if elements is None:\n logger.error(f\"Failed to parse the document: {document_path}.\")\n return False, f\"Failed to parse the document: {document_path}.\"\n else:\n # Convert elements list to string\n elements_str = \"\\n\".join(str(element) for element in elements)\n return True, elements_str\n except Exception:\n return False, \"Failed to extract content from the webpage.\"\n\n else:\n try:\n elements = self.uio.parse_file_or_url(document_path)\n if elements is None:\n logger.error(f\"Failed to parse the document: {document_path}.\")\n return False, f\"Failed to parse the document: {document_path}.\"\n else:\n # Convert elements list to string\n elements_str = \"\\n\".join(str(element) for element in elements)\n return True, elements_str\n\n except Exception as e:\n logger.error(traceback.format_exc())\n return False, f\"Error occurred while processing document: {e}\"\n\n def _is_webpage(self, url: str) -> bool:\n r\"\"\"Judge whether the given URL is a webpage.\"\"\"\n try:\n parsed_url = urlparse(url)\n is_url = all([parsed_url.scheme, parsed_url.netloc])\n if not is_url:\n return False\n\n path = parsed_url.path\n file_type, _ = mimetypes.guess_type(path)\n if file_type is not None and \"text/html\" in file_type:\n return True\n\n response = requests.head(url, allow_redirects=True, timeout=10)\n content_type = response.headers.get(\"Content-Type\", \"\").lower()\n\n if \"text/html\" in content_type:\n return True\n else:\n return False\n\n except requests.exceptions.RequestException as e:\n # raise RuntimeError(f\"Error while checking the URL: {e}\")\n logger.warning(f\"Error while checking the URL: {e}\")\n return False\n\n except TypeError:\n return True\n\n @retry_on_error()\n async def _extract_content_with_chunkr(\n self,\n document_path: str,\n output_format: Literal[\"json\", \"markdown\"] = \"markdown\",\n ) -> str:\n chunkr = Chunkr(api_key=os.getenv(\"CHUNKR_API_KEY\"))\n\n result = await chunkr.upload(document_path)\n\n # result = chunkr.upload(document_path)\n\n if result.status == \"Failed\":\n logger.error(\n f\"Error while processing document {document_path}: {result.message} using Chunkr.\"\n )\n return f\"Error while processing document: {result.message}\"\n\n # extract document name\n document_name = os.path.basename(document_path)\n output_file_path: str\n\n if output_format == \"json\":\n output_file_path = f\"{document_name}.json\"\n result.json(output_file_path)\n\n elif output_format == \"markdown\":\n output_file_path = f\"{document_name}.md\"\n result.markdown(output_file_path)\n\n else:\n return \"Invalid output format.\"\n\n with open(output_file_path, \"r\") as f:\n extracted_text = f.read()\n f.close()\n return extracted_text\n\n @retry_on_error()\n def _extract_webpage_content(self, url: str) -> str:\n api_key = os.getenv(\"FIRECRAWL_API_KEY\")\n from firecrawl import FirecrawlApp\n\n # Initialize the FirecrawlApp with your API key\n app = FirecrawlApp(api_key=api_key)\n\n data = app.crawl_url(\n url, params={\"limit\": 1, \"scrapeOptions\": {\"formats\": [\"markdown\"]}}\n )\n logger.debug(f\"Extractred data from {url}: {data}\")\n if len(data[\"data\"]) == 0:\n if data[\"success\"]:\n return \"No content found on the webpage.\"\n else:\n return \"Error while crawling the webpage.\"\n\n return str(data[\"data\"][0][\"markdown\"])\n\n def _download_file(self, url: str):\n r\"\"\"Download a file from a URL and save it to the cache directory.\"\"\"\n try:\n response = requests.get(url, stream=True)\n response.raise_for_status()\n file_name = url.split(\"/\")[-1]\n\n file_path = os.path.join(self.cache_dir, file_name)\n\n with open(file_path, \"wb\") as file:\n for chunk in response.iter_content(chunk_size=8192):\n file.write(chunk)\n\n return file_path\n\n except requests.exceptions.RequestException as e:\n print(f\"Error downloading the file: {e}\")\n\n def _get_formatted_time(self) -> str:\n import time\n\n return time.strftime(\"%m%d%H%M\")\n\n def _unzip_file(self, zip_path: str) -> List[str]:\n if not zip_path.endswith(\".zip\"):\n raise ValueError(\"Only .zip files are supported\")\n\n zip_name = os.path.splitext(os.path.basename(zip_path))[0]\n extract_path = os.path.join(self.cache_dir, zip_name)\n os.makedirs(extract_path, exist_ok=True)\n\n try:\n subprocess.run([\"unzip\", \"-o\", zip_path, \"-d\", extract_path], check=True)\n except subprocess.CalledProcessError as e:\n raise RuntimeError(f\"Failed to unzip file: {e}\")\n\n extracted_files = []\n for root, _, files in os.walk(extract_path):\n for file in files:\n extracted_files.append(os.path.join(root, file))\n\n return extracted_files\n\n def get_tools(self) -> List[FunctionTool]:\n r\"\"\"Returns a list of FunctionTool objects representing the functions in the toolkit.\n\n Returns:\n List[FunctionTool]: A list of FunctionTool objects representing the functions in the toolkit.\n \"\"\"\n return [\n FunctionTool(self.extract_document_content),\n ] # Added closing triple quotes here\n"], ["/owl/community_usecase/qwen3_mcp/run_mcp_qwen3.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport asyncio\nimport sys\nimport time\nfrom pathlib import Path\nfrom typing import List, Dict, Any\n\nfrom colorama import Fore, init\nfrom dotenv import load_dotenv\n\nfrom camel.agents.chat_agent import ToolCallingRecord\nfrom camel.models import ModelFactory\nfrom camel.toolkits import FunctionTool, MCPToolkit\nfrom camel.types import ModelPlatformType, ModelType\n\nfrom owl.utils.enhanced_role_playing import OwlRolePlaying\n\nimport pathlib\n\n# Initialize colorama for cross-platform colored terminal output\ninit()\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\n\nasync def construct_society(\n question: str,\n tools: List[FunctionTool],\n) -> OwlRolePlaying:\n r\"\"\"Build a multi-agent OwlRolePlaying instance for task completion.\n\n Args:\n question (str): The task to perform.\n tools (List[FunctionTool]): The MCP tools to use for interaction.\n\n Returns:\n OwlRolePlaying: The configured society of agents.\n \"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_PLUS_LATEST,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_PLUS_LATEST,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\n \"model\": models[\"assistant\"],\n \"tools\": tools,\n }\n\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n society = OwlRolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n return society\n\n\ndef create_md_file(task: str) -> str:\n \"\"\"Create a markdown file for the conversation with timestamp in filename.\n \n Args:\n task (str): The task being performed.\n \n Returns:\n str: Path to the created markdown file.\n \"\"\"\n timestamp = time.strftime(\"%Y%m%d_%H%M%S\")\n # Create logs directory if it doesn't exist\n logs_dir = Path(\"conversation_logs\")\n logs_dir.mkdir(exist_ok=True)\n \n # Create a shortened task name for the filename\n task_short = task[:30].replace(\" \", \"_\").replace(\"/\", \"_\")\n filename = f\"{logs_dir}/conversation_{timestamp}_{task_short}.md\"\n \n # Initialize the file with header\n with open(filename, \"w\", encoding=\"utf-8\") as f:\n f.write(f\"# Agent Conversation: {task}\\n\\n\")\n f.write(f\"*Generated on: {time.strftime('%Y-%m-%d %H:%M:%S')}*\\n\\n\")\n f.write(\"## Task Details\\n\\n\")\n f.write(f\"**Task:** {task}\\n\\n\")\n f.write(\"## Conversation\\n\\n\")\n \n return filename\n\n\ndef write_to_md(filename: str, content: Dict[str, Any]) -> None:\n \"\"\"Write content to the markdown file.\n \n Args:\n filename (str): Path to the markdown file.\n content (Dict[str, Any]): Content to write to the file.\n \"\"\"\n with open(filename, \"a\", encoding=\"utf-8\") as f:\n if \"system_info\" in content:\n f.write(f\"### System Information\\n\\n\")\n for key, value in content[\"system_info\"].items():\n f.write(f\"**{key}:** {value}\\n\\n\")\n \n if \"assistant\" in content:\n f.write(f\"### 🤖 Assistant\\n\\n\")\n if \"tool_calls\" in content:\n f.write(\"**Tool Calls:**\\n\\n\")\n for tool_call in content[\"tool_calls\"]:\n f.write(f\"```\\n{tool_call}\\n```\\n\\n\")\n f.write(f\"{content['assistant']}\\n\\n\")\n \n if \"user\" in content:\n f.write(f\"### 👤 User\\n\\n\")\n f.write(f\"{content['user']}\\n\\n\")\n \n if \"summary\" in content:\n f.write(f\"## Summary\\n\\n\")\n f.write(f\"{content['summary']}\\n\\n\")\n\n\nasync def run_society_with_formatted_output(society: OwlRolePlaying, md_filename: str, round_limit: int = 15):\n \"\"\"Run the society with nicely formatted terminal output and write to markdown.\n \n Args:\n society (OwlRolePlaying): The society to run.\n md_filename (str): Path to the markdown file for output.\n round_limit (int, optional): Maximum number of conversation rounds. Defaults to 15.\n \n Returns:\n tuple: (answer, chat_history, token_count)\n \"\"\"\n print(Fore.GREEN + f\"AI Assistant sys message:\\n{society.assistant_sys_msg}\\n\")\n print(Fore.BLUE + f\"AI User sys message:\\n{society.user_sys_msg}\\n\")\n \n print(Fore.YELLOW + f\"Original task prompt:\\n{society.task_prompt}\\n\")\n print(Fore.CYAN + \"Specified task prompt:\" + f\"\\n{society.specified_task_prompt}\\n\")\n print(Fore.RED + f\"Final task prompt:\\n{society.task_prompt}\\n\")\n \n # Write system information to markdown\n write_to_md(md_filename, {\n \"system_info\": {\n \"AI Assistant System Message\": society.assistant_sys_msg,\n \"AI User System Message\": society.user_sys_msg,\n \"Original Task Prompt\": society.task_prompt,\n \"Specified Task Prompt\": society.specified_task_prompt,\n \"Final Task Prompt\": society.task_prompt\n }\n })\n \n input_msg = society.init_chat()\n chat_history = []\n overall_completion_token_count = 0\n overall_prompt_token_count = 0\n n = 0\n \n while n < round_limit:\n n += 1\n assistant_response, user_response = await society.astep(input_msg)\n\n overall_completion_token_count += assistant_response.info[\"usage\"].get(\n \"completion_tokens\", 0\n ) + user_response.info[\"usage\"].get(\"completion_tokens\", 0)\n overall_prompt_token_count += assistant_response.info[\"usage\"].get(\n \"prompt_tokens\", 0\n ) + user_response.info[\"usage\"].get(\"prompt_tokens\", 0)\n\n token_info = {\n \"completion_token_count\": overall_completion_token_count,\n \"prompt_token_count\": overall_prompt_token_count,\n }\n \n md_content = {}\n \n if assistant_response.terminated:\n termination_msg = f\"AI Assistant terminated. Reason: {assistant_response.info['termination_reasons']}.\"\n print(Fore.GREEN + termination_msg)\n md_content[\"summary\"] = termination_msg\n write_to_md(md_filename, md_content)\n break\n \n if user_response.terminated:\n termination_msg = f\"AI User terminated. Reason: {user_response.info['termination_reasons']}.\"\n print(Fore.GREEN + termination_msg)\n md_content[\"summary\"] = termination_msg\n write_to_md(md_filename, md_content)\n break\n \n # Handle tool calls for both terminal and markdown\n if \"tool_calls\" in assistant_response.info:\n tool_calls: List[ToolCallingRecord] = [\n ToolCallingRecord(**call.as_dict())\n for call in assistant_response.info['tool_calls']\n ]\n md_content[\"tool_calls\"] = tool_calls\n \n # Print to terminal\n print(Fore.GREEN + \"AI Assistant:\")\n for func_record in tool_calls:\n print(f\"{func_record}\")\n else:\n print(Fore.GREEN + \"AI Assistant:\")\n \n # Print assistant response to terminal\n print(f\"{assistant_response.msg.content}\\n\")\n \n # Print user response to terminal\n print(Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\")\n \n # Build content for markdown file\n md_content[\"assistant\"] = assistant_response.msg.content\n md_content[\"user\"] = user_response.msg.content\n \n # Write to markdown\n write_to_md(md_filename, md_content)\n \n # Update chat history\n chat_history.append({\n \"assistant\": assistant_response.msg.content,\n \"user\": user_response.msg.content,\n })\n \n if \"TASK_DONE\" in user_response.msg.content:\n task_done_msg = \"Task completed successfully!\"\n print(Fore.YELLOW + task_done_msg + \"\\n\")\n write_to_md(md_filename, {\"summary\": task_done_msg})\n break\n \n input_msg = assistant_response.msg\n \n # Write token count information\n write_to_md(md_filename, token_info)\n \n # Extract final answer\n answer = assistant_response.msg.content if assistant_response and assistant_response.msg else \"\"\n \n return answer, chat_history, token_info\n\n\nasync def main():\n # Load SSE server configuration\n config_path = Path(__file__).parent / \"mcp_sse_config.json\"\n \n # Set default task - a simple example query\n default_task = (\n \"Visit the Qwen3 GitHub repository, summarize the introduction of the repository.\"\n \"Write a comprehensive HTML documentation site with the following features:\"\n \"A clear introduction to Qwen3\"\n \"Well-organized sections of the technical documentation\"\n \"Practical code examples\"\n \"A visually appealing purple technology theme (e.g. modern, clean, purple-accented design)\"\n \"Finally, deploy the HTML site and open it in the browser.\"\n )\n \n # Use command line argument if provided, otherwise use default task\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n \n mcp_toolkit = MCPToolkit(config_path=str(config_path), strict=True)\n \n try:\n # Create markdown file for conversation export\n md_filename = create_md_file(task)\n print(Fore.CYAN + f\"Conversation will be saved to: {md_filename}\")\n \n await mcp_toolkit.connect()\n print(Fore.GREEN + \"Successfully connected to SSE server\")\n \n # Get available tools\n tools = [*mcp_toolkit.get_tools()]\n \n # Build and run society\n print(Fore.YELLOW + f\"Starting task: {task}\\n\")\n society = await construct_society(task, tools)\n answer, chat_history, token_info = await run_society_with_formatted_output(society, md_filename)\n \n print(Fore.GREEN + f\"\\nFinal Result: {answer}\")\n print(Fore.CYAN + f\"Total tokens used: {token_info}\")\n print(Fore.CYAN + f\"Full conversation log saved to: {md_filename}\")\n \n except KeyboardInterrupt:\n print(Fore.YELLOW + \"\\nReceived exit signal, shutting down...\")\n except Exception as e:\n print(Fore.RED + f\"Error occurred: {e}\")\n finally:\n print(Fore.YELLOW + \"Shutting down connections...\")\n try:\n await asyncio.wait_for(\n asyncio.shield(mcp_toolkit.disconnect()), \n timeout=3.0\n )\n print(Fore.GREEN + \"Successfully disconnected\")\n except asyncio.TimeoutError:\n print(Fore.YELLOW + \"Disconnect timed out, but program will exit safely\")\n except asyncio.CancelledError:\n print(Fore.YELLOW + \"Disconnect was cancelled, but program will exit safely\")\n except Exception as e:\n print(Fore.RED + f\"Error during disconnect: {e}\")\n \n try:\n await asyncio.sleep(0.5)\n except:\n pass\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n"], ["/owl/owl/utils/enhanced_role_playing.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\nfrom typing import Dict, List, Optional, Tuple\nimport threading\n\n\nfrom camel.agents import ChatAgent\nfrom camel.responses import ChatAgentResponse\nfrom camel.messages.base import BaseMessage\nfrom camel.societies import RolePlaying\nfrom camel.logger import get_logger\n\n\nfrom copy import deepcopy\n\nlogger = get_logger(__name__)\n\n\nclass OwlRolePlaying(RolePlaying):\n def __init__(self, **kwargs):\n self.user_role_name = kwargs.get(\"user_role_name\", \"user\")\n self.assistant_role_name = kwargs.get(\"assistant_role_name\", \"assistant\")\n\n self.output_language = kwargs.get(\"output_language\", None)\n\n self.user_agent_kwargs: dict = kwargs.get(\"user_agent_kwargs\", {})\n self.assistant_agent_kwargs: dict = kwargs.get(\"assistant_agent_kwargs\", {})\n\n self.output_language = kwargs.get(\"output_language\", None)\n\n super().__init__(**kwargs)\n\n init_user_sys_msg, init_assistant_sys_msg = self._construct_gaia_sys_msgs()\n\n self.assistant_agent: ChatAgent\n self.user_agent: ChatAgent\n self.assistant_sys_msg: Optional[BaseMessage]\n self.user_sys_msg: Optional[BaseMessage]\n\n # self.is_reasoning_task = self._judge_if_reasoning_task(self.task_prompt)\n\n # if self.is_reasoning_task:\n # logger.info(\"The task is judged as a reasoning or coding task. The assistant agent will use the reasoning model O3-MINI.\")\n # else:\n # logger.info(\"The assistant agent will use the default model.\")\n\n self._init_agents(\n init_assistant_sys_msg,\n init_user_sys_msg,\n assistant_agent_kwargs=self.assistant_agent_kwargs,\n user_agent_kwargs=self.user_agent_kwargs,\n output_language=self.output_language,\n # is_reasoning_task=self.is_reasoning_task\n )\n\n def _init_agents(\n self,\n init_assistant_sys_msg: BaseMessage,\n init_user_sys_msg: BaseMessage,\n assistant_agent_kwargs: Optional[Dict] = None,\n user_agent_kwargs: Optional[Dict] = None,\n output_language: Optional[str] = None,\n is_reasoning_task: bool = False,\n stop_event: Optional[threading.Event] = None,\n ) -> None:\n r\"\"\"Initialize assistant and user agents with their system messages.\n\n Args:\n init_assistant_sys_msg (BaseMessage): Assistant agent's initial\n system message.\n init_user_sys_msg (BaseMessage): User agent's initial system\n message.\n assistant_agent_kwargs (Dict, optional): Additional arguments to\n pass to the assistant agent. (default: :obj:`None`)\n user_agent_kwargs (Dict, optional): Additional arguments to\n pass to the user agent. (default: :obj:`None`)\n output_language (str, optional): The language to be output by the\n agents. (default: :obj:`None`)\n \"\"\"\n if self.model is not None:\n if assistant_agent_kwargs is None:\n assistant_agent_kwargs = {\"model\": self.model}\n elif \"model\" not in assistant_agent_kwargs:\n assistant_agent_kwargs.update(dict(model=self.model))\n if user_agent_kwargs is None:\n user_agent_kwargs = {\"model\": self.model}\n elif \"model\" not in user_agent_kwargs:\n user_agent_kwargs.update(dict(model=self.model))\n\n # # If the task is a reasoning task, the assistant agent should use the reasoning model O3-MINI\n # if is_reasoning_task:\n # assistant_agent_kwargs['model'] = ModelFactory.create(\n # model_platform=ModelPlatformType.OPENAI,\n # model_type=ModelType.O3_MINI,\n # )\n\n self.assistant_agent = ChatAgent(\n init_assistant_sys_msg,\n output_language=output_language,\n **(assistant_agent_kwargs or {}),\n )\n self.assistant_sys_msg = self.assistant_agent.system_message\n\n self.user_agent = ChatAgent(\n init_user_sys_msg,\n output_language=output_language,\n **(user_agent_kwargs or {}),\n )\n self.user_sys_msg = self.user_agent.system_message\n\n # def _judge_if_reasoning_task(self, question: str) -> bool:\n # r\"\"\"Judge if the question is a reasoning task.\"\"\"\n\n # LLM = OpenAIModel(model_type=ModelType.O3_MINI)\n # prompt = f\"\"\"\n # Please judge whether the following question is a reasoning or coding task, which can be solved by reasoning without leveraging external resources, or is suitable for writing code to solve the task.\n # If it is a reasoning or coding task, please return only \"yes\".\n # If it is not a reasoning or coding task, please return only \"no\".\n # Note:\n # - If the question required some world knowledge to answer the question, please carefully judge it, because the model's own knowledge is often unreliable.\n # - If it is suitable for writing codes (e.g. process excel files, write simulation codes, etc.), in most cases, it can be considered as a coding task.\n # Question: {question}\n # \"\"\"\n # messages = [{\"role\": \"user\", \"content\": prompt}]\n # resp = LLM.run(messages)\n # if 'yes' in resp.choices[0].message.content.lower():\n # return True\n # else:\n # return False\n\n def _construct_gaia_sys_msgs(self):\n user_system_prompt = f\"\"\"\n===== RULES OF USER =====\nNever forget you are a user and I am a assistant. Never flip roles! You will always instruct me. We share a common interest in collaborating to successfully complete a task.\nI must help you to complete a difficult task.\nYou must instruct me based on my expertise and your needs to solve the task step by step. The format of your instruction is: `Instruction: [YOUR INSTRUCTION]`, where \"Instruction\" describes a sub-task or question.\nYou must give me one instruction at a time.\nI must write a response that appropriately solves the requested instruction.\nYou should instruct me not ask me questions.\n\nPlease note that the task may be very complicated. Do not attempt to solve the task by single step. You must instruct me to find the answer step by step.\nHere are some tips that will help you to give more valuable instructions about our task to me:\n\n- I have various tools to use, such as search toolkit, web browser simulation toolkit, document relevant toolkit, code execution toolkit, etc. Thus, You must think how human will solve the task step-by-step, and give me instructions just like that. For example, one may first use google search to get some initial information and the target url, then retrieve the content of the url, or do some web browser interaction to find the answer.\n- Although the task is complex, the answer does exist. If you can't find the answer using the current scheme, try to re-plan and use other ways to find the answer, e.g. using other tools or methods that can achieve similar results.\n- Always remind me to verify my final answer about the overall task. This work can be done by using multiple tools(e.g., screenshots, webpage analysis, etc.), or something else.\n- If I have written code, please remind me to run the code and get the result.\n- Search results typically do not provide precise answers. It is not likely to find the answer directly using search toolkit only, the search query should be concise and focuses on finding sources rather than direct answers, as it always need to use other tools to further process the url, e.g. interact with the webpage, extract webpage content, etc. \n- If the question mentions youtube video, in most cases you have to process the content of the mentioned video.\n- For downloading files, you can either use the web browser simulation toolkit or write codes (for example, the github content can be downloaded via https://raw.githubusercontent.com/...).\n- Flexibly write codes to solve some problems, such as excel relevant tasks.\n\n\nNow, here is the overall task: {self.task_prompt}. Never forget our task!\n\nNow you must start to instruct me to solve the task step-by-step. Do not add anything else other than your instruction!\nKeep giving me instructions until you think the task is completed.\nWhen the task is completed, you must only reply with a single word .\nNever say unless my responses have solved your task.\n \"\"\"\n\n assistant_system_prompt = f\"\"\"\n===== RULES OF ASSISTANT =====\nNever forget you are a assistant and I am a user. Never flip roles! Never instruct me! You have to utilize your available tools to solve the task I assigned.\nWe share a common interest in collaborating to successfully complete a complex task.\nYou must help me to complete the task.\n\nHere is our overall task: {self.task_prompt}. Never forget our task!\n\nI must instruct you based on your expertise and my needs to complete the task. An instruction is typically a sub-task or question.\n\nYou must leverage your available tools, try your best to solve the problem, and explain your solutions.\nUnless I say the task is completed, you should always start with:\nSolution: [YOUR_SOLUTION]\n[YOUR_SOLUTION] should be specific, including detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.\n\nPlease note that our overall task may be very complicated. Here are some tips that may help you solve the task:\n\n- If one way fails to provide an answer, try other ways or methods. The answer does exists.\n- If the search snippet is unhelpful but the URL comes from an authoritative source, try visit the website for more details. \n- When looking for specific numerical values (e.g., dollar amounts), prioritize reliable sources and avoid relying only on search snippets. \n- When solving tasks that require web searches, check Wikipedia first before exploring other websites. \n- When trying to solve math problems, you can try to write python code and use sympy library to solve the problem.\n- Always verify the accuracy of your final answers! Try cross-checking the answers by other ways. (e.g., screenshots, webpage analysis, etc.). \n- Do not be overly confident in your own knowledge. Searching can provide a broader perspective and help validate existing knowledge. \n- After writing codes, do not forget to run the code and get the result. If it encounters an error, try to debug it. Also, bear in mind that the code execution environment does not support interactive input.\n- When a tool fails to run, or the code does not run correctly, never assume that it returns the correct result and continue to reason based on the assumption, because the assumed result cannot lead you to the correct answer. The right way is to think about the reason for the error and try again.\n- Search results typically do not provide precise answers. It is not likely to find the answer directly using search toolkit only, the search query should be concise and focuses on finding sources rather than direct answers, as it always need to use other tools to further process the url, e.g. interact with the webpage, extract webpage content, etc. \n- For downloading files, you can either use the web browser simulation toolkit or write codes.\n\n\n \"\"\"\n\n user_sys_msg = BaseMessage.make_user_message(\n role_name=self.user_role_name, content=user_system_prompt\n )\n\n assistant_sys_msg = BaseMessage.make_assistant_message(\n role_name=self.assistant_role_name, content=assistant_system_prompt\n )\n\n return user_sys_msg, assistant_sys_msg\n\n def step(\n self, assistant_msg: BaseMessage\n ) -> Tuple[ChatAgentResponse, ChatAgentResponse]:\n user_response = self.user_agent.step(assistant_msg)\n if user_response.terminated or user_response.msgs is None:\n return (\n ChatAgentResponse(msgs=[], terminated=False, info={}),\n ChatAgentResponse(\n msgs=[],\n terminated=user_response.terminated,\n info=user_response.info,\n ),\n )\n user_msg = self._reduce_message_options(user_response.msgs)\n\n modified_user_msg = deepcopy(user_msg)\n\n if \"TASK_DONE\" not in user_msg.content:\n modified_user_msg.content += f\"\"\"\\n\n Here are auxiliary information about the overall task, which may help you understand the intent of the current task:\n \n {self.task_prompt}\n \n If there are available tools and you want to call them, never say 'I will ...', but first call the tool and reply based on tool call's result, and tell me which tool you have called.\n \"\"\"\n\n else:\n # The task is done, and the assistant agent need to give the final answer about the original task\n modified_user_msg.content += f\"\"\"\\n\n Now please make a final answer of the original task based on our conversation : {self.task_prompt}\n \"\"\"\n\n # process assistant's response\n assistant_response = self.assistant_agent.step(modified_user_msg)\n if assistant_response.terminated or assistant_response.msgs is None:\n return (\n ChatAgentResponse(\n msgs=[],\n terminated=assistant_response.terminated,\n info=assistant_response.info,\n ),\n ChatAgentResponse(\n msgs=[user_msg], terminated=False, info=user_response.info\n ),\n )\n assistant_msg = self._reduce_message_options(assistant_response.msgs)\n\n modified_assistant_msg = deepcopy(assistant_msg)\n if \"TASK_DONE\" not in user_msg.content:\n modified_assistant_msg.content += f\"\"\"\\n\n Provide me with the next instruction and input (if needed) based on my response and our current task: {self.task_prompt}\n Before producing the final answer, please check whether I have rechecked the final answer using different toolkit as much as possible. If not, please remind me to do that.\n If I have written codes, remind me to run the codes.\n If you think our task is done, reply with `TASK_DONE` to end our conversation.\n \"\"\"\n\n # return the modified messages\n return (\n ChatAgentResponse(\n msgs=[modified_assistant_msg],\n terminated=assistant_response.terminated,\n info=assistant_response.info,\n ),\n ChatAgentResponse(\n msgs=[modified_user_msg],\n terminated=user_response.terminated,\n info=user_response.info,\n ),\n )\n\n async def astep(\n self, assistant_msg: BaseMessage\n ) -> Tuple[ChatAgentResponse, ChatAgentResponse]:\n user_response = await self.user_agent.astep(assistant_msg)\n if user_response.terminated or user_response.msgs is None:\n return (\n ChatAgentResponse(msgs=[], terminated=False, info={}),\n ChatAgentResponse(\n msgs=[],\n terminated=user_response.terminated,\n info=user_response.info,\n ),\n )\n user_msg = self._reduce_message_options(user_response.msgs)\n\n modified_user_msg = deepcopy(user_msg)\n\n if \"TASK_DONE\" not in user_msg.content:\n modified_user_msg.content += f\"\"\"\\n\n Here are auxiliary information about the overall task, which may help you understand the intent of the current task:\n \n {self.task_prompt}\n \n If there are available tools and you want to call them, never say 'I will ...', but first call the tool and reply based on tool call's result, and tell me which tool you have called.\n \"\"\"\n\n else:\n # The task is done, and the assistant agent need to give the final answer about the original task\n modified_user_msg.content += f\"\"\"\\n\n Now please make a final answer of the original task based on our conversation : {self.task_prompt}\n \"\"\"\n\n assistant_response = await self.assistant_agent.astep(modified_user_msg)\n if assistant_response.terminated or assistant_response.msgs is None:\n return (\n ChatAgentResponse(\n msgs=[],\n terminated=assistant_response.terminated,\n info=assistant_response.info,\n ),\n ChatAgentResponse(\n msgs=[user_msg], terminated=False, info=user_response.info\n ),\n )\n assistant_msg = self._reduce_message_options(assistant_response.msgs)\n\n modified_assistant_msg = deepcopy(assistant_msg)\n if \"TASK_DONE\" not in user_msg.content:\n modified_assistant_msg.content += f\"\"\"\\n\n Provide me with the next instruction and input (if needed) based on my response and our current task: {self.task_prompt}\n Before producing the final answer, please check whether I have rechecked the final answer using different toolkit as much as possible. If not, please remind me to do that.\n If I have written codes, remind me to run the codes.\n If you think our task is done, reply with `TASK_DONE` to end our conversation.\n \"\"\"\n\n return (\n ChatAgentResponse(\n msgs=[assistant_msg],\n terminated=assistant_response.terminated,\n info=assistant_response.info,\n ),\n ChatAgentResponse(\n msgs=[user_msg],\n terminated=user_response.terminated,\n info=user_response.info,\n ),\n )\n\n\nclass OwlGAIARolePlaying(OwlRolePlaying):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def step(\n self, assistant_msg: BaseMessage\n ) -> Tuple[ChatAgentResponse, ChatAgentResponse]:\n user_response = self.user_agent.step(assistant_msg)\n if user_response.terminated or user_response.msgs is None:\n return (\n ChatAgentResponse(msgs=[], terminated=False, info={}),\n ChatAgentResponse(\n msgs=[],\n terminated=user_response.terminated,\n info=user_response.info,\n ),\n )\n user_msg = self._reduce_message_options(user_response.msgs)\n\n modified_user_msg = deepcopy(user_msg)\n\n if \"TASK_DONE\" not in user_msg.content:\n modified_user_msg.content += f\"\"\"\\n\n Here are auxiliary information about the overall task, which may help you understand the intent of the current task:\n \n {self.task_prompt}\n \n If there are available tools and you want to call them, never say 'I will ...', but first call the tool and reply based on tool call's result, and tell me which tool you have called.\n \"\"\"\n\n else:\n # The task is done, and the assistant agent need to give the final answer about the original task\n modified_user_msg.content += f\"\"\"\\n\n Now please make a final answer of the original task based on our conversation : {self.task_prompt}\n Please pay special attention to the format in which the answer is presented.\n You should first analyze the answer format required by the question and then output the final answer that meets the format requirements. \n Your response should include the following content:\n - `analysis`: enclosed by , a detailed analysis of the reasoning result.\n - `final_answer`: enclosed by , the final answer to the question.\n Here are some hint about the final answer:\n \n Your final answer must be output exactly in the format specified by the question. It should be a number OR as few words as possible OR a comma separated list of numbers and/or strings:\n - If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. \n - If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. \n - If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.\n \n \"\"\"\n\n # process assistant's response\n assistant_response = self.assistant_agent.step(modified_user_msg)\n if assistant_response.terminated or assistant_response.msgs is None:\n return (\n ChatAgentResponse(\n msgs=[],\n terminated=assistant_response.terminated,\n info=assistant_response.info,\n ),\n ChatAgentResponse(\n msgs=[user_msg], terminated=False, info=user_response.info\n ),\n )\n assistant_msg = self._reduce_message_options(assistant_response.msgs)\n\n modified_assistant_msg = deepcopy(assistant_msg)\n if \"TASK_DONE\" not in user_msg.content:\n modified_assistant_msg.content += f\"\"\"\\n\n Provide me with the next instruction and input (if needed) based on my response and our current task: {self.task_prompt}\n Before producing the final answer, please check whether I have rechecked the final answer using different toolkit as much as possible. If not, please remind me to do that.\n If I have written codes, remind me to run the codes.\n If you think our task is done, reply with `TASK_DONE` to end our conversation.\n \"\"\"\n\n # return the modified messages\n return (\n ChatAgentResponse(\n msgs=[modified_assistant_msg],\n terminated=assistant_response.terminated,\n info=assistant_response.info,\n ),\n ChatAgentResponse(\n msgs=[modified_user_msg],\n terminated=user_response.terminated,\n info=user_response.info,\n ),\n )\n\n\ndef run_society(\n society: OwlRolePlaying,\n round_limit: int = 15,\n) -> Tuple[str, List[dict], dict]:\n overall_completion_token_count = 0\n overall_prompt_token_count = 0\n\n chat_history = []\n init_prompt = \"\"\"\n Now please give me instructions to solve over overall task step by step. If the task requires some specific knowledge, please instruct me to use tools to complete the task.\n \"\"\"\n input_msg = society.init_chat(init_prompt)\n for _round in range(round_limit):\n assistant_response, user_response = society.step(input_msg)\n # Check if usage info is available before accessing it\n if assistant_response.info.get(\"usage\") and user_response.info.get(\"usage\"):\n overall_completion_token_count += assistant_response.info[\"usage\"].get(\n \"completion_tokens\", 0\n ) + user_response.info[\"usage\"].get(\"completion_tokens\", 0)\n overall_prompt_token_count += assistant_response.info[\"usage\"].get(\n \"prompt_tokens\", 0\n ) + user_response.info[\"usage\"].get(\"prompt_tokens\", 0)\n\n # convert tool call to dict\n tool_call_records: List[dict] = []\n if assistant_response.info.get(\"tool_calls\"):\n for tool_call in assistant_response.info[\"tool_calls\"]:\n tool_call_records.append(tool_call.as_dict())\n\n _data = {\n \"user\": user_response.msg.content\n if hasattr(user_response, \"msg\") and user_response.msg\n else \"\",\n \"assistant\": assistant_response.msg.content\n if hasattr(assistant_response, \"msg\") and assistant_response.msg\n else \"\",\n \"tool_calls\": tool_call_records,\n }\n\n chat_history.append(_data)\n logger.info(\n f\"Round #{_round} user_response:\\n {user_response.msgs[0].content if user_response.msgs and len(user_response.msgs) > 0 else ''}\"\n )\n logger.info(\n f\"Round #{_round} assistant_response:\\n {assistant_response.msgs[0].content if assistant_response.msgs and len(assistant_response.msgs) > 0 else ''}\"\n )\n\n if (\n assistant_response.terminated\n or user_response.terminated\n or \"TASK_DONE\" in user_response.msg.content\n ):\n break\n\n input_msg = assistant_response.msg\n\n answer = chat_history[-1][\"assistant\"]\n token_info = {\n \"completion_token_count\": overall_completion_token_count,\n \"prompt_token_count\": overall_prompt_token_count,\n }\n\n return answer, chat_history, token_info\n\n\nasync def arun_society(\n society: OwlRolePlaying,\n round_limit: int = 15,\n) -> Tuple[str, List[dict], dict]:\n overall_completion_token_count = 0\n overall_prompt_token_count = 0\n\n chat_history = []\n init_prompt = \"\"\"\n Now please give me instructions to solve over overall task step by step. If the task requires some specific knowledge, please instruct me to use tools to complete the task.\n \"\"\"\n input_msg = society.init_chat(init_prompt)\n for _round in range(round_limit):\n assistant_response, user_response = await society.astep(input_msg)\n # Check if usage info is available before accessing it\n if assistant_response.info.get(\"usage\") and user_response.info.get(\"usage\"):\n overall_prompt_token_count += assistant_response.info[\"usage\"].get(\n \"completion_tokens\", 0\n )\n overall_prompt_token_count += assistant_response.info[\"usage\"].get(\n \"prompt_tokens\", 0\n ) + user_response.info[\"usage\"].get(\"prompt_tokens\", 0)\n\n # convert tool call to dict\n tool_call_records: List[dict] = []\n if assistant_response.info.get(\"tool_calls\"):\n for tool_call in assistant_response.info[\"tool_calls\"]:\n tool_call_records.append(tool_call.as_dict())\n\n _data = {\n \"user\": user_response.msg.content\n if hasattr(user_response, \"msg\") and user_response.msg\n else \"\",\n \"assistant\": assistant_response.msg.content\n if hasattr(assistant_response, \"msg\") and assistant_response.msg\n else \"\",\n \"tool_calls\": tool_call_records,\n }\n\n chat_history.append(_data)\n logger.info(\n f\"Round #{_round} user_response:\\n {user_response.msgs[0].content if user_response.msgs and len(user_response.msgs) > 0 else ''}\"\n )\n logger.info(\n f\"Round #{_round} assistant_response:\\n {assistant_response.msgs[0].content if assistant_response.msgs and len(assistant_response.msgs) > 0 else ''}\"\n )\n\n # Check other termination conditions\n if (\n assistant_response.terminated\n or user_response.terminated\n or \"TASK_DONE\" in user_response.msg.content\n or \"任务已完成\" in user_response.msg.content\n ):\n break\n\n input_msg = assistant_response.msg\n\n answer = chat_history[-1][\"assistant\"]\n token_info = {\n \"completion_token_count\": overall_completion_token_count,\n \"prompt_token_count\": overall_prompt_token_count,\n }\n\n return answer, chat_history, token_info\n"], ["/owl/community_usecase/excel_analyzer/data_analyzer_en.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport os\nimport sys\n\n\nfrom dotenv import load_dotenv\nfrom camel.configs import ChatGPTConfig\nfrom camel.models import ModelFactory\nfrom camel.messages.base import BaseMessage\n\nfrom camel.toolkits import (\n CodeExecutionToolkit,\n ExcelToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType\n\nfrom owl.utils import OwlRolePlaying\nfrom typing import Dict, List, Optional, Tuple\nfrom camel.logger import set_log_level, set_log_file, get_logger\n\nimport pathlib\n\nlogger = get_logger(__name__)\n\nbase_dir = pathlib.Path(__file__).parent.parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\nclass ExcelRolePalying(OwlRolePlaying):\n def _construct_gaia_sys_msgs(self):\n user_system_prompt = f\"\"\"\n===== RULES OF USER =====\nNever forget you are a user and I am a assistant. Never flip roles! You will always instruct me. We share a common interest in collaborating to successfully complete a task.\nI must help you to complete a difficult task.\nYou must instruct me based on my expertise and your needs to solve the task step by step. The format of your instruction is: `Instruction: [YOUR INSTRUCTION]`, where \"Instruction\" describes a sub-task or question.\nYou must give me one instruction at a time.\nI must write a response that appropriately solves the requested instruction.\nYou should instruct me not ask me questions.\n\nPlease note that the task may be very complicated. Do not attempt to solve the task by single step. You must instruct me to find the answer step by step.\nHere are some tips that will help you to give more valuable instructions about our task to me:\n\n- I can use various tools, such as Excel Toolkit and Code Execution Toolkit. \n\n- Although the task may be complex, the answer exists. \n If you find that the current approach does not lead to the answer, reconsider the task, and use alternative methods or tools to achieve the same goal. \n\n- Always remind me to verify whether the final answer is correct! \n This can be done in multiple ways, such as screenshots, web analysis, etc. \n\n- If I have written code, remind me to run the code and obtain the results. \n\n- Flexibly use code to solve problems, especially for Excel-related tasks. \n\n\n\nNow, here is the overall task: {self.task_prompt}. Never forget our task!\n\nNow you must start to instruct me to solve the task step-by-step. Do not add anything else other than your instruction!\nKeep giving me instructions until you think the task is completed.\nWhen the task is completed, you must only reply with a single word .\nNever say unless my responses have solved your task.\n \"\"\"\n\n assistant_system_prompt = f\"\"\"\n===== RULES OF ASSISTANT =====\nNever forget you are a assistant and I am a user. Never flip roles! Never instruct me! You have to utilize your available tools to solve the task I assigned.\nWe share a common interest in collaborating to successfully complete a complex task.\nYou must help me to complete the task.\n\nHere is our overall task: {self.task_prompt}. Never forget our task!\n\nI must instruct you based on your expertise and my needs to complete the task. An instruction is typically a sub-task or question.\n\nYou must leverage your available tools, try your best to solve the problem, and explain your solutions.\nUnless I say the task is completed, you should always start with:\nSolution: [YOUR_SOLUTION]\n[YOUR_SOLUTION] should be specific, including detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.\n\nPlease note that our overall task may be very complicated. Here are some tips that may help you solve the task:\n\n- If one method fails, try another. The answer exists! \n- When it comes to viewing information in an Excel file, you can always start by writing Python code to read the Excel file and check sheet names, column names, and similar details. \n- When providing Python code, always remember to import the necessary libraries at the beginning, such as the commonly used libraries for Excel analysis below: \n```\nimport pandas as pd\n```\n- Always verify whether your final answer is correct! \n- Always write complete code from scratch. After writing the code, be sure to run it and obtain the results! \n If you encounter errors, try debugging the code. \n Note that the code execution environment does not support interactive input. \n- If the tool fails to run or the code does not execute correctly, \n never assume that it has returned the correct result and continue reasoning based on it! \n The correct approach is to analyze the cause of the error and try to fix it! \n\n\n \"\"\"\n\n user_sys_msg = BaseMessage.make_user_message(\n role_name=self.user_role_name, content=user_system_prompt\n )\n\n assistant_sys_msg = BaseMessage.make_assistant_message(\n role_name=self.assistant_role_name, content=assistant_system_prompt\n )\n\n return user_sys_msg, assistant_sys_msg\n\ndef run_society(\n society: ExcelRolePalying,\n round_limit: int = 15,\n) -> Tuple[str, List[dict], dict]:\n overall_completion_token_count = 0\n overall_prompt_token_count = 0\n\n chat_history = []\n init_prompt = \"\"\"\n Now please give me instructions to solve over overall task step by step. If the task requires some specific knowledge, please instruct me to use tools to complete the task.\n \"\"\"\n input_msg = society.init_chat(init_prompt)\n for _round in range(round_limit):\n assistant_response, user_response = society.step(input_msg)\n # Check if usage info is available before accessing it\n if assistant_response.info.get(\"usage\") and user_response.info.get(\"usage\"):\n overall_completion_token_count += assistant_response.info[\"usage\"].get(\n \"completion_tokens\", 0\n ) + user_response.info[\"usage\"].get(\"completion_tokens\", 0)\n overall_prompt_token_count += assistant_response.info[\"usage\"].get(\n \"prompt_tokens\", 0\n ) + user_response.info[\"usage\"].get(\"prompt_tokens\", 0)\n\n # convert tool call to dict\n tool_call_records: List[dict] = []\n if assistant_response.info.get(\"tool_calls\"):\n for tool_call in assistant_response.info[\"tool_calls\"]:\n tool_call_records.append(tool_call.as_dict())\n\n _data = {\n \"user\": user_response.msg.content\n if hasattr(user_response, \"msg\") and user_response.msg\n else \"\",\n \"assistant\": assistant_response.msg.content\n if hasattr(assistant_response, \"msg\") and assistant_response.msg\n else \"\",\n \"tool_calls\": tool_call_records,\n }\n\n chat_history.append(_data)\n logger.info(\n f\"Round #{_round} user_response:\\n {user_response.msgs[0].content if user_response.msgs and len(user_response.msgs) > 0 else ''}\"\n )\n logger.info(\n f\"Round #{_round} assistant_response:\\n {assistant_response.msgs[0].content if assistant_response.msgs and len(assistant_response.msgs) > 0 else ''}\"\n )\n\n if (\n assistant_response.terminated\n or user_response.terminated\n or \"TASK_DONE\" in user_response.msg.content\n ):\n break\n\n input_msg = assistant_response.msg\n\n answer = chat_history[-1][\"assistant\"]\n token_info = {\n \"completion_token_count\": overall_completion_token_count,\n \"prompt_token_count\": overall_prompt_token_count,\n }\n\n return answer, chat_history, token_info\n\ndef construct_society(question: str) -> ExcelRolePalying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n OwlRolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components using Azure OpenAI\n base_model_config = {\n \"model_platform\": ModelPlatformType.AZURE,\n \"model_type\": os.getenv(\"AZURE_OPENAI_MODEL_TYPE\"),\n \"model_config_dict\": ChatGPTConfig(temperature=0.01, max_tokens=4096).as_dict(),\n }\n\n\n models = {\n \"user\": ModelFactory.create(**base_model_config),\n \"assistant\": ModelFactory.create(**base_model_config),\n }\n\n # Configure toolkits\n tools = [\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ExcelToolkit().get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = ExcelRolePalying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n output_language=\"English\"\n )\n\n return society\n\n\ndef main():\n # Example question\n\n default_task = \"\"\"Please help analyze the file `./data/admission_en.xlsx` by:\n - Calculating the number of admitted students, as well as the highest and lowest scores for each college\n - Plotting this information in a single chart: use a bar chart for the number of admitted students, and line charts for the highest and lowest scores\n - Saving the generated chart as `vis_en.png` in the current directory\"\"\"\n\n set_log_file('log.txt')\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/learning-assistant/run_gpt4o.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport os\nimport logging\nimport json\n\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.types import ModelPlatformType\n\nfrom camel.toolkits import (\n SearchToolkit,\n BrowserToolkit,\n)\nfrom camel.societies import RolePlaying\nfrom camel.logger import set_log_level, get_logger\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\nlogger = get_logger(__name__)\nfile_handler = logging.FileHandler(\"learning_journey.log\")\nfile_handler.setLevel(logging.DEBUG)\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nfile_handler.setFormatter(formatter)\nlogger.addHandler(file_handler)\n\nroot_logger = logging.getLogger()\nroot_logger.addHandler(file_handler)\n\n\ndef construct_learning_society(task: str) -> RolePlaying:\n \"\"\"Construct a society of agents for the learning journey companion.\n\n Args:\n task (str): The learning task description including what the user wants to learn and what they already know.\n\n Returns:\n RolePlaying: A configured society of agents for the learning companion.\n \"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.4},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.4},\n ),\n \"content_researcher\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.2},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.3},\n ),\n }\n\n browser_toolkit = BrowserToolkit(\n headless=False,\n web_agent_model=models[\"content_researcher\"],\n planning_agent_model=models[\"planning\"],\n )\n\n tools = [\n *browser_toolkit.get_tools(),\n SearchToolkit().search_duckduckgo,\n ]\n\n user_agent_kwargs = {\n \"model\": models[\"user\"],\n }\n\n assistant_agent_kwargs = {\n \"model\": models[\"assistant\"],\n \"tools\": tools,\n }\n\n task_kwargs = {\n \"task_prompt\": task,\n \"with_task_specify\": False,\n }\n\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"learner\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"learning_companion\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef analyze_chat_history(chat_history):\n \"\"\"Analyze chat history and extract tool call information.\"\"\"\n print(\"\\n============ Tool Call Analysis ============\")\n logger.info(\"========== Starting tool call analysis ==========\")\n\n tool_calls = []\n for i, message in enumerate(chat_history):\n if message.get(\"role\") == \"assistant\" and \"tool_calls\" in message:\n for tool_call in message.get(\"tool_calls\", []):\n if tool_call.get(\"type\") == \"function\":\n function = tool_call.get(\"function\", {})\n tool_info = {\n \"call_id\": tool_call.get(\"id\"),\n \"name\": function.get(\"name\"),\n \"arguments\": function.get(\"arguments\"),\n \"message_index\": i,\n }\n tool_calls.append(tool_info)\n print(\n f\"Tool Call: {function.get('name')} Args: {function.get('arguments')}\"\n )\n logger.info(\n f\"Tool Call: {function.get('name')} Args: {function.get('arguments')}\"\n )\n\n elif message.get(\"role\") == \"tool\" and \"tool_call_id\" in message:\n for tool_call in tool_calls:\n if tool_call.get(\"call_id\") == message.get(\"tool_call_id\"):\n result = message.get(\"content\", \"\")\n result_summary = (\n result[:100] + \"...\" if len(result) > 100 else result\n )\n print(\n f\"Tool Result: {tool_call.get('name')} Return: {result_summary}\"\n )\n logger.info(\n f\"Tool Result: {tool_call.get('name')} Return: {result_summary}\"\n )\n\n print(f\"Total tool calls found: {len(tool_calls)}\")\n logger.info(f\"Total tool calls found: {len(tool_calls)}\")\n logger.info(\"========== Finished tool call analysis ==========\")\n\n with open(\"learning_journey_history.json\", \"w\", encoding=\"utf-8\") as f:\n json.dump(chat_history, f, ensure_ascii=False, indent=2)\n\n print(\"Records saved to learning_journey_history.json\")\n print(\"============ Analysis Complete ============\\n\")\n\n\ndef run_learning_companion(task: str = None):\n \"\"\"Run the learning companion with the given task.\n\n Args:\n task (str, optional): The learning task description. Defaults to an example task.\n \"\"\"\n task = \"\"\"\n I want to learn about the transformers architecture in an llm. \n I've also taken a basic statistics course. \n I have about 10 hours per week to dedicate to learning. Devise a roadmap for me .\n \"\"\"\n\n society = construct_learning_society(task)\n\n from owl.utils import run_society\n\n answer, chat_history, token_count = run_society(society, round_limit=5)\n\n # Record tool usage history\n analyze_chat_history(chat_history)\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n run_learning_companion()\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/market_data_agent.py", "\"\"\"\n市场数据分析代理实现\n\"\"\"\nimport os\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport pandas as pd\nimport akshare as ak\nfrom datetime import datetime, timedelta\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import StockData\n\nfrom camel.messages import BaseMessage, OpenAIUserMessage, OpenAIAssistantMessage\n\n\nclass MarketDataAgent(BaseAgent):\n \"\"\"市场数据分析代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化市场数据分析代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"market_data_analyst\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"MarketDataAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理市场数据获取和预处理\n \n Args:\n data: 包含以下键的字典:\n - ticker: 股票代码\n - start_date: 开始日期\n - end_date: 结束日期\n - num_of_news: 新闻数量\n \n Returns:\n Dict[str, Any]: 处理后的数据,包含以下内容:\n - stock_data: 股票数据对象\n - messages: 处理过程中的消息\n \"\"\"\n # 提取参数\n ticker = data.get(\"ticker\")\n start_date = data.get(\"start_date\")\n end_date = data.get(\"end_date\")\n num_of_news = data.get(\"num_of_news\", 5)\n \n if not ticker:\n raise ValueError(\"缺少股票代码\")\n \n self.logger.info(f\"正在获取 {ticker} 的市场数据\")\n \n try:\n # 获取历史价格数据\n historical_data = self._get_historical_data(ticker, start_date, end_date)\n \n # 计算技术指标\n technical_indicators = self._calculate_technical_indicators(historical_data)\n \n # 获取财务数据\n fundamental_data = self._get_financial_data(ticker)\n \n # 获取新闻数据\n news_data = self._get_news_data(ticker, num_of_news)\n \n # 创建股票数据对象\n stock_data = StockData(\n ticker=ticker,\n historical_data=historical_data,\n technical_indicators=technical_indicators,\n fundamental_data=fundamental_data,\n news_data=news_data\n )\n \n # 使用代理处理数据分析请求\n prompt = f\"\"\"请分析以下关于股票 {ticker} 的市场数据,识别重要趋势和关键指标表现。\n 提供以下方面的见解:\n 1. 价格走势概要\n 2. 成交量分析\n 3. 主要技术指标分析(RSI、MACD、布林带)\n 4. 关键支撑和阻力位\n 5. 市场趋势和整体判断\"\"\"\n \n analysis_result = self._process_data_with_agent(prompt, {\n \"ticker\": ticker,\n \"historical_data\": historical_data,\n \"technical_indicators\": technical_indicators\n })\n \n # 返回结果\n return {\n \"stock_data\": stock_data,\n \"analysis\": analysis_result,\n \"messages\": [] # 暂时返回空消息列表\n }\n \n except Exception as e:\n self.logger.error(f\"获取市场数据时发生错误: {str(e)}\")\n raise e\n \n def _get_historical_data(self, ticker: str, start_date: str, end_date: str) -> Dict[str, Any]:\n \"\"\"获取历史价格数据\n \n Args:\n ticker: 股票代码\n start_date: 开始日期\n end_date: 结束日期\n \n Returns:\n Dict[str, Any]: 历史价格数据\n \"\"\"\n try:\n self.logger.info(f\"获取历史价格数据: {ticker} 从 {start_date} 到 {end_date}\")\n \n # 使用真实API获取数据\n from src.tools.api import get_price_data\n \n # 获取价格数据\n df = get_price_data(ticker, start_date, end_date)\n \n if df is None or df.empty:\n self.logger.warning(f\"无法获取{ticker}的价格数据,将使用空数据继续\")\n return {\n \"raw\": {\"dates\": [], \"prices\": [], \"volumes\": []},\n \"summary\": {\n \"ticker\": ticker,\n \"start_date\": start_date,\n \"end_date\": end_date,\n \"latest_price\": 0,\n \"price_change\": 0,\n \"high_price\": 0,\n \"low_price\": 0,\n \"average_volume\": 0\n }\n }\n \n # 将DataFrame转换为可处理的字典格式\n dates = df['date'].dt.strftime('%Y-%m-%d').tolist()\n prices = df['close'].tolist()\n volumes = df['volume'].tolist()\n \n # 计算汇总数据\n latest_price = prices[-1] if prices else 0\n previous_price = prices[-2] if len(prices) > 1 else latest_price\n price_change = ((latest_price - previous_price) / previous_price * 100) if previous_price else 0\n high_price = max(prices) if prices else 0\n low_price = min(prices) if prices else 0\n \n # 构建结果\n result = {\n \"raw\": {\n \"dates\": dates,\n \"prices\": prices,\n \"volumes\": volumes\n },\n \"summary\": {\n \"ticker\": ticker,\n \"start_date\": start_date,\n \"end_date\": end_date,\n \"latest_price\": latest_price,\n \"price_change\": round(price_change, 2),\n \"high_price\": high_price,\n \"low_price\": low_price,\n \"average_volume\": sum(volumes) / len(volumes) if volumes else 0\n }\n }\n \n return result\n \n except Exception as e:\n self.logger.error(f\"获取历史价格数据时发生错误: {str(e)}\")\n # 返回最小数据集以避免整个流程中断\n return {\n \"raw\": {\"dates\": [], \"prices\": [], \"volumes\": []},\n \"summary\": {\n \"ticker\": ticker,\n \"start_date\": start_date,\n \"end_date\": end_date,\n \"latest_price\": 0,\n \"price_change\": 0,\n \"high_price\": 0,\n \"low_price\": 0,\n \"average_volume\": 0,\n \"error\": str(e)\n }\n }\n \n def _calculate_technical_indicators(self, historical_data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"计算技术指标\n \n Args:\n historical_data: 历史价格数据\n \n Returns:\n Dict[str, Any]: 技术指标数据\n \"\"\"\n try:\n from src.tools.data_helper import calculate_technical_indicators\n \n raw_data = historical_data.get(\"raw\", {})\n dates = raw_data.get(\"dates\", [])\n prices = raw_data.get(\"prices\", [])\n volumes = raw_data.get(\"volumes\", [])\n \n if not prices:\n return {}\n \n # 将数据转换为DataFrame格式,以便使用data_helper中的函数\n df = pd.DataFrame({\n \"日期\": dates if dates else [],\n \"收盘\": prices if prices else [],\n \"成交量\": volumes if volumes else []\n })\n \n # 记录使用的列名\n self.logger.info(f\"DataFrame列名: {df.columns.tolist()}\")\n \n # 使用data_helper中的函数计算技术指标\n indicators = calculate_technical_indicators(df)\n \n if indicators and \"error\" in indicators:\n self.logger.error(f\"计算技术指标时出错: {indicators['error']}\")\n return {}\n \n # 提取最新的技术指标值用于摘要\n latest_indicators = {}\n \n # 提取SMA (简单移动平均线)\n for period in [5, 10, 20, 50, 200]:\n key = f\"ma_{period}\"\n if key in indicators and indicators[key]:\n latest_indicators[key] = indicators[key][-1]\n \n # 提取RSI (相对强弱指数)\n if \"rsi\" in indicators and indicators[\"rsi\"]:\n latest_indicators[\"rsi\"] = indicators[\"rsi\"][-1]\n \n # 提取MACD\n if all(k in indicators for k in [\"macd\", \"macd_signal\", \"macd_histogram\"]):\n latest_indicators[\"macd\"] = indicators[\"macd\"][-1] if indicators[\"macd\"] else None\n latest_indicators[\"macd_signal\"] = indicators[\"macd_signal\"][-1] if indicators[\"macd_signal\"] else None\n latest_indicators[\"macd_histogram\"] = indicators[\"macd_histogram\"][-1] if indicators[\"macd_histogram\"] else None\n \n # 提取布林带\n if all(k in indicators for k in [\"bollinger_ma\", \"bollinger_upper\", \"bollinger_lower\"]):\n latest_indicators[\"bollinger_middle\"] = indicators[\"bollinger_ma\"][-1] if indicators[\"bollinger_ma\"] else None\n latest_indicators[\"bollinger_upper\"] = indicators[\"bollinger_upper\"][-1] if indicators[\"bollinger_upper\"] else None\n latest_indicators[\"bollinger_lower\"] = indicators[\"bollinger_lower\"][-1] if indicators[\"bollinger_lower\"] else None\n \n # 分析价格位置\n if \"ma_20\" in latest_indicators and \"ma_50\" in latest_indicators and prices:\n latest_price = prices[-1]\n latest_indicators[\"price_vs_ma20\"] = \"above\" if latest_price > latest_indicators[\"ma_20\"] else \"below\"\n latest_indicators[\"price_vs_ma50\"] = \"above\" if latest_price > latest_indicators[\"ma_50\"] else \"below\"\n \n return {\n \"full\": indicators,\n \"latest\": latest_indicators\n }\n \n except Exception as e:\n self.logger.error(f\"计算技术指标时发生错误: {str(e)}\")\n return {}\n \n def _prepare_summary_prompt(self, ticker: str, stock_data: StockData) -> str:\n \"\"\"准备数据摘要提示\n \n Args:\n ticker: 股票代码\n stock_data: 股票数据对象\n \n Returns:\n str: 数据摘要提示\n \"\"\"\n # 提取相关数据\n historical_summary = stock_data.historical_data.get(\"summary\", {})\n technical_indicators = stock_data.technical_indicators.get(\"latest\", {})\n \n # 构建提示\n prompt = f\"\"\"\n请对以下股票数据进行分析和预处理,确认数据质量并提供简要说明。\n\n股票: {ticker}\n最新价格: {historical_summary.get('latest_price')}\n涨跌幅: {historical_summary.get('price_change')}%\n时间范围: {historical_summary.get('start_date')} 至 {historical_summary.get('end_date')}\n\n主要技术指标:\n- MA(5): {technical_indicators.get('ma_5')}\n- MA(20): {technical_indicators.get('ma_20')}\n- RSI: {technical_indicators.get('rsi')}\n- MACD: {technical_indicators.get('macd')}\n\n请分析这些数据,确认数据是否合理、完整,并提供简要的市场数据状况描述。\n如果发现任何数据问题,请指出并提供可能的解决方法。\n\"\"\"\n return prompt\n \n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"使用代理处理数据并获取结果\n \n Args:\n prompt: 提示信息\n data: 要处理的数据\n \n Returns:\n Dict[str, Any]: 处理结果\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请以JSON格式返回结果。\n\"\"\"\n try:\n # 创建消息 - 使用新的消息格式\n msg = self.generate_human_message(content=full_prompt)\n \n # 获取代理响应\n response = self.agent.step(msg)\n \n # 记录响应\n self.log_message(response.msgs[0])\n \n # 解析响应\n return self.parse_json_response(response.msgs[0].content)\n \n except Exception as e:\n self.logger.error(f\"处理数据时发生错误: {str(e)}\")\n return {}\n\n def _get_financial_data(self, ticker: str) -> Dict[str, Any]:\n \"\"\"获取股票的财务数据\n \n Args:\n ticker: 股票代码\n \n Returns:\n Dict[str, Any]: 财务数据\n \"\"\"\n try:\n from src.tools.data_helper import get_fundamental_data\n \n self.logger.info(f\"获取财务数据: {ticker}\")\n \n # 使用data_helper中的函数获取财务数据\n financial_data = get_fundamental_data(ticker)\n \n # 如果获取失败,返回空结构\n if not financial_data or \"error\" in financial_data:\n self.logger.error(f\"获取财务数据失败: {financial_data.get('error', '未知错误')}\")\n return {\n \"income_statement\": {},\n \"balance_sheet\": {},\n \"financial_ratios\": {},\n \"quarterly_results\": [],\n \"dividend_info\": {},\n }\n \n # 提取并组织数据\n financial_indicators = financial_data.get(\"financial_indicators\", {})\n income_statement = financial_data.get(\"income_statement\", {})\n stock_info = financial_data.get(\"stock_info\", {})\n summary = financial_data.get(\"summary\", {})\n \n # 获取历史财务数据,默认获取最近4个季度\n historical_data = self._get_historical_financial_data(ticker, 4)\n \n # 构建返回结构\n result = {\n \"income_statement\": {\n \"revenue\": income_statement.get(\"营业收入\", 0),\n \"operating_income\": income_statement.get(\"营业利润\", 0),\n \"net_income\": income_statement.get(\"净利润\", 0),\n \"total_profit\": income_statement.get(\"利润总额\", 0),\n \"eps\": income_statement.get(\"基本每股收益\", 0),\n \"income_tax\": income_statement.get(\"减:所得税\", 0),\n \"interest_income\": income_statement.get(\"利息收入\", 0),\n \"interest_expense\": income_statement.get(\"利息支出\", 0),\n \"investment_income\": income_statement.get(\"投资收益\", 0),\n \"operating_expense\": income_statement.get(\"营业支出\", 0),\n \"rd_expense\": income_statement.get(\"研发费用\", 0),\n \"business_tax\": income_statement.get(\"营业税金及附加\", 0),\n \"management_expense\": income_statement.get(\"业务及管理费用\", 0),\n \"asset_impairment_loss\": income_statement.get(\"资产减值损失\", 0),\n \"credit_impairment_loss\": income_statement.get(\"信用减值损失\", 0),\n \"non_operating_income\": income_statement.get(\"加:营业外收入\", 0),\n \"non_operating_expense\": income_statement.get(\"减:营业外支出\", 0),\n \"reporting_date\": income_statement.get(\"报告日\", \"\"),\n \"year_over_year_growth\": financial_indicators.get(\"净利润同比增长率\", 0),\n \"diluted_eps\": income_statement.get(\"稀释每股收益\", 0),\n },\n \"balance_sheet\": {\n \"total_assets\": financial_indicators.get(\"总资产\", 0),\n \"total_liabilities\": financial_indicators.get(\"总负债\", 0),\n \"total_equity\": financial_indicators.get(\"所有者权益\", 0),\n \"cash_and_equivalents\": financial_indicators.get(\"货币资金\", 0),\n \"total_debt\": financial_indicators.get(\"带息债务\", 0),\n \"retained_earnings\": income_statement.get(\"未分配利润\", 0),\n },\n \"financial_ratios\": {\n \"pe_ratio\": stock_info.get(\"市盈率-动态\", 0),\n \"pb_ratio\": stock_info.get(\"市净率\", 0),\n \"roe\": financial_indicators.get(\"净资产收益率\", 0),\n \"debt_to_equity\": financial_indicators.get(\"资产负债率\", 0),\n \"profit_margin\": financial_indicators.get(\"净利率\", 0),\n \"current_ratio\": financial_indicators.get(\"流动比率\", 0),\n \"turnover_rate\": stock_info.get(\"换手率\", 0),\n \"amplitude\": stock_info.get(\"振幅\", 0),\n \"year_to_date_change\": stock_info.get(\"年初至今涨跌幅\", 0),\n \"sixty_day_change\": stock_info.get(\"60日涨跌幅\", 0),\n },\n \"market_info\": {\n \"market_cap\": stock_info.get(\"总市值\", 0),\n \"circulating_market_value\": stock_info.get(\"流通市值\", 0),\n \"industry\": summary.get(\"industry\", \"\"),\n \"name\": stock_info.get(\"名称\", \"\"),\n \"latest_price\": stock_info.get(\"最新价\", 0),\n \"change_percent\": stock_info.get(\"涨跌幅\", 0),\n \"change_amount\": stock_info.get(\"涨跌额\", 0),\n \"volume\": stock_info.get(\"成交量\", 0),\n \"turnover\": stock_info.get(\"成交额\", 0),\n \"highest\": stock_info.get(\"最高\", 0),\n \"lowest\": stock_info.get(\"最低\", 0),\n \"open\": stock_info.get(\"今开\", 0),\n \"prev_close\": stock_info.get(\"昨收\", 0),\n },\n \"historical_data\": historical_data,\n \"trends\": self._calculate_financial_trends(historical_data)\n }\n \n return result\n \n except Exception as e:\n self.logger.error(f\"获取财务数据时发生错误: {str(e)}\")\n # 返回基本数据结构以避免流程中断\n return {\n \"income_statement\": {},\n \"balance_sheet\": {},\n \"financial_ratios\": {},\n \"market_info\": {},\n \"historical_data\": [],\n \"trends\": {},\n \"error\": str(e)\n }\n \n def _get_historical_financial_data(self, ticker: str, num_quarters: int = 4) -> List[Dict[str, Any]]:\n \"\"\"获取历史财务数据\n \n Args:\n ticker: 股票代码\n num_quarters: 要获取的季度数量\n \n Returns:\n List[Dict[str, Any]]: 历史财务数据列表\n \"\"\"\n try:\n import akshare as ak\n \n self.logger.info(f\"获取{ticker}的历史财务数据,共{num_quarters}个季度\")\n \n # 确定股票前缀\n stock_prefix = 'sz' if ticker.startswith('0') or ticker.startswith('3') else 'sh'\n formatted_ticker = f\"{stock_prefix}{ticker}\"\n \n # 获取利润表数据\n income_statements = ak.stock_financial_report_sina(stock=formatted_ticker, symbol=\"利润表\")\n \n # 获取资产负债表数据\n try:\n balance_sheets = ak.stock_financial_report_sina(stock=formatted_ticker, symbol=\"资产负债表\")\n except Exception as e:\n self.logger.warning(f\"获取{ticker}的资产负债表数据失败: {str(e)}\")\n balance_sheets = pd.DataFrame()\n \n # 获取现金流量表数据\n try:\n cash_flows = ak.stock_financial_report_sina(stock=formatted_ticker, symbol=\"现金流量表\")\n except Exception as e:\n self.logger.warning(f\"获取{ticker}的现金流量表数据失败: {str(e)}\")\n cash_flows = pd.DataFrame()\n \n # 获取财务指标数据\n try:\n financial_indicators = ak.stock_financial_analysis_indicator(symbol=ticker)\n except Exception as e:\n self.logger.warning(f\"获取{ticker}的财务指标数据失败: {str(e)}\")\n financial_indicators = pd.DataFrame()\n \n # 限制数量\n if not income_statements.empty:\n income_statements = income_statements.head(num_quarters)\n if not balance_sheets.empty:\n balance_sheets = balance_sheets.head(num_quarters)\n if not cash_flows.empty:\n cash_flows = cash_flows.head(num_quarters)\n if not financial_indicators.empty:\n financial_indicators = financial_indicators.head(num_quarters)\n \n # 组织历史数据\n historical_data = []\n \n # 使用利润表的报告日期作为基准\n if not income_statements.empty:\n for i, row in income_statements.iterrows():\n if i >= num_quarters:\n break\n \n report_date = row.get(\"报告日\", \"\")\n \n # 查找相应日期的资产负债表和现金流量表数据\n balance_sheet_row = balance_sheets[balance_sheets[\"报告日\"] == report_date].iloc[0] if not balance_sheets.empty and report_date in balance_sheets[\"报告日\"].values else pd.Series()\n cash_flow_row = cash_flows[cash_flows[\"报告日\"] == report_date].iloc[0] if not cash_flows.empty and report_date in cash_flows[\"报告日\"].values else pd.Series()\n \n # 提取财务指标数据\n financial_indicator_row = pd.Series()\n if not financial_indicators.empty:\n # 处理财务指标数据,通常日期格式不同,需要转换\n for _, indicator_row in financial_indicators.iterrows():\n indicator_date = indicator_row.get(\"日期\")\n if indicator_date and str(indicator_date).replace(\"-\", \"\").startswith(report_date[:6]):\n financial_indicator_row = indicator_row\n break\n \n # 组织单季度数据\n quarter_data = {\n \"report_date\": report_date,\n \"formatted_date\": f\"{report_date[:4]}年{report_date[4:6]}月{report_date[6:]}日\",\n \"income_statement\": {\n \"revenue\": row.get(\"营业收入\", 0),\n \"operating_profit\": row.get(\"营业利润\", 0),\n \"net_income\": row.get(\"净利润\", 0),\n \"total_profit\": row.get(\"利润总额\", 0),\n \"eps\": row.get(\"基本每股收益\", 0),\n },\n \"balance_sheet\": {\n \"total_assets\": balance_sheet_row.get(\"资产总计\", 0),\n \"total_liabilities\": balance_sheet_row.get(\"负债合计\", 0),\n \"equity\": balance_sheet_row.get(\"所有者权益(或股东权益)合计\", 0),\n \"cash\": balance_sheet_row.get(\"货币资金\", 0),\n },\n \"cash_flow\": {\n \"operating_cash_flow\": cash_flow_row.get(\"经营活动产生的现金流量净额\", 0),\n \"investing_cash_flow\": cash_flow_row.get(\"投资活动产生的现金流量净额\", 0),\n \"financing_cash_flow\": cash_flow_row.get(\"筹资活动产生的现金流量净额\", 0),\n },\n \"financial_indicators\": {\n \"roe\": financial_indicator_row.get(\"净资产收益率(%)\", 0),\n \"gross_margin\": financial_indicator_row.get(\"销售毛利率(%)\", 0),\n \"debt_ratio\": financial_indicator_row.get(\"资产负债率(%)\", 0),\n }\n }\n \n historical_data.append(quarter_data)\n \n self.logger.info(f\"成功获取{ticker}的历史财务数据,共{len(historical_data)}个季度\")\n return historical_data\n \n except Exception as e:\n self.logger.error(f\"获取历史财务数据时发生错误: {str(e)}\")\n return []\n \n def _calculate_financial_trends(self, historical_data: List[Dict[str, Any]]) -> Dict[str, Any]:\n \"\"\"计算财务趋势\n \n Args:\n historical_data: 历史财务数据列表\n \n Returns:\n Dict[str, Any]: 财务趋势数据\n \"\"\"\n if not historical_data or len(historical_data) < 2:\n return {}\n \n # 提取关键指标的时间序列\n revenue_trend = []\n net_income_trend = []\n eps_trend = []\n roe_trend = []\n \n for quarter in historical_data:\n revenue_trend.append(float(quarter[\"income_statement\"][\"revenue\"]))\n net_income_trend.append(float(quarter[\"income_statement\"][\"net_income\"]))\n eps_trend.append(float(quarter[\"income_statement\"][\"eps\"]))\n roe_trend.append(float(quarter[\"financial_indicators\"][\"roe\"]))\n \n # 计算同比增长率\n try:\n revenue_growth = (revenue_trend[0] - revenue_trend[-1]) / revenue_trend[-1] * 100 if revenue_trend[-1] else 0\n net_income_growth = (net_income_trend[0] - net_income_trend[-1]) / net_income_trend[-1] * 100 if net_income_trend[-1] else 0\n except (IndexError, ZeroDivisionError):\n revenue_growth = 0\n net_income_growth = 0\n \n # 计算趋势\n trends = {\n \"revenue\": {\n \"values\": revenue_trend,\n \"growth\": revenue_growth,\n \"trend\": \"上升\" if revenue_growth > 0 else \"下降\" if revenue_growth < 0 else \"持平\"\n },\n \"net_income\": {\n \"values\": net_income_trend,\n \"growth\": net_income_growth,\n \"trend\": \"上升\" if net_income_growth > 0 else \"下降\" if net_income_growth < 0 else \"持平\"\n },\n \"eps\": {\n \"values\": eps_trend,\n \"trend\": \"上升\" if eps_trend[0] > eps_trend[-1] else \"下降\" if eps_trend[0] < eps_trend[-1] else \"持平\"\n },\n \"roe\": {\n \"values\": roe_trend,\n \"trend\": \"上升\" if roe_trend[0] > roe_trend[-1] else \"下降\" if roe_trend[0] < roe_trend[-1] else \"持平\"\n }\n }\n \n return trends\n \n def _get_news_data(self, ticker: str, num_of_news: int = 5) -> Dict[str, Any]:\n \"\"\"获取股票相关的新闻数据\n \n Args:\n ticker: 股票代码\n num_of_news: 获取的新闻数量\n \n Returns:\n Dict[str, Any]: 新闻数据\n \"\"\"\n try:\n from src.tools.data_helper import get_stock_news\n \n self.logger.info(f\"获取新闻数据: {ticker}, 数量: {num_of_news}\")\n \n # 使用data_helper中的函数获取新闻数据\n news_list = get_stock_news(ticker, num_of_news)\n \n # 如果没有获取到新闻,返回空结构\n if not news_list:\n return {\n \"news\": [],\n \"overall_sentiment\": 0,\n \"sentiment_breakdown\": {\"positive\": 0, \"neutral\": 0, \"negative\": 0}\n }\n \n # 简单情感分析 (实际应用中应使用NLP模型进行分析)\n # 这里使用模型分析标题进行简单情感判断\n sentiment_scores = []\n sentiments = {\"positive\": 0, \"neutral\": 0, \"negative\": 0}\n \n for news in news_list:\n # 让LLM对新闻标题进行情感分析\n sentiment_prompt = f\"\"\"\n 请分析以下新闻标题的情感倾向,仅回复\"positive\"、\"neutral\"或\"negative\":\n {news.get('title', '')}\n \"\"\"\n \n try:\n # 使用LLM分析情感\n msg = self.generate_human_message(content=sentiment_prompt)\n response = self.agent.step(msg)\n sentiment = response.msgs[0].content.strip().lower()\n \n # 规范化情感结果\n if \"positive\" in sentiment:\n news[\"sentiment\"] = \"positive\"\n news[\"sentiment_score\"] = 0.8\n sentiments[\"positive\"] += 1\n sentiment_scores.append(0.8)\n elif \"negative\" in sentiment:\n news[\"sentiment\"] = \"negative\"\n news[\"sentiment_score\"] = -0.7\n sentiments[\"negative\"] += 1\n sentiment_scores.append(-0.7)\n else:\n news[\"sentiment\"] = \"neutral\"\n news[\"sentiment_score\"] = 0.1\n sentiments[\"neutral\"] += 1\n sentiment_scores.append(0.1)\n \n except Exception:\n # 如果LLM分析失败,默认为中性\n news[\"sentiment\"] = \"neutral\"\n news[\"sentiment_score\"] = 0.0\n sentiments[\"neutral\"] += 1\n sentiment_scores.append(0.0)\n \n # 计算总体情感得分\n overall_sentiment = sum(sentiment_scores) / len(sentiment_scores) if sentiment_scores else 0\n \n return {\n \"news\": news_list,\n \"overall_sentiment\": overall_sentiment,\n \"sentiment_breakdown\": sentiments\n }\n \n except Exception as e:\n self.logger.error(f\"获取新闻数据时发生错误: {str(e)}\")\n # 返回基本数据结构以避免流程中断\n return {\n \"news\": [],\n \"overall_sentiment\": 0,\n \"sentiment_breakdown\": {\"positive\": 0, \"neutral\": 0, \"negative\": 0},\n \"error\": str(e)\n } "], ["/owl/community_usecase/cooking-assistant/run_gpt4o.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport os\nimport logging\nimport json\n\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.types import ModelPlatformType\n\nfrom camel.toolkits import (\n SearchToolkit,\n BrowserToolkit,\n)\nfrom camel.societies import RolePlaying\nfrom camel.logger import set_log_level, get_logger\n\n\nfrom owl.utils import run_society\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\nlogger = get_logger(__name__)\nfile_handler = logging.FileHandler(\"cooking_companion.log\")\nfile_handler.setLevel(logging.DEBUG)\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nfile_handler.setFormatter(formatter)\nlogger.addHandler(file_handler)\n\nroot_logger = logging.getLogger()\nroot_logger.addHandler(file_handler)\n\n\ndef construct_cooking_society(task: str) -> RolePlaying:\n \"\"\"Construct a society of agents for the cooking companion.\n\n Args:\n task (str): The cooking-related task to be addressed.\n\n Returns:\n RolePlaying: A configured society of agents for the cooking companion.\n \"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.4},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.4},\n ),\n \"recipe_analyst\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.2},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.3},\n ),\n }\n\n browser_toolkit = BrowserToolkit(\n headless=False,\n web_agent_model=models[\"recipe_analyst\"],\n planning_agent_model=models[\"planning\"],\n )\n\n tools = [\n *browser_toolkit.get_tools(),\n SearchToolkit().search_duckduckgo,\n ]\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n task_kwargs = {\n \"task_prompt\": task,\n \"with_task_specify\": False,\n }\n\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"cooking_assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef analyze_chat_history(chat_history):\n \"\"\"Analyze chat history and extract tool call information.\"\"\"\n print(\"\\n============ Tool Call Analysis ============\")\n logger.info(\"========== Starting tool call analysis ==========\")\n\n tool_calls = []\n for i, message in enumerate(chat_history):\n if message.get(\"role\") == \"assistant\" and \"tool_calls\" in message:\n for tool_call in message.get(\"tool_calls\", []):\n if tool_call.get(\"type\") == \"function\":\n function = tool_call.get(\"function\", {})\n tool_info = {\n \"call_id\": tool_call.get(\"id\"),\n \"name\": function.get(\"name\"),\n \"arguments\": function.get(\"arguments\"),\n \"message_index\": i,\n }\n tool_calls.append(tool_info)\n print(\n f\"Tool Call: {function.get('name')} Args: {function.get('arguments')}\"\n )\n logger.info(\n f\"Tool Call: {function.get('name')} Args: {function.get('arguments')}\"\n )\n\n elif message.get(\"role\") == \"tool\" and \"tool_call_id\" in message:\n for tool_call in tool_calls:\n if tool_call.get(\"call_id\") == message.get(\"tool_call_id\"):\n result = message.get(\"content\", \"\")\n result_summary = (\n result[:100] + \"...\" if len(result) > 100 else result\n )\n print(\n f\"Tool Result: {tool_call.get('name')} Return: {result_summary}\"\n )\n logger.info(\n f\"Tool Result: {tool_call.get('name')} Return: {result_summary}\"\n )\n\n print(f\"Total tool calls found: {len(tool_calls)}\")\n logger.info(f\"Total tool calls found: {len(tool_calls)}\")\n logger.info(\"========== Finished tool call analysis ==========\")\n\n with open(\"cooking_chat_history.json\", \"w\", encoding=\"utf-8\") as f:\n json.dump(chat_history, f, ensure_ascii=False, indent=2)\n\n print(\"Records saved to cooking_chat_history.json\")\n print(\"============ Analysis Complete ============\\n\")\n\n\ndef run_cooking_companion():\n task = \"I have chicken breast, broccoli, garlic, and pasta. I'm looking for a quick dinner recipe that's healthy. I'm also trying to reduce my sodium intake. Search the internet for a recipe, modify it for low sodium, and create a shopping list for any additional ingredients I need?\"\n society = construct_cooking_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Record tool usage history\n analyze_chat_history(chat_history)\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n run_cooking_companion()\n"], ["/owl/community_usecase/stock-analysis/tools/sec_tools.py", "from typing import List\nfrom typing import Optional\nfrom camel.toolkits.base import BaseToolkit\nfrom camel.toolkits.function_tool import FunctionTool\nfrom camel.utils import api_keys_required, dependencies_required\nimport requests\nimport html2text\nimport re\n\nclass SECToolkit(BaseToolkit):\n r\"\"\"A class representing a toolkit for SEC filings analysis.\n \n This toolkit provides functionality to:\n - Fetch and process 10-K (annual) reports\n - Fetch and process 10-Q (quarterly) reports\n - Clean and format filing content for analysis\n - Support semantic search capabilities on filing content\n \n The toolkit requires SEC API credentials and handles HTTP requests\n to SEC's EDGAR database to retrieve filing documents.\n \"\"\"\n\n @dependencies_required(\"sec_api\")\n @api_keys_required(\n [\n (None, \"SEC_API_API_KEY\"),\n ]\n )\n def fetch_10k_filing(self, stock_name: str) -> Optional[str]:\n r\"\"\"Fetches and processes the latest 10-K form content for a given stock symbol.\n\n This function retrieves the most recent 10-K filing from SEC's database using\n the provided stock ticker symbol. It downloads the filing content, converts\n it from HTML to text format, and performs text cleaning.\n\n Args:\n stock_name (str): The stock ticker symbol (e.g., 'AAPL' for Apple Inc.).\n\n Returns:\n Optional[str]: A cleaned text version of the 10-K filing content.\n Returns None in the following cases:\n - No filings found for the given stock symbol\n - HTTP errors during content retrieval\n - Other exceptions during processing\n \n The returned text is preprocessed to:\n - Remove HTML formatting\n - Remove special characters\n - Retain only alphanumeric characters, dollar signs, spaces and newlines\n \"\"\"\n \n from sec_api import QueryApi\n import os\n\n try:\n queryApi = QueryApi(api_key=os.environ['SEC_API_API_KEY'])\n query = {\n \"query\": {\n \"query_string\": {\n \"query\": f\"ticker:{stock_name} AND formType:\\\"10-K\\\"\"\n }\n },\n \"from\": \"0\",\n \"size\": \"1\",\n \"sort\": [{ \"filedAt\": { \"order\": \"desc\" }}]\n }\n response = queryApi.get_filings(query)\n if response and 'filings' in response:\n filings = response['filings']\n else:\n filings = []\n if len(filings) == 0:\n print(\"No filings found for this stock.\")\n return None\n\n url = filings[0]['linkToFilingDetails']\n \n headers = {\n \"User-Agent\": \"crewai.com bisan@crewai.com\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Host\": \"www.sec.gov\"\n }\n response = requests.get(url, headers=headers)\n response.raise_for_status()\n h = html2text.HTML2Text()\n h.ignore_links = False\n text = h.handle(response.content.decode(\"utf-8\"))\n\n text = re.sub(r\"[^a-zA-Z$0-9\\s\\n]\", \"\", text)\n return text\n except requests.exceptions.HTTPError as e:\n print(f\"HTTP error occurred: {e}\")\n return None\n except Exception as e:\n print(f\"Error fetching 10-K URL: {e}\")\n return None\n \n @dependencies_required(\"sec_api\")\n @api_keys_required(\n [\n (None, \"SEC_API_API_KEY\"),\n ]\n )\n def fetch_10q_filing(self, stock_name: str) -> Optional[str]:\n r\"\"\"Fetches and processes the latest 10-Q form content for a given stock symbol.\n\n This function retrieves the most recent 10-Q filing from SEC's database using\n the provided stock ticker symbol. It downloads the filing content, converts\n it from HTML to text format, and performs text cleaning.\n\n Args:\n stock_name (str): The stock ticker symbol (e.g., 'AAPL' for Apple Inc.).\n\n Returns:\n Optional[str]: A cleaned text version of the 10-Q filing content.\n Returns None in the following cases:\n - No filings found for the given stock symbol\n - HTTP errors during content retrieval\n - Other exceptions during processing\n \n The returned text is preprocessed to:\n - Remove HTML formatting\n - Remove special characters\n - Retain only alphanumeric characters, dollar signs, spaces and newlines\n \"\"\"\n\n from sec_api import QueryApi\n import os\n\n try:\n queryApi = QueryApi(api_key=os.environ['SEC_API_API_KEY'])\n query = {\n \"query\": {\n \"query_string\": {\n \"query\": f\"ticker:{stock_name} AND formType:\\\"10-Q\\\"\"\n }\n },\n \"from\": \"0\",\n \"size\": \"1\",\n \"sort\": [{ \"filedAt\": { \"order\": \"desc\" }}]\n }\n response = queryApi.get_filings(query)\n if response and 'filings' in response:\n filings = response['filings']\n else:\n filings = []\n if len(filings) == 0:\n print(\"No filings found for this stock.\")\n return None\n\n url = filings[0]['linkToFilingDetails']\n \n headers = {\n \"User-Agent\": \"crewai.com bisan@crewai.com\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Host\": \"www.sec.gov\"\n }\n response = requests.get(url, headers=headers)\n response.raise_for_status() # Raise an exception for HTTP errors\n h = html2text.HTML2Text()\n h.ignore_links = False\n text = h.handle(response.content.decode(\"utf-8\"))\n\n # Removing all non-English words, dollar signs, numbers, and newlines from text\n text = re.sub(r\"[^a-zA-Z$0-9\\s\\n]\", \"\", text)\n return text\n except requests.exceptions.HTTPError as e:\n print(f\"HTTP error occurred: {e}\")\n return None\n except Exception as e:\n print(f\"Error fetching 10-Q URL: {e}\")\n return None\n\n def get_tools(self) -> List[FunctionTool]:\n r\"\"\"Returns a list of FunctionTool objects representing the\n functions in the toolkit.\n\n Returns:\n List[FunctionTool]: A list of FunctionTool objects\n representing the functions in the toolkit.\n \"\"\"\n\n return [\n FunctionTool(self.fetch_10k_filing),\n FunctionTool(self.fetch_10q_filing)\n ]\n\nif __name__ == \"__main__\":\n toolkit = SECToolkit()\n data_10k = toolkit.fetch_10k_filing(\"GOOG\")\n data_10q = toolkit.fetch_10q_filing(\"GOOG\")\n # 检查 data_10k 是否为 None,如果不是则计算长度\n print(f\"fetch_10k_filing AAPL = {len(data_10k) if data_10k is not None else 0}\")\n print(f\"fetch_10q_filing AAPL = {len(data_10q) if data_10q is not None else 0}\")"], ["/owl/community_usecase/Mcp_use_case/Content_curator.py", "import asyncio\nimport sys\nfrom pathlib import Path\nfrom typing import List, Dict\n\n\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import FunctionTool, MCPToolkit\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\n\nfrom owl.utils.enhanced_role_playing import OwlRolePlaying, arun_society\n\nimport pathlib\n\nset_log_level(level=\"DEBUG\")\n\n# Load environment variables from .env file if available\nload_dotenv()\n\n\nasync def construct_society(\n question: str,\n tools: List[FunctionTool],\n) -> OwlRolePlaying:\n \"\"\"Build a multi-agent OwlRolePlaying instance with enhanced content curation capabilities.\"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\n \"temperature\": 0.7,\n # \"max_tokens\": 4000 # Add token limit to prevent overflow\n },\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\n \"temperature\": 0.7,\n #\"max_tokens\": 4000\n },\n ),\n }\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\n \"model\": models[\"assistant\"],\n \"tools\": tools,\n }\n\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n return OwlRolePlaying(\n **task_kwargs,\n user_role_name=\"content_curator\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"research_assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\nasync def main():\n config_path = Path(__file__).parent / \"mcp_servers_config.json\"\n mcp_toolkit = MCPToolkit(config_path=str(config_path))\n\n try:\n await mcp_toolkit.connect()\n\n default_task = (\n \"Content Curation Task:\\n\"\n \"1. Search for these tech websites:\\n\"\n \" - TechCrunch\\n\"\n \" - The Verge\\n\"\n \" - Wired\\n\"\n \"2. For each site:\\n\"\n \" - Use the firecrawl_scrape tool with proper extraction options\\n\"\n \" - Extract the homepage content\\n\"\n \" - Focus on headlines and recent articles\\n\"\n \"3. For each article found:\\n\"\n \" - Extract title and summary\\n\"\n \" - Note the publication date if available\\n\"\n \"4. Create a summary report including:\\n\"\n \" - Top stories from each source\\n\"\n \" - Common themes or trends\\n\"\n \"5. Save the report as 'Latest_tech_digest.md'\\n\"\n )\n\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Connect to all MCP toolkits\n tools = [*mcp_toolkit.get_tools()]\n society = await construct_society(task, tools)\n \n try:\n # Add error handling for the society execution\n result = await arun_society(society)\n \n # Handle the result properly\n if isinstance(result, tuple) and len(result) == 3:\n answer, chat_history, token_count = result\n else:\n answer = str(result)\n chat_history = []\n token_count = 0\n\n except Exception as e:\n print(f\"Error during society execution: {str(e)}\")\n raise\n\n finally:\n # Cleanup\n await asyncio.sleep(1)\n tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]\n for task in tasks:\n task.cancel()\n try:\n await task\n except asyncio.CancelledError:\n pass\n \n try:\n await mcp_toolkit.disconnect()\n except Exception as e:\n print(f\"Cleanup error (can be ignored): {e}\")\n\nif __name__ == \"__main__\":\n try:\n asyncio.run(main())\n except KeyboardInterrupt:\n print(\"\\nShutting down gracefully...\")\n finally:\n if sys.platform == 'win32':\n try:\n import asyncio.windows_events\n asyncio.windows_events._overlapped = None\n except (ImportError, AttributeError):\n pass"], ["/owl/community_usecase/Puppeteer MCP/demo.py", "\nimport asyncio\nfrom pathlib import Path\n\nimport streamlit as st\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import FunctionTool\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.toolkits import MCPToolkit, SearchToolkit\nimport sys\n\nfrom owl.utils.enhanced_role_playing import OwlRolePlaying, arun_society\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\n# Load environment variables and set logger level\nif sys.platform.startswith(\"win\"):\n asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())\nload_dotenv()\nset_log_level(level=\"DEBUG\")\n\nasync def construct_society(task: str, tools: list[FunctionTool]) -> OwlRolePlaying:\n \"\"\"\n Build a multi-agent OwlRolePlaying instance.\n \"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n task_kwargs = {\n \"task_prompt\": task,\n \"with_task_specify\": False,\n }\n\n society = OwlRolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n return society\n\nasync def run_task(task: str) -> str:\n \"\"\"\n Connect to MCP servers, run the provided task, and return the answer.\n \"\"\"\n # Construct the path to your MCP server config file.\n config_path = Path(__file__).parent / \"mcp_servers_config.json\"\n mcp_toolkit = MCPToolkit(config_path=str(config_path))\n answer = \"\"\n try:\n logging.debug(\"Connecting to MCP server...\")\n await mcp_toolkit.connect()\n logging.debug(\"Connected to MCP server.\")\n\n # Prepare all tools from the MCP toolkit and the web search toolkit\n tools = [*mcp_toolkit.get_tools(), SearchToolkit().search_duckduckgo]\n society = await construct_society(task, tools)\n answer, chat_history, token_count = await arun_society(society)\n except Exception as e:\n import traceback\n st.error(f\"An error occurred: {e}\")\n st.text(traceback.format_exc())\n finally:\n try:\n await mcp_toolkit.disconnect()\n except Exception as e:\n answer += f\"\\nError during disconnect: {e}\"\n return answer\n\ndef main():\n st.title(\"OWL X Puppeteer MCP Server\")\n\n # Get the task from the user\n task = st.text_input(\"Enter your task\",value=\"Please find the top articles from dev.to this week and go to each article and then summarize it. Please use MCP given to you\")\n\n if st.button(\"Run Task\"):\n if not task.strip():\n st.error(\"Please enter a valid task.\")\n else:\n with st.spinner(\"Processing the task...\"):\n try:\n # Create a new event loop for the current thread\n new_loop = asyncio.new_event_loop()\n asyncio.set_event_loop(new_loop)\n result = new_loop.run_until_complete(run_task(task))\n except Exception as e:\n st.error(f\"An error occurred: {e}\")\n result = \"\"\n finally:\n new_loop.close()\n st.success(\"Task completed!\")\n st.write(result)\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/Airbnb-MCP/Airbnb_MCP.py", "import asyncio\nimport sys\nfrom pathlib import Path\nfrom typing import List, Dict\n\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import FunctionTool, MCPToolkit\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\n\nfrom owl.utils.enhanced_role_playing import OwlRolePlaying, arun_society\n\nimport pathlib\n\nset_log_level(level=\"DEBUG\")\n\n# Load environment variables from .env file if available\nload_dotenv()\n\n\nasync def construct_society(\n question: str,\n tools: List[FunctionTool],\n) -> OwlRolePlaying:\n \"\"\"Build a multi-agent OwlRolePlaying instance with enhanced content curation capabilities.\"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\n \"temperature\": 0.7,\n # \"max_tokens\": 4000 # Add token limit to prevent overflow\n },\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\n \"temperature\": 0.7,\n #\"max_tokens\": 4000\n },\n ),\n }\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\n \"model\": models[\"assistant\"],\n \"tools\": tools,\n }\n\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n return OwlRolePlaying(\n **task_kwargs,\n user_role_name=\"content_curator\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"research_assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\nasync def main():\n config_path = Path(__file__).parent / \"mcp_servers_config.json\"\n mcp_toolkit = MCPToolkit(config_path=str(config_path))\n\n try:\n await mcp_toolkit.connect()\n\n default_task = (\n \"Find me the best Airbnb in Gurugram with a check-in date of 2025-06-01 \"\n \"and a check-out date of 2025-06-07 for 2 adults. Return the top 5 listings with their names, \"\n \"prices, and locations.\"\n )\n\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Connect to all MCP toolkits\n tools = [*mcp_toolkit.get_tools()]\n society = await construct_society(task, tools)\n \n try:\n # Add error handling for the society execution\n result = await arun_society(society)\n \n # Handle the result properly\n if isinstance(result, tuple) and len(result) == 3:\n answer, chat_history, token_count = result\n else:\n answer = str(result)\n chat_history = []\n token_count = 0\n\n except Exception as e:\n print(f\"Error during society execution: {str(e)}\")\n raise\n\n finally:\n # Cleanup\n await asyncio.sleep(1)\n tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]\n for task in tasks:\n task.cancel()\n try:\n await task\n except asyncio.CancelledError:\n pass\n \n try:\n await mcp_toolkit.disconnect()\n except Exception as e:\n print(f\"Cleanup error (can be ignored): {e}\")\n\nif __name__ == \"__main__\":\n try:\n asyncio.run(main())\n except KeyboardInterrupt:\n print(\"\\nShutting down gracefully...\")\n finally:\n if sys.platform == 'win32':\n try:\n import asyncio.windows_events\n asyncio.windows_events._overlapped = None\n except (ImportError, AttributeError):\n pass"], ["/owl/community_usecase/Notion-MCP/notion_manager.py", "import os\nimport asyncio\nimport sys\nfrom pathlib import Path\nfrom typing import List\n\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import FunctionTool, MCPToolkit\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import get_logger, set_log_file\n\nfrom owl.utils.enhanced_role_playing import OwlRolePlaying, arun_society\n\n# Set logging level\nset_log_file(\"notion_mcp.log\")\nlogger = get_logger(__name__)\n\n# Load environment variables\nload_dotenv(os.path.join(os.path.dirname(__file__), '../../owl/.env'))\n\nasync def construct_society(\n question: str,\n tools: List[FunctionTool],\n) -> OwlRolePlaying:\n \"\"\"Build a multi-agent OwlRolePlaying instance for Notion management.\"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\n \"temperature\": 0.7,\n },\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\n \"temperature\": 0.7,\n },\n ),\n }\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\n \"model\": models[\"assistant\"],\n \"tools\": tools,\n }\n\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n return OwlRolePlaying(\n **task_kwargs,\n user_role_name=\"notion_manager\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"notion_assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\nasync def execute_notion_task(society: OwlRolePlaying):\n \"\"\"Execute the Notion task and handle the result.\"\"\"\n try:\n result = await arun_society(society)\n \n if isinstance(result, tuple) and len(result) == 3:\n answer, chat_history, token_count = result\n logger.info(f\"\\nTask Result: {answer}\")\n logger.info(f\"Token count: {token_count}\")\n else:\n logger.info(f\"\\nTask Result: {result}\")\n \n except Exception as e:\n logger.info(f\"\\nError during task execution: {str(e)}\")\n raise\n\nasync def main():\n config_path = Path(__file__).parent / \"mcp_servers_config.json\"\n mcp_toolkit = MCPToolkit(config_path=str(config_path))\n\n try:\n logger.info(\"Connecting to Notion MCP server...\")\n await mcp_toolkit.connect()\n logger.info(\"Successfully connected to Notion MCP server\")\n\n default_task = (\n\n \"Notion Task:\\n\"\n \"1. Find the page titled 'Travel Itinerary\\n\"\n \"2. Create a list of Top 10 travel destinations in Europe and add them to the page along with their description.\\n\"\n \"3. Also mention the best time to visit these destintions.\\n\"\n\n )\n\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n logger.info(f\"\\nExecuting task:\\n{task}\")\n\n tools = [*mcp_toolkit.get_tools()]\n society = await construct_society(task, tools)\n \n await execute_notion_task(society)\n\n except Exception as e:\n logger.info(f\"\\nError: {str(e)}\")\n raise\n\n finally:\n logger.info(\"\\nPerforming cleanup...\")\n tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]\n for task in tasks:\n task.cancel()\n try:\n await task\n except asyncio.CancelledError:\n pass\n \n try:\n await mcp_toolkit.disconnect()\n logger.info(\"Successfully disconnected from Notion MCP server\")\n except Exception as e:\n logger.info(f\"Cleanup error (can be ignored): {e}\")\n\nif __name__ == \"__main__\":\n try:\n asyncio.run(main())\n except KeyboardInterrupt:\n logger.info(\"\\nReceived keyboard interrupt. Shutting down gracefully...\")\n finally:\n if sys.platform == 'win32':\n try:\n import asyncio.windows_events\n asyncio.windows_events._overlapped = None\n except (ImportError, AttributeError):\n pass"], ["/owl/community_usecase/excel_analyzer/data_analyzer_zh.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport os\nimport sys\n\n\nfrom dotenv import load_dotenv\nfrom camel.configs import ChatGPTConfig\nfrom camel.models import ModelFactory\nfrom camel.messages.base import BaseMessage\n\nfrom camel.toolkits import (\n CodeExecutionToolkit,\n ExcelToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType\n\nfrom owl.utils import OwlRolePlaying\nfrom typing import Dict, List, Optional, Tuple\nfrom camel.logger import set_log_level, set_log_file, get_logger\n\nimport pathlib\n\nlogger = get_logger(__name__)\n\nbase_dir = pathlib.Path(__file__).parent.parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\nclass ExcelRolePalying(OwlRolePlaying):\n def _construct_gaia_sys_msgs(self):\n user_system_prompt = f\"\"\"\n### ===== 用户规则 ===== \n永远不要忘记,你是用户,而我是助手。绝对不能互换角色! 你必须始终指导我,我们的共同目标是合作完成任务。 \n我的职责是帮助你完成一个复杂的任务。 \n\n你必须根据我的专业能力和你的需求逐步指导我解决任务。 \n你的指令格式必须为: \n`Instruction: [你的指令]` \n其中,\"Instruction\" 代表一个子任务或问题。 \n\n- 你每次只能给出一个指令。 \n- 我必须依据你的指令提供适当的解决方案。 \n- 你只能指导我,而不能向我提问。 \n\n---\n\n### 请注意 \n任务可能会非常复杂,不要试图一次性解决整个任务! \n你必须让我一步一步地寻找答案。 \n\n以下是一些能帮助你给出更有价值指令的提示: \n\n#### \n- 我可以使用各种工具,比如:excel Toolkit 和 code Execution Toolkit 等。\n\n- 尽管任务复杂,但答案是存在的。 \n 如果你发现当前方案无法找到答案,请重新规划任务,使用其他方法或工具来达到相同的目标。 \n\n- 务必提醒我验证最终答案是否正确! \n 这可以通过多种方式完成,例如截图、网页分析等。 \n\n- 如果我编写了代码,请提醒我运行代码并获取结果。 \n\n- 请灵活使用代码解决问题,尤其是涉及 Excel 相关任务时。 \n\n\n\n---\n\n### 任务描述 \n当前任务如下: \n{self.task_prompt} \n永远不要忘记这个任务! \n\n### 任务执行规则 \n你现在必须开始 逐步指导我完成任务。 \n- 不要添加任何额外的内容! \n- 继续给出指令,直到你认为任务完成。 \n\n### 任务完成规则 \n当任务完成时,你只能回复一个单词: \n`` \n\n在我的回答完全解决你的任务之前,绝对不要说 ``!\n \"\"\"\n\n assistant_system_prompt = f\"\"\"\n===== 助手规则 ===== \n永远不要忘记,你是助手,而我是用户。绝对不能互换角色! 绝对不能指挥我! 你必须利用你的工具来解决我分配的任务。 \n我们的共同目标是合作完成一个复杂的任务。 \n你的职责是帮助我完成任务。 \n\n当前任务如下: \n{self.task_prompt} \n永远不要忘记这个任务! \n\n我会根据你的专业能力和我的需求指导你完成任务。 \n每条指令通常是一个子任务或问题。 \n\n你必须充分利用你的工具,尽力解决问题,并详细解释你的解决方案。 \n除非我宣布任务完成,你的回答必须以以下格式开始: \n\nSolution: [你的解决方案] \n\n[你的解决方案] 必须具体,包含详细的解释,并提供可行的实现方案、示例或清单来解决任务。 \n\n---\n\n### 请注意:整体任务可能会非常复杂! \n以下是一些可能帮助你解决任务的重要提示: \n\n#### \n- 如果一种方法失败了,尝试其他方法。答案是存在的! \n- 当涉及到查看某个excel信息的时候,你可以总是以编写python代码读入excel文件查看sheet名,列名之类的信息开始。\n- 当你尝试给出python代码的时候,始终记得在最开头import相关的库,比如下面这些excel分析常见的库\n```\nimport pandas as pd\n```\n- 始终验证你的最终答案是否正确! \n- 请每次都从头开始编写完整代码,编写代码后,务必运行代码并获取结果! \n 如果遇到错误,尝试调试代码。 \n- 如果工具运行失败,或者代码无法正确运行, \n 绝对不要假设其返回了正确结果,并在此基础上继续推理! \n 正确的做法是分析错误原因,并尝试修正! \n- [重要!!!]如果你写的代码涉及到用matplotlib画图,请始终在代码开头下面这段代码:\n```\nimport matplotlib\nmatplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 支持中文\nmatplotlib.rcParams['axes.unicode_minus'] = False # 解决负号显示问题\n```\n- 请始终使用英文来画图,比如title, xlabel, ylabel以及其他均使用英文。\n\n \"\"\"\n\n user_sys_msg = BaseMessage.make_user_message(\n role_name=self.user_role_name, content=user_system_prompt\n )\n\n assistant_sys_msg = BaseMessage.make_assistant_message(\n role_name=self.assistant_role_name, content=assistant_system_prompt\n )\n\n return user_sys_msg, assistant_sys_msg\n\ndef run_society(\n society: OwlRolePlaying,\n round_limit: int = 15,\n) -> Tuple[str, List[dict], dict]:\n overall_completion_token_count = 0\n overall_prompt_token_count = 0\n\n chat_history = []\n init_prompt = \"\"\"\n现在请给我逐步解决整个任务的指令。如果任务需要一些特定的知识,请指示我使用工具来完成任务。\n \"\"\"\n input_msg = society.init_chat(init_prompt)\n for _round in range(round_limit):\n assistant_response, user_response = society.step(input_msg)\n # Check if usage info is available before accessing it\n if assistant_response.info.get(\"usage\") and user_response.info.get(\"usage\"):\n overall_completion_token_count += assistant_response.info[\"usage\"].get(\n \"completion_tokens\", 0\n ) + user_response.info[\"usage\"].get(\"completion_tokens\", 0)\n overall_prompt_token_count += assistant_response.info[\"usage\"].get(\n \"prompt_tokens\", 0\n ) + user_response.info[\"usage\"].get(\"prompt_tokens\", 0)\n\n # convert tool call to dict\n tool_call_records: List[dict] = []\n if assistant_response.info.get(\"tool_calls\"):\n for tool_call in assistant_response.info[\"tool_calls\"]:\n tool_call_records.append(tool_call.as_dict())\n\n _data = {\n \"user\": user_response.msg.content\n if hasattr(user_response, \"msg\") and user_response.msg\n else \"\",\n \"assistant\": assistant_response.msg.content\n if hasattr(assistant_response, \"msg\") and assistant_response.msg\n else \"\",\n \"tool_calls\": tool_call_records,\n }\n\n chat_history.append(_data)\n logger.info(\n f\"Round #{_round} user_response:\\n {user_response.msgs[0].content if user_response.msgs and len(user_response.msgs) > 0 else ''}\"\n )\n logger.info(\n f\"Round #{_round} assistant_response:\\n {assistant_response.msgs[0].content if assistant_response.msgs and len(assistant_response.msgs) > 0 else ''}\"\n )\n\n if (\n assistant_response.terminated\n or user_response.terminated\n or \"TASK_DONE\" in user_response.msg.content\n ):\n break\n\n input_msg = assistant_response.msg\n\n answer = chat_history[-1][\"assistant\"]\n token_info = {\n \"completion_token_count\": overall_completion_token_count,\n \"prompt_token_count\": overall_prompt_token_count,\n }\n\n return answer, chat_history, token_info\n\ndef construct_society(question: str) -> ExcelRolePalying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n OwlRolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n base_model_config = {\n \"model_platform\": ModelPlatformType.DEEPSEEK,\n \"model_type\": 'deepseek-chat',\n \"model_config_dict\": ChatGPTConfig(temperature=0.1, max_tokens=8192).as_dict(),\n }\n\n # Create models for different components using Azure OpenAI\n # base_model_config = {\n # \"model_platform\": ModelPlatformType.AZURE,\n # \"model_type\": os.getenv(\"AZURE_OPENAI_MODEL_TYPE\"),\n # \"model_config_dict\": ChatGPTConfig(temperature=0.4, max_tokens=4096).as_dict(),\n # }\n\n\n models = {\n \"user\": ModelFactory.create(**base_model_config),\n \"assistant\": ModelFactory.create(**base_model_config),\n }\n\n # Configure toolkits\n tools = [\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ExcelToolkit().get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = ExcelRolePalying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n output_language=\"中文\"\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with Azure OpenAI.\"\"\"\n # Example question\n # default_task = \"\"\"帮忙分析一下这个文件中各个学院的录取人数以及最高分最低分,把这些信息画到一张图上,并存到当前路径下。文件路径是`./data/admission_zh.xlsx`\"\"\"\n\n default_task = \"\"\"帮忙分析一下`./data/admission_zh.xlsx`这个文件,请你:\n - 统计各个学院的录取人数以及最高分最低分\n - 把这些信息画到一张图上,录取人数使用柱状图,最高分最低分使用折线图\n - 把画完的图`vis_zh.png`存到当前目录下\"\"\"\n\n\n set_log_file('log.txt')\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/PHI_Sanitization_Summarization_and_Article_Writing/project.py", "import streamlit as st\nfrom dotenv import load_dotenv\nfrom pathlib import Path\nimport os\n\n# Import Camel-AI and OWL modules\nfrom camel.models import ModelFactory\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.societies import RolePlaying\nfrom camel.toolkits import (\n ExcelToolkit,\n SearchToolkit,\n CodeExecutionToolkit,\n)\nfrom owl.utils import run_society\nfrom owl.utils import DocumentProcessingToolkit\n\n# Set log level to see detailed logs (optional)\nset_log_level(\"DEBUG\")\n\n# Load environment variables from .env file if available\n\nload_dotenv()\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_wiki,\n SearchToolkit().search_baidu,\n *ExcelToolkit().get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\ndef summarize_section():\n st.header(\"Summarize Medical Text\")\n text = st.text_area(\"Enter medical text to summarize:\", height=200)\n if st.button(\"Summarize\"):\n if text:\n # Create a task prompt for summarization\n task_prompt = f\"Summarize the following medical text:\\n\\n{text}\"\n society = construct_society(task_prompt)\n with st.spinner(\"Running summarization society...\"):\n answer, chat_history, token_count = run_society(society)\n st.subheader(\"Summary:\")\n st.write(answer)\n st.write(chat_history)\n else:\n st.warning(\"Please enter some text to summarize.\")\n\ndef write_and_refine_article_section():\n st.header(\"Write and Refine Research Article\")\n topic = st.text_input(\"Enter the topic for the research article:\")\n outline = st.text_area(\"Enter an outline (optional):\", height=150)\n if st.button(\"Write and Refine Article\"):\n if topic:\n # Create a task prompt for article writing and refinement\n task_prompt = f\"Write a research article on the topic: {topic}.\"\n if outline.strip():\n task_prompt += f\" Use the following outline as guidance:\\n{outline}\"\n society = construct_society(task_prompt)\n with st.spinner(\"Running research article society...\"):\n print(task_prompt)\n answer, chat_history, token_count = run_society(society)\n st.subheader(\"Article:\")\n st.write(answer)\n st.write(chat_history)\n else:\n st.warning(\"Please enter a topic for the research article.\")\n\ndef sanitize_data_section():\n st.header(\"Sanitize Medical Data (PHI)\")\n data = st.text_area(\"Enter medical data to sanitize:\", height=200)\n if st.button(\"Sanitize Data\"):\n if data:\n # Create a task prompt for data sanitization\n task_prompt = f\"Sanitize the following medical data by removing any protected health information (PHI):\\n\\n{data}\"\n society = construct_society(task_prompt)\n with st.spinner(\"Running data sanitization society...\"):\n answer, chat_history, token_count = run_society(society)\n st.subheader(\"Sanitized Data:\")\n st.write(answer)\n st.write(chat_history)\n else:\n st.warning(\"Please enter medical data to sanitize.\")\n\ndef main():\n st.set_page_config(page_title=\"Multi-Agent AI System with Camel & OWL\", layout=\"wide\")\n st.title(\"Multi-Agent AI System with Camel-AI and OWL\")\n\n st.sidebar.title(\"Select Task\")\n task = st.sidebar.selectbox(\"Choose a task:\", [\n \"Summarize Medical Text\",\n \"Write and Refine Research Article\",\n \"Sanitize Medical Data (PHI)\"\n ])\n\n if task == \"Summarize Medical Text\":\n summarize_section()\n elif task == \"Write and Refine Research Article\":\n write_and_refine_article_section()\n elif task == \"Sanitize Medical Data (PHI)\":\n sanitize_data_section()\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/virtual_fitting_room/run_gpt4o.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport os\nimport logging\nimport functools\nimport json\nfrom typing import Callable, Any, Dict, List\n\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory, BaseModelBackend\n\nfrom camel.toolkits import (\n ExcelToolkit,\n ImageAnalysisToolkit,\n SearchToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n VirtualTryOnToolkit\n)\nfrom camel.toolkits.base import BaseToolkit\nfrom camel.types import ModelPlatformType\n\nfrom owl.utils import run_society\nfrom camel.societies import RolePlaying\nfrom camel.logger import set_log_level, get_logger\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\n# set detailed log recording for debug\nset_log_level(level=\"DEBUG\")\nlogger = get_logger(__name__)\nfile_handler = logging.FileHandler('tool_calls.log')\nfile_handler.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nfile_handler.setFormatter(formatter)\nlogger.addHandler(file_handler)\n\nroot_logger = logging.getLogger()\nroot_logger.addHandler(file_handler)\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components (here I use gpt-4o for all agents, so remember to set the openai key in .env)\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.4},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.4},\n ),\n \"web\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.2},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.3},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"gpt-4o\",\n api_key=os.getenv(\"OPENAI_API_KEY\"),\n model_config_dict={\"temperature\": 0.4},\n ),\n }\n\n # prepare toolkits\n image_toolkit = ImageAnalysisToolkit(model=models[\"image\"])\n browser_toolkit = BrowserToolkit(\n headless=False,\n web_agent_model=models[\"web\"],\n planning_agent_model=models[\"planning\"],\n )\n excel_toolkit = ExcelToolkit()\n file_toolkit = FileWriteToolkit(output_dir=\"./\")\n virtual_try_on_toolkit = VirtualTryOnToolkit()\n \n tools = [\n *browser_toolkit.get_tools(),\n *image_toolkit.get_tools(),\n SearchToolkit().search_duckduckgo,\n # SearchToolkit().search_google,\n # SearchToolkit().search_wiki,\n *excel_toolkit.get_tools(),\n *file_toolkit.get_tools(),\n *virtual_try_on_toolkit.get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n\n question = f\"open https://www.uniqlo.com/eu-at/en/women/tops?path=37608%2C84986%2C85018%2C85207 which shows some clothes on sale. First, directly click one image of clothes which should be an big interactive element (don't wrongly click the small like button overlapped on the image!) to go into its specific details page and then get a partial screenshot for this clothes. Second, only after you've get the partial screenshort of the product, using your own virtual try-on toolkit (there is no built-in virtual try-on button on this website, either no third party tool required) to show me the virtual try-on result with the product.\"\n\n # Construct and run the society\n society = construct_society(question)\n answer, chat_history, token_count = run_society(society)\n # output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/investment_agent.py", "\"\"\"\n投资分析代理实现\n\"\"\"\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport json\nimport re\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import StockData\n\nfrom camel.messages import BaseMessage\n\n\nclass InvestmentAgent(BaseAgent):\n \"\"\"投资分析代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化投资分析代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"investment_analyst\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"InvestmentAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理投资分析请求\n \n Args:\n data: 输入数据,包含股票信息\n \n Returns:\n Dict[str, Any]: 投资分析结果\n \"\"\"\n try:\n # 获取输入数据\n stock_data = data.get(\"stock_data\")\n if not stock_data:\n raise ValueError(\"缺少股票数据\")\n \n ticker = stock_data.ticker\n \n # 获取财务数据\n fundamental_data = stock_data.fundamental_data\n \n # 获取历史数据\n historical_data = fundamental_data.get(\"historical_data\", [])\n financial_trends = fundamental_data.get(\"trends\", {})\n \n # 创建分析提示\n prompt = f\"\"\"你是一位专业的投资分析师,请根据以下数据对股票 {ticker} 进行全面的投资分析和推荐:\n\n 1. 基本面分析:\n - 财务状况:分析公司收入、利润、现金流和资产负债情况\n - 增长趋势:评估收入增长、利润增长和ROE变化趋势\n - 估值指标:分析市盈率、市净率等估值指标的合理性\n \n 2. 技术面分析:\n - 价格趋势:分析股票价格走势\n - 成交量:评估交易量变化\n - 技术指标:解读主要技术指标\n \n 3. 投资建议:\n - 给出明确的投资建议(买入/持有/卖出)\n - 说明理由和风险因素\n - 给出合理的目标价格区间\n\n 4. 风险分析:\n - 列出主要风险因素\n - 给出风险应对建议\n\n 请基于数据给出客观、全面的分析,避免过度乐观或悲观的观点。分析应当深入浅出,使投资者容易理解。\n \"\"\"\n \n # 构建分析输入\n analysis_input = {\n \"ticker\": ticker,\n \"financial_data\": fundamental_data,\n \"historical_data\": historical_data,\n \"financial_trends\": financial_trends,\n \"technical_indicators\": stock_data.technical_indicators,\n \"historical_prices\": stock_data.historical_data,\n \"news\": stock_data.news_data\n }\n \n # 使用代理进行分析\n analysis_result = self._process_data_with_agent(prompt, analysis_input)\n \n # 提取投资建议\n recommendation = self._extract_recommendation(analysis_result)\n \n # 返回结果\n return {\n \"analysis\": analysis_result,\n \"recommendation\": recommendation,\n \"messages\": [] # 暂时返回空消息列表\n }\n \n except Exception as e:\n self.logger.error(f\"进行投资分析时发生错误: {str(e)}\")\n raise e\n\n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> str:\n \"\"\"使用代理处理数据分析请求\n \n Args:\n prompt: 分析提示\n data: 包含基本面数据和历史数据的数据\n \n Returns:\n str: 分析结果文本\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请提供详细的分析报告。\n\"\"\"\n # 发送到Camel代理进行分析\n human_message = self.generate_human_message(content=full_prompt)\n response = self.agent.step(human_message)\n self.log_message(response.msgs[0])\n \n # 返回结果文本\n return response.msgs[0].content\n \n def generate_human_message(self, content: str) -> BaseMessage:\n \"\"\"生成人类消息\n \n Args:\n content: 消息内容\n \n Returns:\n BaseMessage: 人类消息对象\n \"\"\"\n return BaseMessage(role_name=\"Human\", role_type=\"user\", meta_info={}, content=content)\n \n def parse_json_response(self, response: str) -> Dict[str, Any]:\n \"\"\"解析JSON响应\n \n Args:\n response: 响应文本\n \n Returns:\n Dict[str, Any]: 解析后的JSON数据\n \"\"\"\n try:\n # 尝试提取JSON部分\n json_match = re.search(r'```json\\s*([\\s\\S]*?)\\s*```', response)\n if json_match:\n json_str = json_match.group(1)\n else:\n # 尝试找到可能的JSON对象\n json_match = re.search(r'\\{[\\s\\S]*\\}', response)\n if json_match:\n json_str = json_match.group(0)\n else:\n return {}\n \n # 解析JSON\n return json.loads(json_str)\n except Exception as e:\n self.logger.error(f\"解析JSON响应时发生错误: {str(e)}\")\n return {}\n\n def _extract_recommendation(self, analysis: str) -> Dict[str, Any]:\n \"\"\"从分析结果中提取投资建议\n \n Args:\n analysis: 分析文本\n \n Returns:\n Dict[str, Any]: 投资建议\n \"\"\"\n try:\n # 使用代理提取关键信息\n prompt = \"\"\"从以下投资分析报告中提取关键信息,包括:\n 1. 投资评级(买入/持有/卖出)\n 2. 目标价格区间(如果有)\n 3. 主要投资理由(不超过3点)\n 4. 主要风险因素(不超过3点)\n \n 以JSON格式返回结果,包含以下字段:\n - rating: 投资评级\n - target_price_low: 目标价格下限(如果有)\n - target_price_high: 目标价格上限(如果有)\n - reasons: 投资理由列表\n - risks: 风险因素列表\n \n 分析报告:\n \"\"\"\n \n extraction_result = self._process_data_with_agent(prompt + analysis, {})\n \n # 尝试解析JSON结果\n try:\n import json\n json_match = re.search(r'\\{[\\s\\S]*\\}', extraction_result)\n if json_match:\n json_str = json_match.group(0)\n recommendation = json.loads(json_str)\n return recommendation\n else:\n return {\n \"rating\": self._determine_rating(analysis),\n \"target_price_low\": 0,\n \"target_price_high\": 0,\n \"reasons\": [],\n \"risks\": []\n }\n except:\n # 如果解析失败,返回简化结果\n return {\n \"rating\": self._determine_rating(analysis),\n \"target_price_low\": 0,\n \"target_price_high\": 0,\n \"reasons\": [],\n \"risks\": []\n }\n \n except Exception as e:\n self.logger.error(f\"提取投资建议时发生错误: {str(e)}\")\n return {\n \"rating\": \"未知\",\n \"target_price_low\": 0,\n \"target_price_high\": 0,\n \"reasons\": [],\n \"risks\": []\n }\n \n def _determine_rating(self, analysis: str) -> str:\n \"\"\"从分析文本中确定投资评级\n \n Args:\n analysis: 分析文本\n \n Returns:\n str: 投资评级\n \"\"\"\n analysis_lower = analysis.lower()\n \n if \"买入\" in analysis or \"强烈推荐\" in analysis or \"buy\" in analysis_lower:\n return \"买入\"\n elif \"卖出\" in analysis or \"sell\" in analysis_lower:\n return \"卖出\"\n elif \"持有\" in analysis or \"观望\" in analysis or \"hold\" in analysis_lower:\n return \"持有\"\n else:\n return \"未知\"\n \n def _analyze_financial_trends(self, historical_data: List[Dict[str, Any]], trends: Dict[str, Any]) -> str:\n \"\"\"分析财务趋势\n \n Args:\n historical_data: 历史财务数据\n trends: 财务趋势数据\n \n Returns:\n str: 财务趋势分析\n \"\"\"\n if not historical_data or len(historical_data) < 2:\n return \"财务数据不足以进行趋势分析。\"\n \n analysis = []\n \n # 收入趋势分析\n if \"revenue\" in trends:\n revenue_trend = trends[\"revenue\"]\n revenue_values = revenue_trend.get(\"values\", [])\n revenue_growth = revenue_trend.get(\"growth\", 0)\n revenue_trend_dir = revenue_trend.get(\"trend\", \"未知\")\n \n if revenue_values:\n if revenue_growth > 20:\n analysis.append(f\"公司收入呈高速{revenue_trend_dir}趋势,同比增长{revenue_growth:.2f}%,显示出强劲的业务增长。\")\n elif revenue_growth > 5:\n analysis.append(f\"公司收入呈稳健{revenue_trend_dir}趋势,同比增长{revenue_growth:.2f}%,业务发展稳定。\")\n elif revenue_growth >= 0:\n analysis.append(f\"公司收入略有{revenue_trend_dir},同比增长{revenue_growth:.2f}%,业务增长放缓。\")\n else:\n analysis.append(f\"公司收入呈{revenue_trend_dir}趋势,同比下降{abs(revenue_growth):.2f}%,业务面临挑战。\")\n \n # 净利润趋势分析\n if \"net_income\" in trends:\n income_trend = trends[\"net_income\"]\n income_values = income_trend.get(\"values\", [])\n income_growth = income_trend.get(\"growth\", 0)\n income_trend_dir = income_trend.get(\"trend\", \"未知\")\n \n if income_values:\n if income_growth > 20:\n analysis.append(f\"公司净利润呈高速{income_trend_dir}趋势,同比增长{income_growth:.2f}%,盈利能力强劲。\")\n elif income_growth > 5:\n analysis.append(f\"公司净利润呈稳健{income_trend_dir}趋势,同比增长{income_growth:.2f}%,盈利能力稳定。\")\n elif income_growth >= 0:\n analysis.append(f\"公司净利润略有{income_trend_dir},同比增长{income_growth:.2f}%,盈利增长放缓。\")\n else:\n analysis.append(f\"公司净利润呈{income_trend_dir}趋势,同比下降{abs(income_growth):.2f}%,盈利能力受到挑战。\")\n \n # ROE趋势分析\n if \"roe\" in trends:\n roe_trend = trends[\"roe\"]\n roe_values = roe_trend.get(\"values\", [])\n roe_trend_dir = roe_trend.get(\"trend\", \"未知\")\n \n if roe_values and len(roe_values) > 0:\n latest_roe = roe_values[0]\n if latest_roe > 15:\n analysis.append(f\"公司ROE为{latest_roe:.2f}%,处于较高水平,资本回报率优秀。ROE呈{roe_trend_dir}趋势。\")\n elif latest_roe > 10:\n analysis.append(f\"公司ROE为{latest_roe:.2f}%,处于良好水平,资本回报率不错。ROE呈{roe_trend_dir}趋势。\")\n elif latest_roe > 5:\n analysis.append(f\"公司ROE为{latest_roe:.2f}%,处于一般水平,资本回报率尚可。ROE呈{roe_trend_dir}趋势。\")\n else:\n analysis.append(f\"公司ROE为{latest_roe:.2f}%,处于较低水平,资本回报率不佳。ROE呈{roe_trend_dir}趋势。\")\n \n # 季度对比分析\n if len(historical_data) >= 4:\n latest_quarter = historical_data[0]\n year_ago_quarter = None\n \n # 寻找去年同期数据(通常是第4个季度报告)\n if len(historical_data) >= 4:\n year_ago_quarter = historical_data[3]\n \n if latest_quarter and year_ago_quarter:\n latest_revenue = float(latest_quarter[\"income_statement\"][\"revenue\"])\n latest_net_income = float(latest_quarter[\"income_statement\"][\"net_income\"])\n \n year_ago_revenue = float(year_ago_quarter[\"income_statement\"][\"revenue\"])\n year_ago_net_income = float(year_ago_quarter[\"income_statement\"][\"net_income\"])\n \n # 计算同比增长率\n if year_ago_revenue > 0:\n yoy_revenue_growth = (latest_revenue - year_ago_revenue) / year_ago_revenue * 100\n analysis.append(f\"同比而言,该季度营收增长{yoy_revenue_growth:.2f}%。\")\n \n if year_ago_net_income > 0:\n yoy_net_income_growth = (latest_net_income - year_ago_net_income) / year_ago_net_income * 100\n analysis.append(f\"同比而言,该季度净利润增长{yoy_net_income_growth:.2f}%。\")\n \n return \"\\n\".join(analysis) "], ["/owl/community_usecase/Whatsapp-MCP/app.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\"\"\"MCP Multi-Agent System Example\n\nThis example demonstrates how to use MCP (Model Context Protocol) with CAMEL agents\nfor advanced information retrieval and processing tasks.\n\nEnvironment Setup:\n1. Configure the required dependencies of owl library\n Refer to: https://github.com/camel-ai/owl for installation guide\n\n2. MCP Server Setup:\n\n\n 2.1 MCP Playwright Service:\n ```bash\n # Install MCP service\n npm install -g @executeautomation/playwright-mcp-server\n npx playwright install-deps\n\n # Configure in mcp_servers_config.json:\n {\n \"mcpServers\": {\n \"playwright\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n }\n }\n }\n ```\n\n 2.2 MCP Fetch Service (Optional - for better retrieval):\n ```bash\n # Install MCP service\n pip install mcp-server-fetch\n\n # Configure in mcp_servers_config.json:\n {\n \"mcpServers\": {\n \"fetch\": {\n \"command\": \"python\",\n \"args\": [\"-m\", \"mcp_server_fetch\"]\n }\n }\n }\n ```\n\nUsage:\n1. Ensure all MCP servers are properly configured in mcp_servers_config.json\n2. Run this script to create a multi-agent system that can:\n - Access and manipulate files through MCP Desktop Commander\n - Perform web automation tasks using Playwright\n - Process and generate information using GPT-4o\n - Fetch web content (if fetch service is configured)\n3. The system will execute the specified task while maintaining security through\n controlled access\n\nNote:\n- All file operations are restricted to configured directories\n- System uses GPT-4o for both user and assistant roles\n- Supports asynchronous operations for efficient processing\n\"\"\"\n\nimport asyncio\nimport sys\nfrom pathlib import Path\nfrom typing import List\n\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import FunctionTool\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.toolkits import MCPToolkit,SearchToolkit\n\nfrom owl.utils.enhanced_role_playing import OwlRolePlaying, arun_society\n\nload_dotenv()\n\nset_log_level(level=\"DEBUG\")\n\n\nasync def construct_society(\n question: str,\n tools: List[FunctionTool],\n) -> OwlRolePlaying:\n r\"\"\"build a multi-agent OwlRolePlaying instance.\n\n Args:\n question (str): The question to ask.\n tools (List[FunctionTool]): The MCP tools to use.\n \"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\n \"model\": models[\"assistant\"],\n \"tools\": tools,\n }\n\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n society = OwlRolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n return society\n\n\nasync def main():\n config_path = Path(__file__).parent / \"mcp_servers_config.json\"\n mcp_toolkit = MCPToolkit(config_path=str(config_path))\n\n try:\n print(\"Attempting to connect to MCP servers...\")\n await mcp_toolkit.connect()\n\n # Default task\n default_task = (\n \"Read the unread messages from {contact name} on whatsapp and reply to his query\"\n )\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n # Connect to all MCP toolkits\n tools = [*mcp_toolkit.get_tools(),SearchToolkit().search_duckduckgo,]\n society = await construct_society(task, tools)\n answer, chat_history, token_count = await arun_society(society)\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n except Exception as e:\n print(f\"An error occurred during connection: {e}\")\n\n finally:\n # Make sure to disconnect safely after all operations are completed.\n try:\n await mcp_toolkit.disconnect()\n except Exception:\n print(\"Disconnect failed\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n"], ["/owl/licenses/update_license.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport os\nimport re\nimport sys\nfrom pathlib import Path\nfrom typing import List\n\n\n# The license template file is hard-coded with specific start and end lines\ndef fine_license_start_line(lines: List[str], start_with: str) -> int:\n for i in range(len(lines)):\n if lines[i].startswith(start_with):\n return i\n return None\n\n\ndef find_license_end_line(lines: List[str], start_with: str) -> int:\n for i in range(len(lines) - 1, -1, -1):\n if lines[i].startswith(start_with):\n return i\n return None\n\n\ndef update_license_in_file(\n file_path: str,\n license_template_path: str,\n start_line_start_with: str,\n end_line_start_with: str,\n) -> bool:\n with open(file_path, \"r\", encoding=\"utf-8\") as f: # for windows compatibility\n content = f.read()\n\n with open(license_template_path, \"r\", encoding=\"utf-8\") as f:\n new_license = f.read().strip()\n\n maybe_existing_licenses = re.findall(\n r\"^#.*?(?=\\n)\", content, re.MULTILINE | re.DOTALL\n )\n start_index = fine_license_start_line(\n maybe_existing_licenses, start_line_start_with\n )\n end_index = find_license_end_line(maybe_existing_licenses, end_line_start_with)\n if start_index is not None and end_index is not None:\n maybe_existing_licenses = maybe_existing_licenses[start_index : end_index + 1]\n else:\n maybe_existing_licenses = None\n if maybe_existing_licenses:\n maybe_old_licenses = \"\\n\".join(maybe_existing_licenses)\n if maybe_old_licenses.strip() != new_license.strip():\n replaced_content = content.replace(maybe_old_licenses, new_license)\n with open(file_path, \"w\") as f:\n f.write(replaced_content)\n print(f\"Replaced license in {file_path}\")\n return True\n else:\n return False\n else:\n with open(file_path, \"w\") as f:\n f.write(new_license + \"\\n\" + content)\n print(f\"Added license to {file_path}\")\n return True\n\n\ndef update_license_in_directory(\n directory_path: str,\n license_template_path: str,\n start_line_start_with: str,\n end_line_start_with: str,\n) -> None:\n # Check if directory exists\n if not os.path.isdir(directory_path):\n raise NotADirectoryError(f\"{directory_path} is not a directory\")\n # Check if license template exists\n if not os.path.isfile(license_template_path):\n raise FileNotFoundError(f\"{license_template_path} not found\")\n\n file_count = 0\n for py_files in Path(directory_path).rglob(\"*.py\"):\n if py_files.name.startswith(\".\"):\n continue\n if any(part.startswith(\".\") for part in py_files.parts):\n continue\n # Skip files in the community_usecase directory\n if \"community_usecase\" in py_files.parts:\n continue\n if update_license_in_file(\n py_files,\n license_template_path,\n start_line_start_with,\n end_line_start_with,\n ):\n file_count += 1\n\n print(f\"License updated in {file_count} files\")\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 3:\n print(\n \"Usage from command line: \"\n \"python update_license.py \"\n \"No valid input arguments found, please enter manually.\"\n )\n directory_path = input(\"Enter directory path: \")\n license_template_path = input(\"Enter license template path: \")\n else:\n directory_path = sys.argv[1]\n license_template_path = sys.argv[2]\n\n start_line_start_with = \"# ========= Copyright\"\n end_line_start_with = \"# ========= Copyright\"\n update_license_in_directory(\n directory_path,\n license_template_path,\n start_line_start_with,\n end_line_start_with,\n )\n"], ["/owl/examples/run_mistral.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\"\"\"MCP Multi-Agent System Example\n\nThis example demonstrates how to use MCP (Model Context Protocol) with CAMEL agents\nfor advanced information retrieval and processing tasks.\n\nEnvironment Setup:\n1. Configure the required dependencies of owl library\n Refer to: https://github.com/camel-ai/owl for installation guide\n\n2. MCP Server Setup:\n\n\n 2.1 MCP Playwright Service:\n ```bash\n # Install MCP service\n npm install -g @executeautomation/playwright-mcp-server\n npx playwright install-deps\n\n # Configure in mcp_servers_config.json:\n {\n \"mcpServers\": {\n \"playwright\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n }\n }\n }\n ```\n\n 2.2 MCP Fetch Service (Optional - for better retrieval):\n ```bash\n # Install MCP service\n pip install mcp-server-fetch\n\n # Configure in mcp_servers_config.json:\n {\n \"mcpServers\": {\n \"fetch\": {\n \"command\": \"python\",\n \"args\": [\"-m\", \"mcp_server_fetch\"]\n }\n }\n }\n ```\n\nUsage:\n1. Ensure all MCP servers are properly configured in mcp_servers_config.json\n2. Run this script to create a multi-agent system that can:\n - Access and manipulate files through MCP Desktop Commander\n - Perform web automation tasks using Playwright\n - Process and generate information using Mistral\n - Fetch web content (if fetch service is configured)\n3. The system will execute the specified task while maintaining security through\n controlled access\n\nNote:\n- All file operations are restricted to configured directories\n- Supports asynchronous operations for efficient processing\n\"\"\"\n\nimport asyncio\nimport sys\nfrom pathlib import Path\nfrom typing import List\n\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import FunctionTool\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.toolkits import MCPToolkit, FileWriteToolkit, CodeExecutionToolkit\nfrom camel.societies import RolePlaying\n\nfrom owl.utils.enhanced_role_playing import arun_society\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\nasync def construct_society(\n question: str,\n tools: List[FunctionTool],\n) -> RolePlaying:\n r\"\"\"build a multi-agent RolePlaying instance.\n\n Args:\n question (str): The question to ask.\n tools (List[FunctionTool]): The MCP tools to use.\n \"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.MISTRAL,\n model_type=ModelType.MISTRAL_MEDIUM_3,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.MISTRAL,\n model_type=ModelType.MISTRAL_LARGE,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\n \"model\": models[\"assistant\"],\n \"tools\": tools,\n }\n\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n return society\n\n\nasync def main():\n config_path = Path(__file__).parent / \"mcp_servers_config.json\"\n mcp_toolkit = MCPToolkit(config_path=str(config_path))\n\n try:\n await mcp_toolkit.connect()\n\n # Default task\n default_task = (\n \"Help me search the latest reports about smart city, \"\n \"summarize them and help me generate a PDF file. You have \"\n \"been provided with tools to do browser operation. Open \"\n \"browser to finish the task.\"\n )\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Connect to toolkits\n tools = [\n *mcp_toolkit.get_tools(),\n *FileWriteToolkit().get_tools(),\n *CodeExecutionToolkit().get_tools(),\n ]\n society = await construct_society(task, tools)\n answer, chat_history, token_count = await arun_society(society)\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n finally:\n # Make sure to disconnect safely after all operations are completed.\n try:\n await mcp_toolkit.disconnect()\n except Exception:\n print(\"Disconnect failed\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n"], ["/owl/examples/run_deepseek_zh.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\n\n# To run this file, you need to configure the DeepSeek API key\n# You can obtain your API key from DeepSeek platform: https://platform.deepseek.com/api_keys\n# Set it as DEEPSEEK_API_KEY=\"your-api-key\" in your .env file or add it to your environment variables\n\nimport sys\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n ExcelToolkit,\n SearchToolkit,\n FileWriteToolkit,\n CodeExecutionToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.societies import RolePlaying\nfrom camel.logger import set_log_level\n\nfrom owl.utils import run_society\n\nimport pathlib\n\nset_log_level(level=\"DEBUG\")\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.DEEPSEEK,\n model_type=ModelType.DEEPSEEK_CHAT,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.DEEPSEEK,\n model_type=ModelType.DEEPSEEK_CHAT,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_wiki,\n SearchToolkit().search_baidu,\n *ExcelToolkit().get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n output_language=\"Chinese\",\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Example research question\n default_task = \"搜索OWL项目最近的新闻并生成一篇报告,最后保存到本地。\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run_ppio.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\n\n# To run this file, you need to configure the PPIO API key\n# You can obtain your API key from PPIO platform: https://ppinfra.com/settings/key-management?utm_source=github_owl\n# Set it as PPIO_API_KEY=\"your-api-key\" in your .env file or add it to your environment variables\n\nimport sys\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n ExcelToolkit,\n SearchToolkit,\n FileWriteToolkit,\n CodeExecutionToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.societies import RolePlaying\nfrom camel.logger import set_log_level\n\nfrom owl.utils import run_society\n\nimport pathlib\n\nset_log_level(level=\"DEBUG\")\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.PPIO,\n model_type=ModelType.PPIO_DEEPSEEK_V3_COMMUNITY,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.PPIO,\n model_type=ModelType.PPIO_DEEPSEEK_V3_COMMUNITY,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_wiki,\n SearchToolkit().search_baidu,\n *ExcelToolkit().get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n output_language=\"Chinese\",\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Example research question\n default_task = \"使用百度整理2023年1月1日到2023年12月31日,中国股市的涨跌情况。\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/portfolio_manager.py", "\"\"\"\n投资组合管理代理实现\n\"\"\"\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport pandas as pd\nimport math\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import AnalysisSignal, StockData, RiskAnalysis, TradingDecision\n\nfrom camel.messages import BaseMessage\n\n\nclass PortfolioManagerAgent(BaseAgent):\n \"\"\"投资组合管理代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化投资组合管理代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"portfolio_manager\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"PortfolioManagerAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理投资决策\n \n Args:\n data: 包含以下键的字典:\n - stock_data: 股票数据对象\n - technical_analysis: 技术分析结果\n - fundamentals_analysis: 基本面分析结果\n - sentiment_analysis: 情绪分析结果\n - valuation_analysis: 估值分析结果\n - debate_result: 辩论结果\n - risk_analysis: 风险分析结果\n - portfolio: 投资组合信息\n - messages: 处理过程中的消息\n \n Returns:\n Dict[str, Any]: 处理后的数据,包含以下内容:\n - trading_decision: 交易决策\n - messages: 处理过程中的消息\n \"\"\"\n # 提取各种分析结果和股票数据\n stock_data = data.get(\"stock_data\")\n technical_analysis = data.get(\"technical_analysis\")\n fundamentals_analysis = data.get(\"fundamentals_analysis\")\n sentiment_analysis = data.get(\"sentiment_analysis\")\n valuation_analysis = data.get(\"valuation_analysis\")\n debate_result = data.get(\"debate_result\")\n risk_analysis = data.get(\"risk_analysis\")\n portfolio = data.get(\"portfolio\", {\"cash\": 100000.0, \"stock\": 0})\n \n if not stock_data:\n raise ValueError(\"缺少股票数据\")\n \n self.logger.info(f\"正在制定投资决策\")\n \n try:\n # 提取股票基本信息和最新价格\n ticker = stock_data.ticker\n historical_data = stock_data.historical_data\n latest_price = self._get_latest_price(historical_data)\n \n # 收集所有分析信号\n agent_signals = []\n if technical_analysis:\n agent_signals.append(technical_analysis)\n if fundamentals_analysis:\n agent_signals.append(fundamentals_analysis)\n if sentiment_analysis:\n agent_signals.append(sentiment_analysis)\n if valuation_analysis:\n agent_signals.append(valuation_analysis)\n if debate_result:\n agent_signals.append(debate_result)\n \n # 组织投资决策数据\n decision_data = {\n \"ticker\": ticker,\n \"latest_price\": latest_price,\n \"portfolio\": portfolio,\n \"technical_analysis\": technical_analysis.dict() if technical_analysis else None,\n \"fundamentals_analysis\": fundamentals_analysis.dict() if fundamentals_analysis else None,\n \"sentiment_analysis\": sentiment_analysis.dict() if sentiment_analysis else None,\n \"valuation_analysis\": valuation_analysis.dict() if valuation_analysis else None,\n \"debate_result\": debate_result.dict() if debate_result else None,\n \"risk_analysis\": risk_analysis.dict() if risk_analysis else None\n }\n \n # 使用代理处理数据分析请求\n prompt = f\"\"\"请作为投资组合经理,对股票 {ticker} 制定最终的投资决策。\n 综合考虑以下因素:\n 1. 各类分析师的交易信号\n 2. 辩论结果\n 3. 风险分析\n 4. 当前投资组合状况\n 5. 最新市场价格\n \n 请给出明确的交易行动(buy/sell/hold)、交易数量和详细理由。\n 最新价格: {latest_price}元/股\n \n 返回格式为JSON:\n {{\n \"action\": \"buy/sell/hold\",\n \"quantity\": 数量,\n \"confidence\": 0.8,\n \"reasoning\": \"投资决策详细理由...\"\n }}\n \"\"\"\n \n analysis_result = self._process_data_with_agent(prompt, decision_data)\n \n # 创建交易决策\n trading_decision = self._create_trading_decision(analysis_result, agent_signals)\n \n # 返回处理结果\n return {\n \"trading_decision\": trading_decision,\n \"messages\": []\n }\n \n except Exception as e:\n self.logger.error(f\"制定投资决策过程中发生错误: {str(e)}\")\n \n # 返回默认交易决策\n default_decision = TradingDecision(\n action=\"hold\",\n quantity=0,\n confidence=0.5,\n agent_signals=[],\n reasoning=\"决策过程中发生错误,默认保持不变\"\n )\n \n return {\n \"trading_decision\": default_decision,\n \"messages\": []\n }\n \n def _get_latest_price(self, historical_data: Dict[str, Any]) -> float:\n \"\"\"获取最新价格\n \n Args:\n historical_data: 历史数据\n \n Returns:\n float: 最新价格\n \"\"\"\n try:\n # 假设历史数据中有'close'字段,并且是按时间顺序排列的\n if isinstance(historical_data, list) and len(historical_data) > 0:\n return historical_data[-1].get(\"close\", 0.0)\n elif isinstance(historical_data, dict) and \"close\" in historical_data:\n if isinstance(historical_data[\"close\"], list):\n return historical_data[\"close\"][-1]\n return historical_data[\"close\"]\n except Exception as e:\n self.logger.error(f\"获取最新价格时发生错误: {str(e)}\")\n \n return 0.0\n \n def _create_trading_decision(self, analysis_result: Dict[str, Any], agent_signals: List[AnalysisSignal]) -> TradingDecision:\n \"\"\"创建交易决策\n \n Args:\n analysis_result: 分析结果\n agent_signals: 分析师信号列表\n \n Returns:\n TradingDecision: 交易决策\n \"\"\"\n action = analysis_result.get(\"action\", \"hold\")\n quantity = analysis_result.get(\"quantity\", 0)\n confidence = analysis_result.get(\"confidence\", 0.5)\n reasoning = analysis_result.get(\"reasoning\", \"未提供决策理由\")\n \n # 确保数量是整数\n if not isinstance(quantity, int):\n try:\n quantity = int(quantity)\n except:\n quantity = 0\n \n # 确保数量非负\n quantity = max(0, quantity)\n \n return TradingDecision(\n action=action,\n quantity=quantity,\n confidence=confidence,\n agent_signals=agent_signals,\n reasoning=reasoning\n )\n \n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"使用代理处理数据分析请求\n \n Args:\n prompt: 分析提示\n data: 包含各种分析数据\n \n Returns:\n Dict[str, Any]: 分析结果\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请以JSON格式返回结果。\n\"\"\"\n # 发送到Camel代理进行分析\n human_message = self.generate_human_message(content=full_prompt)\n response = self.agent.step(human_message)\n self.log_message(response.msgs[0])\n \n # 解析结果\n result = self.parse_json_response(response.msgs[0].content)\n \n # 如果解析结果为空,使用默认值\n if not result:\n result = {\n \"action\": \"hold\",\n \"quantity\": 0,\n \"confidence\": 0.5,\n \"reasoning\": \"无法解析投资决策,默认保持不变\"\n }\n \n return result "], ["/owl/examples/run_mcp.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\"\"\"MCP Multi-Agent System Example\n\nThis example demonstrates how to use MCP (Model Context Protocol) with CAMEL agents\nfor advanced information retrieval and processing tasks.\n\nEnvironment Setup:\n1. Configure the required dependencies of owl library\n Refer to: https://github.com/camel-ai/owl for installation guide\n\n2. MCP Server Setup:\n\n\n 2.1 MCP Playwright Service:\n ```bash\n # Install MCP service\n npm install -g @executeautomation/playwright-mcp-server\n npx playwright install-deps\n\n # Configure in mcp_servers_config.json:\n {\n \"mcpServers\": {\n \"playwright\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n }\n }\n }\n ```\n\n 2.2 MCP Fetch Service (Optional - for better retrieval):\n ```bash\n # Install MCP service\n pip install mcp-server-fetch\n\n # Configure in mcp_servers_config.json:\n {\n \"mcpServers\": {\n \"fetch\": {\n \"command\": \"python\",\n \"args\": [\"-m\", \"mcp_server_fetch\"]\n }\n }\n }\n ```\n\nUsage:\n1. Ensure all MCP servers are properly configured in mcp_servers_config.json\n2. Run this script to create a multi-agent system that can:\n - Access and manipulate files through MCP Desktop Commander\n - Perform web automation tasks using Playwright\n - Process and generate information using GPT-4o\n - Fetch web content (if fetch service is configured)\n3. The system will execute the specified task while maintaining security through\n controlled access\n\nNote:\n- All file operations are restricted to configured directories\n- System uses GPT-4o for both user and assistant roles\n- Supports asynchronous operations for efficient processing\n\"\"\"\n\nimport asyncio\nimport sys\nfrom pathlib import Path\nfrom typing import List\n\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import FunctionTool\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.toolkits import MCPToolkit\n\nfrom owl.utils.enhanced_role_playing import OwlRolePlaying, arun_society\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\nasync def construct_society(\n question: str,\n tools: List[FunctionTool],\n) -> OwlRolePlaying:\n r\"\"\"build a multi-agent OwlRolePlaying instance.\n\n Args:\n question (str): The question to ask.\n tools (List[FunctionTool]): The MCP tools to use.\n \"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\n \"model\": models[\"assistant\"],\n \"tools\": tools,\n }\n\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n society = OwlRolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n return society\n\n\nasync def main():\n config_path = Path(__file__).parent / \"mcp_servers_config.json\"\n mcp_toolkit = MCPToolkit(config_path=str(config_path))\n\n try:\n await mcp_toolkit.connect()\n\n # Default task\n default_task = (\n \"I'd like a academic report about Andrew Ng, including \"\n \"his research direction, published papers (At least 3),\"\n \" institutions, etc. \"\n )\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Connect to all MCP toolkits\n tools = [*mcp_toolkit.get_tools()]\n society = await construct_society(task, tools)\n answer, chat_history, token_count = await arun_society(society)\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n finally:\n # Make sure to disconnect safely after all operations are completed.\n try:\n await mcp_toolkit.disconnect()\n except Exception:\n print(\"Disconnect failed\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n"], ["/owl/examples/run_groq.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\n\"\"\"\nThis module provides integration with the Groq API platform for the OWL system.\n\nIt configures different agent roles with appropriate Groq models based on their requirements:\n- Tool-intensive roles (assistant, web, planning, video, image) use GROQ_LLAMA_3_3_70B\n- Document processing uses GROQ_MIXTRAL_8_7B\n- Simple roles (user) use GROQ_LLAMA_3_1_8B\n\nTo use this module:\n1. Set GROQ_API_KEY in your .env file\n2. Set OPENAI_API_BASE_URL to \"https://api.groq.com/openai/v1\"\n3. Run with: python -m examples.run_groq\n\"\"\"\n\nimport sys\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n AudioAnalysisToolkit,\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n SearchToolkit,\n VideoAnalysisToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\n\nfrom owl.utils import OwlRolePlaying, run_society, DocumentProcessingToolkit\n\nload_dotenv()\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> OwlRolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n OwlRolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.GROQ,\n model_type=ModelType.GROQ_LLAMA_3_1_8B, # Simple role, can use 8B model\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.GROQ,\n model_type=ModelType.GROQ_LLAMA_3_3_70B, # Main assistant needs tool capability\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.GROQ,\n model_type=ModelType.GROQ_LLAMA_3_3_70B, # Web browsing requires tool usage\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.GROQ,\n model_type=ModelType.GROQ_LLAMA_3_3_70B, # Planning requires complex reasoning\n model_config_dict={\"temperature\": 0},\n ),\n \"video\": ModelFactory.create(\n model_platform=ModelPlatformType.GROQ,\n model_type=ModelType.GROQ_LLAMA_3_3_70B, # Video analysis is multimodal\n model_config_dict={\"temperature\": 0},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.GROQ,\n model_type=ModelType.GROQ_LLAMA_3_3_70B, # Image analysis is multimodal\n model_config_dict={\"temperature\": 0},\n ),\n \"document\": ModelFactory.create(\n model_platform=ModelPlatformType.GROQ,\n model_type=ModelType.GROQ_MIXTRAL_8_7B, # Document processing can use Mixtral\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *VideoAnalysisToolkit(model=models[\"video\"]).get_tools(),\n *AudioAnalysisToolkit().get_tools(), # This requires OpenAI Key\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_google, # Comment this out if you don't have google search\n SearchToolkit().search_wiki,\n *ExcelToolkit().get_tools(),\n *DocumentProcessingToolkit(model=models[\"document\"]).get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = OwlRolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Example research question\n default_task = \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\"\n\n # Construct and run the society\n # Note: This configuration uses GROQ_LLAMA_3_3_70B for tool-intensive roles (assistant, web, planning, video, image)\n # and GROQ_MIXTRAL_8_7B for document processing. GROQ_LLAMA_3_1_8B is used only for the user role\n # which doesn't require tool usage capabilities.\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/tools/data_helper.py", "\"\"\"\n数据辅助工具模块\n\"\"\"\nimport pandas as pd\nimport akshare as ak\nfrom datetime import datetime, timedelta\nimport logging\nfrom typing import Dict, Any, List, Optional\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame:\n \"\"\"\n 获取股票历史数据\n \n Args:\n ticker: 股票代码\n start_date: 开始日期 (YYYY-MM-DD)\n end_date: 结束日期 (YYYY-MM-DD)\n \n Returns:\n pd.DataFrame: 股票历史数据\n \"\"\"\n try:\n logger.info(f\"获取股票 {ticker} 的历史数据\")\n \n # 转换日期格式\n start_date_fmt = datetime.strptime(start_date, \"%Y-%m-%d\").strftime(\"%Y%m%d\")\n end_date_fmt = datetime.strptime(end_date, \"%Y-%m-%d\").strftime(\"%Y%m%d\")\n \n # 使用akshare获取A股历史数据\n df = ak.stock_zh_a_hist(\n symbol=ticker,\n period=\"daily\",\n start_date=start_date_fmt,\n end_date=end_date_fmt,\n adjust=\"qfq\" # 前复权\n )\n \n logger.info(f\"成功获取历史数据,共 {len(df)} 条记录\")\n return df\n \n except Exception as e:\n logger.error(f\"获取历史数据时发生错误: {str(e)}\")\n return pd.DataFrame()\n\n\ndef get_fundamental_data(ticker: str) -> Dict[str, Any]:\n \"\"\"\n 获取股票基本面数据\n \n Args:\n ticker: 股票代码\n \n Returns:\n Dict[str, Any]: 基本面数据\n \"\"\"\n try:\n logger.info(f\"获取股票 {ticker} 的基本面数据\")\n \n # 获取财务指标数据\n financial_indicators = ak.stock_financial_analysis_indicator(symbol=ticker)\n \n # 获取利润表数据\n try:\n # 根据akshare文档修正\n # stock参数格式应该为'sh'或'sz'+股票代码,而不是直接使用数字代码\n stock_prefix = 'sz' if ticker.startswith('0') or ticker.startswith('3') else 'sh'\n formatted_ticker = f\"{stock_prefix}{ticker}\"\n # 必须传入symbol参数,设置为\"利润表\"\n income_statement = ak.stock_financial_report_sina(stock=formatted_ticker, symbol=\"利润表\")\n logger.info(f\"成功获取{ticker}的利润表数据\")\n except Exception as e:\n logger.error(f\"获取利润表数据时出错: {str(e)}\")\n income_statement = pd.DataFrame()\n \n # 获取实时行情\n real_time_quote = ak.stock_zh_a_spot_em()\n stock_quote = real_time_quote[real_time_quote['代码'] == ticker]\n \n # 记录实时行情字段名,帮助调试\n if not stock_quote.empty:\n logger.info(f\"实时行情数据字段: {stock_quote.columns.tolist()}\")\n \n # 提取关键财务指标\n latest_indicators = {}\n if not financial_indicators.empty:\n latest_indicators = financial_indicators.iloc[-1].to_dict()\n \n # 提取关键利润表指标\n income_data = {}\n if not income_statement.empty:\n income_data = income_statement.iloc[-1].to_dict()\n \n # 股票基本信息\n stock_info = {}\n if not stock_quote.empty:\n stock_info = stock_quote.iloc[0].to_dict()\n \n logger.info(f\"成功获取基本面数据\")\n \n # 调整处理市场信息,确保字段名正确匹配\n market_summary = {\n \"name\": stock_info.get(\"名称\", \"\"),\n \"pe_ratio\": stock_info.get(\"市盈率-动态\", None), # 调整为实际字段名\n \"pb_ratio\": stock_info.get(\"市净率\", None),\n \"market_cap\": stock_info.get(\"总市值\", None),\n \"industry\": \"\" # 行情数据中没有行业信息\n }\n \n return {\n \"financial_indicators\": latest_indicators,\n \"income_statement\": income_data,\n \"stock_info\": stock_info,\n \"summary\": market_summary\n }\n \n except Exception as e:\n logger.error(f\"获取基本面数据时发生错误: {str(e)}\")\n return {\n \"financial_indicators\": {},\n \"income_statement\": {},\n \"stock_info\": {},\n \"summary\": {\n \"name\": \"\",\n \"pe_ratio\": None,\n \"pb_ratio\": None,\n \"market_cap\": None,\n \"industry\": \"\"\n },\n \"error\": str(e)\n }\n\n\ndef get_stock_news(ticker: str, num_of_news: int = 5) -> List[Dict[str, Any]]:\n \"\"\"\n 获取股票相关新闻\n \n Args:\n ticker: 股票代码\n num_of_news: 获取的新闻数量\n \n Returns:\n List[Dict[str, Any]]: 新闻列表\n \"\"\"\n try:\n logger.info(f\"获取股票 {ticker} 的新闻数据 (共{num_of_news}条)\")\n \n # 获取股票名称\n real_time_quote = ak.stock_zh_a_spot_em()\n stock_quote = real_time_quote[real_time_quote['代码'] == ticker]\n stock_name = stock_quote.iloc[0]['名称'] if not stock_quote.empty else \"\"\n \n if not stock_name:\n logger.warning(f\"无法获取股票 {ticker} 的名称\")\n return []\n \n # 获取财经新闻\n news_df = ak.stock_news_em(symbol=stock_name)\n \n # 记录新闻数据字段名,帮助调试\n if not news_df.empty:\n logger.info(f\"新闻数据字段: {news_df.columns.tolist()}\")\n \n # 筛选最近的新闻\n recent_news = news_df.head(min(num_of_news, len(news_df)))\n \n news_list = []\n for _, row in recent_news.iterrows():\n news_list.append({\n \"title\": row.get(\"新闻标题\", \"\"),\n \"content\": row.get(\"新闻内容\", \"\"),\n \"date\": row.get(\"发布时间\", \"\"),\n \"source\": row.get(\"文章来源\", \"\") # 调整为正确的字段名\n })\n \n logger.info(f\"成功获取 {len(news_list)} 条新闻\")\n return news_list\n \n except Exception as e:\n logger.error(f\"获取新闻数据时发生错误: {str(e)}\")\n return []\n\n\ndef calculate_technical_indicators(df: pd.DataFrame) -> Dict[str, Any]:\n \"\"\"\n 计算技术指标\n \n Args:\n df: 股票历史数据DataFrame\n \n Returns:\n Dict[str, Any]: 技术指标\n \"\"\"\n try:\n logger.info(\"计算技术指标\")\n \n if df.empty:\n logger.warning(\"没有历史数据用于计算技术指标\")\n return {}\n \n # 记录实际的列名,帮助调试\n logger.info(f\"传入DataFrame的列名: {df.columns.tolist()}\")\n \n # 确保列名符合预期\n price_column = None\n volume_column = None\n \n # 逐个检查可能的列名\n for col_name in [\"收盘\", \"close\"]:\n if col_name in df.columns:\n price_column = col_name\n break\n \n for col_name in [\"成交量\", \"volume\"]:\n if col_name in df.columns:\n volume_column = col_name\n break\n \n if not price_column:\n logger.error(\"找不到有效的价格列,当前列名: \" + str(df.columns.tolist()))\n return {\"error\": \"找不到有效的价格列\"}\n \n if not volume_column:\n logger.warning(\"找不到有效的成交量列,将只计算价格相关指标\")\n \n # 提取收盘价和成交量数据\n close_prices = df[price_column].values\n volumes = df[volume_column].values if volume_column else None\n \n # 计算常用技术指标\n indicators = {}\n \n # 1. 移动平均线\n ma_windows = [5, 10, 20, 50, 200]\n for window in ma_windows:\n if len(close_prices) >= window:\n ma = pd.Series(close_prices).rolling(window=window).mean().values\n indicators[f\"ma_{window}\"] = ma.tolist()\n \n # 2. 相对强弱指数 (RSI)\n if len(close_prices) >= 14:\n delta = pd.Series(close_prices).diff()\n gain = delta.clip(lower=0)\n loss = -delta.clip(upper=0)\n avg_gain = gain.rolling(window=14).mean()\n avg_loss = loss.rolling(window=14).mean()\n rs = avg_gain / avg_loss\n rsi = 100 - (100 / (1 + rs))\n indicators[\"rsi\"] = rsi.values.tolist()\n \n # 3. MACD (移动平均收敛/发散)\n if len(close_prices) >= 26:\n exp12 = pd.Series(close_prices).ewm(span=12, adjust=False).mean()\n exp26 = pd.Series(close_prices).ewm(span=26, adjust=False).mean()\n macd = exp12 - exp26\n signal = macd.ewm(span=9, adjust=False).mean()\n indicators[\"macd\"] = macd.values.tolist()\n indicators[\"macd_signal\"] = signal.values.tolist()\n indicators[\"macd_histogram\"] = (macd - signal).values.tolist()\n \n # 4. 布林带\n if len(close_prices) >= 20:\n ma20 = pd.Series(close_prices).rolling(window=20).mean()\n std20 = pd.Series(close_prices).rolling(window=20).std()\n upper_band = ma20 + (std20 * 2)\n lower_band = ma20 - (std20 * 2)\n indicators[\"bollinger_ma\"] = ma20.values.tolist()\n indicators[\"bollinger_upper\"] = upper_band.values.tolist()\n indicators[\"bollinger_lower\"] = lower_band.values.tolist()\n \n logger.info(\"成功计算技术指标\")\n return indicators\n \n except Exception as e:\n logger.error(f\"计算技术指标时发生错误: {str(e)}\")\n return {\"error\": str(e)} "], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/researcher_bear.py", "\"\"\"\n空头研究员代理实现\n\"\"\"\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport pandas as pd\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import AnalysisSignal, StockData, ResearchReport\n\nfrom camel.messages import BaseMessage\n\n\nclass ResearcherBearAgent(BaseAgent):\n \"\"\"空头研究员代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化空头研究员代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"researcher_bear\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"ResearcherBearAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理空头研究报告生成\n \n Args:\n data: 包含以下键的字典:\n - stock_data: 股票数据对象\n - technical_analysis: 技术分析结果\n - fundamentals_analysis: 基本面分析结果\n - sentiment_analysis: 情绪分析结果\n - valuation_analysis: 估值分析结果\n - messages: 处理过程中的消息\n \n Returns:\n Dict[str, Any]: 处理后的数据,包含以下内容:\n - bear_research: 空头研究报告\n - messages: 处理过程中的消息\n \"\"\"\n # 提取股票数据和各类分析结果\n stock_data = data.get(\"stock_data\")\n technical_analysis = data.get(\"technical_analysis\")\n fundamentals_analysis = data.get(\"fundamentals_analysis\")\n sentiment_analysis = data.get(\"sentiment_analysis\")\n valuation_analysis = data.get(\"valuation_analysis\")\n \n if not stock_data:\n raise ValueError(\"缺少股票数据\")\n \n self.logger.info(f\"正在生成空头研究报告\")\n \n try:\n # 提取股票基本信息\n ticker = stock_data.ticker\n \n # 组织各种分析结果\n analysis_data = {\n \"ticker\": ticker,\n \"technical_analysis\": technical_analysis.dict() if technical_analysis else None,\n \"fundamentals_analysis\": fundamentals_analysis.dict() if fundamentals_analysis else None,\n \"sentiment_analysis\": sentiment_analysis.dict() if sentiment_analysis else None,\n \"valuation_analysis\": valuation_analysis.dict() if valuation_analysis else None\n }\n \n # 使用代理处理数据分析请求\n prompt = f\"\"\"请作为持有看空观点的研究员,寻找支持卖出股票 {ticker} 的最有力证据和论据。\n 重点关注以下方面:\n 1. 技术分析中的看跌信号\n 2. 基本面分析中的负面因素\n 3. 市场情绪分析中的悲观迹象\n 4. 估值分析中的高估证据\n 5. 可能被市场忽视的风险因素\n \n 请提供一份全面的看空研究报告,以JSON格式返回:\n {{\n \"key_points\": [\"关键点1\", \"关键点2\", ...],\n \"confidence\": 0.8,\n \"technical_summary\": \"技术分析总结...\",\n \"fundamental_summary\": \"基本面分析总结...\",\n \"sentiment_summary\": \"情绪分析总结...\",\n \"valuation_summary\": \"估值分析总结...\",\n \"reasoning\": \"整体推理过程和看空理由...\"\n }}\n \"\"\"\n \n analysis_result = self._process_data_with_agent(prompt, analysis_data)\n \n # 创建研究报告\n bear_research = self._create_research_report(analysis_result, ticker)\n \n # 返回处理结果\n return {\n \"bear_research\": bear_research,\n \"messages\": []\n }\n \n except Exception as e:\n self.logger.error(f\"生成空头研究报告过程中发生错误: {str(e)}\")\n \n # 返回默认研究报告\n default_report = ResearchReport(\n stance=\"bearish\",\n key_points=[\"数据不足以支持详细分析\"],\n confidence=0.5,\n reasoning=\"处理过程中发生错误,无法生成完整研究报告\"\n )\n \n return {\n \"bear_research\": default_report,\n \"messages\": []\n }\n \n def _create_research_report(self, analysis_result: Dict[str, Any], ticker: str) -> ResearchReport:\n \"\"\"创建研究报告\n \n Args:\n analysis_result: 分析结果\n ticker: 股票代码\n \n Returns:\n ResearchReport: 研究报告\n \"\"\"\n key_points = analysis_result.get(\"key_points\", [\"无关键点\"])\n confidence = analysis_result.get(\"confidence\", 0.5)\n technical_summary = analysis_result.get(\"technical_summary\")\n fundamental_summary = analysis_result.get(\"fundamental_summary\")\n sentiment_summary = analysis_result.get(\"sentiment_summary\")\n valuation_summary = analysis_result.get(\"valuation_summary\")\n reasoning = analysis_result.get(\"reasoning\", \"未提供分析理由\")\n \n return ResearchReport(\n stance=\"bearish\",\n key_points=key_points,\n confidence=confidence,\n technical_summary=technical_summary,\n fundamental_summary=fundamental_summary,\n sentiment_summary=sentiment_summary,\n valuation_summary=valuation_summary,\n reasoning=reasoning\n )\n \n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"使用代理处理数据分析请求\n \n Args:\n prompt: 分析提示\n data: 包含各类分析结果的数据\n \n Returns:\n Dict[str, Any]: 分析结果\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请以JSON格式返回结果。\n\"\"\"\n # 发送到Camel代理进行分析\n human_message = self.generate_human_message(content=full_prompt)\n response = self.agent.step(human_message)\n self.log_message(response.msgs[0])\n \n # 解析结果\n result = self.parse_json_response(response.msgs[0].content)\n \n # 如果解析结果为空,使用默认值\n if not result:\n result = {\n \"key_points\": [\"无法解析分析结果\"],\n \"confidence\": 0.5,\n \"technical_summary\": \"无法获取技术分析总结\",\n \"fundamental_summary\": \"无法获取基本面分析总结\",\n \"sentiment_summary\": \"无法获取情绪分析总结\",\n \"valuation_summary\": \"无法获取估值分析总结\",\n \"reasoning\": \"无法解析空头研究报告\"\n }\n \n return result "], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/researcher_bull.py", "\"\"\"\n多头研究员代理实现\n\"\"\"\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport pandas as pd\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import AnalysisSignal, StockData, ResearchReport\n\nfrom camel.messages import BaseMessage\n\n\nclass ResearcherBullAgent(BaseAgent):\n \"\"\"多头研究员代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化多头研究员代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"researcher_bull\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"ResearcherBullAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理多头研究报告生成\n \n Args:\n data: 包含以下键的字典:\n - stock_data: 股票数据对象\n - technical_analysis: 技术分析结果\n - fundamentals_analysis: 基本面分析结果\n - sentiment_analysis: 情绪分析结果\n - valuation_analysis: 估值分析结果\n - messages: 处理过程中的消息\n \n Returns:\n Dict[str, Any]: 处理后的数据,包含以下内容:\n - bull_research: 多头研究报告\n - messages: 处理过程中的消息\n \"\"\"\n # 提取股票数据和各类分析结果\n stock_data = data.get(\"stock_data\")\n technical_analysis = data.get(\"technical_analysis\")\n fundamentals_analysis = data.get(\"fundamentals_analysis\")\n sentiment_analysis = data.get(\"sentiment_analysis\")\n valuation_analysis = data.get(\"valuation_analysis\")\n \n if not stock_data:\n raise ValueError(\"缺少股票数据\")\n \n self.logger.info(f\"正在生成多头研究报告\")\n \n try:\n # 提取股票基本信息\n ticker = stock_data.ticker\n \n # 组织各种分析结果\n analysis_data = {\n \"ticker\": ticker,\n \"technical_analysis\": technical_analysis.dict() if technical_analysis else None,\n \"fundamentals_analysis\": fundamentals_analysis.dict() if fundamentals_analysis else None,\n \"sentiment_analysis\": sentiment_analysis.dict() if sentiment_analysis else None,\n \"valuation_analysis\": valuation_analysis.dict() if valuation_analysis else None\n }\n \n # 使用代理处理数据分析请求\n prompt = f\"\"\"请作为持有看多观点的研究员,寻找支持买入股票 {ticker} 的最有力证据和论据。\n 重点关注以下方面:\n 1. 技术分析中的看涨信号\n 2. 基本面分析中的积极因素\n 3. 市场情绪分析中的乐观迹象\n 4. 估值分析中的低估证据\n 5. 可能被市场忽视的积极因素\n \n 请提供一份全面的看多研究报告,以JSON格式返回:\n {{\n \"key_points\": [\"关键点1\", \"关键点2\", ...],\n \"confidence\": 0.8,\n \"technical_summary\": \"技术分析总结...\",\n \"fundamental_summary\": \"基本面分析总结...\",\n \"sentiment_summary\": \"情绪分析总结...\",\n \"valuation_summary\": \"估值分析总结...\",\n \"reasoning\": \"整体推理过程和看多理由...\"\n }}\n \"\"\"\n \n analysis_result = self._process_data_with_agent(prompt, analysis_data)\n \n # 创建研究报告\n bull_research = self._create_research_report(analysis_result, ticker)\n \n # 返回处理结果\n return {\n \"bull_research\": bull_research,\n \"messages\": []\n }\n \n except Exception as e:\n self.logger.error(f\"生成多头研究报告过程中发生错误: {str(e)}\")\n \n # 返回默认研究报告\n default_report = ResearchReport(\n stance=\"bullish\",\n key_points=[\"数据不足以支持详细分析\"],\n confidence=0.5,\n reasoning=\"处理过程中发生错误,无法生成完整研究报告\"\n )\n \n return {\n \"bull_research\": default_report,\n \"messages\": []\n }\n \n def _create_research_report(self, analysis_result: Dict[str, Any], ticker: str) -> ResearchReport:\n \"\"\"创建研究报告\n \n Args:\n analysis_result: 分析结果\n ticker: 股票代码\n \n Returns:\n ResearchReport: 研究报告\n \"\"\"\n key_points = analysis_result.get(\"key_points\", [\"无关键点\"])\n confidence = analysis_result.get(\"confidence\", 0.5)\n technical_summary = analysis_result.get(\"technical_summary\")\n fundamental_summary = analysis_result.get(\"fundamental_summary\")\n sentiment_summary = analysis_result.get(\"sentiment_summary\")\n valuation_summary = analysis_result.get(\"valuation_summary\")\n reasoning = analysis_result.get(\"reasoning\", \"未提供分析理由\")\n \n return ResearchReport(\n stance=\"bullish\",\n key_points=key_points,\n confidence=confidence,\n technical_summary=technical_summary,\n fundamental_summary=fundamental_summary,\n sentiment_summary=sentiment_summary,\n valuation_summary=valuation_summary,\n reasoning=reasoning\n )\n \n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"使用代理处理数据分析请求\n \n Args:\n prompt: 分析提示\n data: 包含各类分析结果的数据\n \n Returns:\n Dict[str, Any]: 分析结果\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请以JSON格式返回结果。\n\"\"\"\n # 发送到Camel代理进行分析\n human_message = self.generate_human_message(content=full_prompt)\n response = self.agent.step(human_message)\n self.log_message(response.msgs[0])\n \n # 解析结果\n result = self.parse_json_response(response.msgs[0].content)\n \n # 如果解析结果为空,使用默认值\n if not result:\n result = {\n \"key_points\": [\"无法解析分析结果\"],\n \"confidence\": 0.5,\n \"technical_summary\": \"无法获取技术分析总结\",\n \"fundamental_summary\": \"无法获取基本面分析总结\",\n \"sentiment_summary\": \"无法获取情绪分析总结\",\n \"valuation_summary\": \"无法获取估值分析总结\",\n \"reasoning\": \"无法解析多头研究报告\"\n }\n \n return result "], ["/owl/examples/run_qwen_zh.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\n# To run this file, you need to configure the Qwen API key\n# You can obtain your API key from Bailian platform: bailian.console.aliyun.com\n# Set it as QWEN_API_KEY=\"your-api-key\" in your .env file or add it to your environment variables\n\nimport sys\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n SearchToolkit,\n VideoAnalysisToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.societies import RolePlaying\n\nfrom owl.utils import run_society, DocumentProcessingToolkit\n\nfrom camel.logger import set_log_level\n\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n \"\"\"\n Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_VL_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"video\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_VL_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_VL_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"document\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_VL_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n output_language=\"Chinese\",\n ).get_tools(),\n *VideoAnalysisToolkit(model=models[\"video\"]).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_google, # Comment this out if you don't have google search\n SearchToolkit().search_wiki,\n SearchToolkit().search_baidu,\n *ExcelToolkit().get_tools(),\n *DocumentProcessingToolkit(model=models[\"document\"]).get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n output_language=\"Chinese\",\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Example research question\n default_task = \"浏览亚马逊并找出一款对程序员有吸引力的产品。请提供产品名称和价格\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/valuation_analyst.py", "\"\"\"\n估值分析代理实现\n\"\"\"\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport pandas as pd\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import AnalysisSignal, StockData\n\nfrom camel.messages import BaseMessage\n\n\nclass ValuationAnalystAgent(BaseAgent):\n \"\"\"估值分析代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化估值分析代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"valuation_analyst\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"ValuationAnalystAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理估值分析\n \n Args:\n data: 包含以下键的字典:\n - stock_data: 股票数据对象\n - fundamentals_analysis: 基本面分析结果\n - messages: 处理过程中的消息\n \n Returns:\n Dict[str, Any]: 处理后的数据,包含以下内容:\n - valuation_analysis: 估值分析信号\n - messages: 处理过程中的消息\n \"\"\"\n # 提取股票数据和基本面分析\n stock_data = data.get(\"stock_data\")\n fundamentals_analysis = data.get(\"fundamentals_analysis\")\n \n if not stock_data:\n raise ValueError(\"缺少股票数据\")\n \n self.logger.info(f\"正在进行估值分析\")\n \n try:\n # 提取基本面数据和历史数据\n fundamental_data = stock_data.fundamental_data\n historical_data = stock_data.historical_data\n \n # 使用代理处理数据分析请求\n prompt = f\"\"\"请对以下股票进行估值分析,给出明确的交易信号(bullish/bearish/neutral)。\n 分析以下方面:\n 1. 当前市场估值(如PE、PB、PS等)\n 2. 估值相对于历史水平\n 3. 估值相对于行业平均水平\n 4. 使用不同估值模型(如DCF、相对估值法)\n 5. 内在价值与当前市场价格的比较\n \n 请给出明确的交易信号、置信度(0-1)和详细理由。\n 返回格式为JSON:\n {{\n \"signal\": \"bullish/bearish/neutral\",\n \"confidence\": 0.7,\n \"reasoning\": \"分析理由...\",\n \"fair_value\": 数值,\n \"key_metrics\": [\"指标1\", \"指标2\"]\n }}\n \"\"\"\n \n analysis_data = {\n \"fundamental_data\": fundamental_data,\n \"historical_data\": historical_data\n }\n \n # 如果有基本面分析结果,添加到分析数据中\n if fundamentals_analysis:\n analysis_data[\"fundamentals_analysis\"] = fundamentals_analysis.dict()\n \n analysis_result = self._process_data_with_agent(prompt, analysis_data)\n \n # 创建估值分析信号\n valuation_analysis = self._create_valuation_signal(analysis_result, stock_data)\n \n # 返回处理结果\n return {\n \"valuation_analysis\": valuation_analysis,\n \"messages\": []\n }\n \n except Exception as e:\n self.logger.error(f\"估值分析过程中发生错误: {str(e)}\")\n \n # 返回默认分析结果\n default_signal = AnalysisSignal(\n agent=\"估值分析师\",\n signal=\"neutral\",\n confidence=0.5,\n reasoning=\"分析过程中发生错误,返回中性信号\"\n )\n \n return {\n \"valuation_analysis\": default_signal,\n \"messages\": []\n }\n \n def _create_valuation_signal(self, analysis_result: Dict[str, Any], stock_data: StockData) -> AnalysisSignal:\n \"\"\"创建估值分析信号\n \n Args:\n analysis_result: 分析结果\n stock_data: 股票数据\n \n Returns:\n AnalysisSignal: 分析信号\n \"\"\"\n signal = analysis_result.get(\"signal\", \"neutral\")\n confidence = analysis_result.get(\"confidence\", 0.5)\n reasoning = analysis_result.get(\"reasoning\", \"未提供分析理由\")\n fair_value = analysis_result.get(\"fair_value\", 0)\n key_metrics = analysis_result.get(\"key_metrics\", [])\n \n details = {\n \"ticker\": stock_data.ticker,\n \"fair_value\": fair_value,\n \"key_metrics\": key_metrics,\n }\n \n return AnalysisSignal(\n agent=\"估值分析师\",\n signal=signal,\n confidence=confidence,\n reasoning=reasoning,\n details=details\n )\n \n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"使用代理处理数据分析请求\n \n Args:\n prompt: 分析提示\n data: 包含基本面数据和历史数据的数据\n \n Returns:\n Dict[str, Any]: 分析结果\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请以JSON格式返回结果。\n\"\"\"\n # 发送到Camel代理进行分析\n human_message = self.generate_human_message(content=full_prompt)\n response = self.agent.step(human_message)\n self.log_message(response.msgs[0])\n \n # 解析结果\n result = self.parse_json_response(response.msgs[0].content)\n \n # 如果解析结果为空,使用默认值\n if not result:\n result = {\n \"signal\": \"neutral\",\n \"confidence\": 0.5,\n \"reasoning\": \"无法解析分析结果\",\n \"fair_value\": 0,\n \"key_metrics\": []\n }\n \n return result "], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/sentiment_analyst.py", "\"\"\"\n情绪分析代理实现\n\"\"\"\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport pandas as pd\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import AnalysisSignal, StockData\n\nfrom camel.messages import BaseMessage\n\n\nclass SentimentAnalystAgent(BaseAgent):\n \"\"\"情绪分析代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化情绪分析代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"sentiment_analyst\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"SentimentAnalystAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理情绪分析\n \n Args:\n data: 包含以下键的字典:\n - stock_data: 股票数据对象\n - messages: 处理过程中的消息\n \n Returns:\n Dict[str, Any]: 处理后的数据,包含以下内容:\n - sentiment_analysis: 情绪分析信号\n - messages: 处理过程中的消息\n \"\"\"\n # 提取股票数据\n stock_data = data.get(\"stock_data\")\n \n if not stock_data:\n raise ValueError(\"缺少股票数据\")\n \n self.logger.info(f\"正在进行情绪分析\")\n \n try:\n # 提取股票基本信息和新闻数据\n ticker = stock_data.ticker\n news_data = stock_data.news_data\n \n # 使用代理处理数据分析请求\n prompt = f\"\"\"请对以下与股票相关的新闻和社交媒体数据进行分析,给出明确的市场情绪信号(bullish/bearish/neutral)。\n 分析以下方面:\n 1. 整体市场情绪(积极、中性或消极)\n 2. 重要事件或新闻的影响\n 3. 机构投资者和分析师观点\n 4. 社交媒体讨论的热度和倾向性\n 5. 情绪变化趋势\n \n 请给出明确的交易信号、置信度(0-1)和详细理由。\n 返回格式为JSON:\n {{\n \"signal\": \"bullish/bearish/neutral\",\n \"confidence\": 0.7,\n \"reasoning\": \"分析理由...\",\n \"key_events\": [\"事件1\", \"事件2\"]\n }}\n \"\"\"\n \n analysis_result = self._process_data_with_agent(prompt, {\n \"ticker\": ticker,\n \"news_data\": news_data\n })\n \n # 创建情绪分析信号\n sentiment_analysis = self._create_sentiment_signal(analysis_result, stock_data)\n \n # 返回处理结果\n return {\n \"sentiment_analysis\": sentiment_analysis,\n \"messages\": []\n }\n \n except Exception as e:\n self.logger.error(f\"情绪分析过程中发生错误: {str(e)}\")\n \n # 返回默认分析结果\n default_signal = AnalysisSignal(\n agent=\"情绪分析师\",\n signal=\"neutral\",\n confidence=0.5,\n reasoning=\"分析过程中发生错误,返回中性信号\"\n )\n \n return {\n \"sentiment_analysis\": default_signal,\n \"messages\": []\n }\n \n def _create_sentiment_signal(self, analysis_result: Dict[str, Any], stock_data: StockData) -> AnalysisSignal:\n \"\"\"创建情绪分析信号\n \n Args:\n analysis_result: 分析结果\n stock_data: 股票数据\n \n Returns:\n AnalysisSignal: 分析信号\n \"\"\"\n signal = analysis_result.get(\"signal\", \"neutral\")\n confidence = analysis_result.get(\"confidence\", 0.5)\n reasoning = analysis_result.get(\"reasoning\", \"未提供分析理由\")\n key_events = analysis_result.get(\"key_events\", [])\n \n details = {\n \"ticker\": stock_data.ticker,\n \"key_events\": key_events,\n }\n \n return AnalysisSignal(\n agent=\"情绪分析师\",\n signal=signal,\n confidence=confidence,\n reasoning=reasoning,\n details=details\n )\n \n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"使用代理处理数据分析请求\n \n Args:\n prompt: 分析提示\n data: 包含新闻数据的字典\n \n Returns:\n Dict[str, Any]: 分析结果\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请以JSON格式返回结果。\n\"\"\"\n # 发送到Camel代理进行分析\n human_message = self.generate_human_message(content=full_prompt)\n response = self.agent.step(human_message)\n self.log_message(response.msgs[0])\n \n # 解析结果\n result = self.parse_json_response(response.msgs[0].content)\n \n # 如果解析结果为空,使用默认值\n if not result:\n result = {\n \"signal\": \"neutral\",\n \"confidence\": 0.5,\n \"reasoning\": \"无法解析分析结果\",\n \"key_events\": []\n }\n \n return result "], ["/owl/examples/run_openai_compatible_model.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport os\nimport sys\n\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n SearchToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType\n\nfrom owl.utils import run_society\nfrom camel.societies import RolePlaying\nfrom camel.logger import set_log_level\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"qwen-max\",\n api_key=os.getenv(\"QWEN_API_KEY\"),\n url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n model_config_dict={\"temperature\": 0.4, \"max_tokens\": 128000},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"qwen-max\",\n api_key=os.getenv(\"QWEN_API_KEY\"),\n url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n model_config_dict={\"temperature\": 0.4, \"max_tokens\": 128000},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"qwen-vl-max\",\n api_key=os.getenv(\"QWEN_API_KEY\"),\n url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n model_config_dict={\"temperature\": 0.4, \"max_tokens\": 128000},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"qwen-max\",\n api_key=os.getenv(\"QWEN_API_KEY\"),\n url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n model_config_dict={\"temperature\": 0.4, \"max_tokens\": 128000},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"qwen-vl-max\",\n api_key=os.getenv(\"QWEN_API_KEY\"),\n url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n model_config_dict={\"temperature\": 0.4, \"max_tokens\": 128000},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_google, # Comment this out if you don't have google search\n SearchToolkit().search_wiki,\n *ExcelToolkit().get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Example research question\n default_task = \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/technical_analyst.py", "\"\"\"\n技术分析代理实现\n\"\"\"\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport json\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import StockData, AnalysisSignal\n\nfrom camel.messages import BaseMessage\n\n\nclass TechnicalAnalystAgent(BaseAgent):\n \"\"\"技术分析代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化技术分析代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"technical_analyst\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"TechnicalAnalystAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理技术分析\n \n Args:\n data: 包含以下键的字典:\n - stock_data: 股票数据对象\n - messages: 处理过程中的消息\n \n Returns:\n Dict[str, Any]: 处理后的数据,包含以下内容:\n - technical_analysis: 技术分析信号\n - messages: 处理过程中的消息\n \"\"\"\n # 提取股票数据\n stock_data = data.get(\"stock_data\")\n if not stock_data:\n raise ValueError(\"缺少股票数据\")\n \n self.logger.info(f\"正在进行技术分析\")\n \n try:\n # 提取技术指标\n technical_indicators = stock_data.technical_indicators\n historical_data = stock_data.historical_data\n \n # 使用代理处理数据分析请求\n prompt = f\"\"\"请对以下股票的技术指标进行分析,给出明确的交易信号(bullish/bearish/neutral)。\n 分析以下方面:\n 1. 趋势指标 (移动平均线, MACD等)\n 2. 动量指标 (RSI, 随机指标等)\n 3. 波动性指标 (布林带, ATR等)\n 4. 量价关系\n 5. 支撑位和阻力位\n \n 请给出明确的交易信号、置信度(0-1)和详细理由。\n 返回格式为JSON:\n {{\n \"signal\": \"bullish/bearish/neutral\",\n \"confidence\": 0.7,\n \"reasoning\": \"分析理由...\",\n \"key_indicators\": [\"指标1\", \"指标2\"]\n }}\n \"\"\"\n \n analysis_result = self._process_data_with_agent(prompt, {\n \"technical_indicators\": technical_indicators,\n \"historical_data\": historical_data\n })\n \n # 创建技术分析信号\n technical_analysis = self._create_technical_signal(analysis_result, stock_data)\n \n # 返回处理结果\n return {\n \"technical_analysis\": technical_analysis,\n \"messages\": []\n }\n \n except Exception as e:\n self.logger.error(f\"技术分析过程中发生错误: {str(e)}\")\n \n # 返回默认分析结果\n default_signal = AnalysisSignal(\n agent=\"技术分析师\",\n signal=\"neutral\",\n confidence=0.5,\n reasoning=\"分析过程中发生错误,返回中性信号\"\n )\n \n return {\n \"technical_analysis\": default_signal,\n \"messages\": []\n }\n \n def _prepare_analysis_prompt(self, stock_data: StockData) -> str:\n \"\"\"准备技术分析提示\n \n Args:\n stock_data: 股票数据对象\n \n Returns:\n str: 技术分析提示\n \"\"\"\n # 提取技术指标\n technical_indicators = stock_data.technical_indicators\n historical_data = stock_data.historical_data\n \n # 构建提示\n prompt = f\"\"\"请对以下股票的技术指标进行分析,给出明确的交易信号(bullish/bearish/neutral)。\n 分析以下方面:\n 1. 趋势指标 (移动平均线, MACD等)\n 2. 动量指标 (RSI, 随机指标等)\n 3. 波动性指标 (布林带, ATR等)\n 4. 量价关系\n 5. 支撑位和阻力位\n \n 请给出明确的交易信号、置信度(0-1)和详细理由。\n 返回格式为JSON:\n {{\n \"signal\": \"bullish/bearish/neutral\",\n \"confidence\": 0.7,\n \"reasoning\": \"分析理由...\",\n \"key_indicators\": [\"指标1\", \"指标2\"]\n }}\n \"\"\"\n return prompt\n \n def _create_technical_signal(self, result: Dict[str, Any], stock_data: StockData) -> AnalysisSignal:\n \"\"\"创建技术分析信号\n \n Args:\n result: 分析结果\n stock_data: 股票数据对象\n \n Returns:\n AnalysisSignal: 技术分析信号\n \"\"\"\n signal = result.get(\"signal\", \"neutral\")\n confidence = result.get(\"confidence\", 0.5)\n reasoning = result.get(\"reasoning\", \"\")\n key_indicators = result.get(\"key_indicators\", [])\n \n return AnalysisSignal(\n agent=\"Technical Analysis\",\n signal=signal,\n confidence=confidence,\n reasoning=reasoning,\n details={\n \"key_indicators\": key_indicators\n }\n )\n \n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"使用代理处理数据分析请求\n \n Args:\n prompt: 分析提示\n data: 包含技术指标和历史数据的数据\n \n Returns:\n Dict[str, Any]: 分析结果\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请以JSON格式返回结果。\n\"\"\"\n # 发送到Camel代理进行分析\n human_message = self.generate_human_message(content=full_prompt)\n response = self.agent.step(human_message)\n self.log_message(response.msgs[0])\n \n # 解析结果\n result = self.parse_json_response(response.msgs[0].content)\n \n # 如果解析结果为空,使用默认值\n if not result:\n result = {\n \"signal\": \"neutral\",\n \"confidence\": 0.5,\n \"reasoning\": \"无法解析分析结果\",\n \"key_indicators\": []\n }\n \n return result "], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/fundamentals_analyst.py", "\"\"\"\n基本面分析代理实现\n\"\"\"\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport pandas as pd\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import AnalysisSignal, StockData\n\nfrom camel.messages import BaseMessage\n\n\nclass FundamentalsAnalystAgent(BaseAgent):\n \"\"\"基本面分析代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化基本面分析代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"fundamentals_analyst\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"FundamentalsAnalystAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理基本面分析\n \n Args:\n data: 包含以下键的字典:\n - stock_data: 股票数据对象\n - messages: 处理过程中的消息\n \n Returns:\n Dict[str, Any]: 处理后的数据,包含以下内容:\n - fundamentals_analysis: 基本面分析信号\n - messages: 处理过程中的消息\n \"\"\"\n # 提取股票数据\n stock_data = data.get(\"stock_data\")\n if not stock_data:\n raise ValueError(\"缺少股票数据\")\n \n self.logger.info(f\"正在进行基本面分析\")\n \n try:\n # 提取基本面数据和历史数据\n fundamental_data = stock_data.fundamental_data\n historical_data = stock_data.historical_data\n \n # 使用代理处理数据分析请求\n prompt = f\"\"\"请对以下股票的基本面数据进行分析,给出明确的交易信号(bullish/bearish/neutral)。\n 分析以下方面:\n 1. 财务指标评估(净利润、毛利率、ROE等)\n 2. 收入和盈利增长趋势\n 3. 估值水平(市盈率、市净率等)\n 4. 财务健康状况(资产负债率、流动性等)\n 5. 行业地位与竞争优势\n \n 请给出明确的交易信号、置信度(0-1)和详细理由。\n 返回格式为JSON:\n {{\n \"signal\": \"bullish/bearish/neutral\",\n \"confidence\": 0.7,\n \"reasoning\": \"分析理由...\",\n \"key_financials\": [\"指标1\", \"指标2\"]\n }}\n \"\"\"\n \n analysis_result = self._process_data_with_agent(prompt, {\n \"fundamental_data\": fundamental_data,\n \"historical_data\": historical_data\n })\n \n # 创建基本面分析信号\n fundamentals_analysis = self._create_fundamentals_signal(analysis_result, stock_data)\n \n # 返回处理结果\n return {\n \"fundamentals_analysis\": fundamentals_analysis,\n \"messages\": []\n }\n \n except Exception as e:\n self.logger.error(f\"基本面分析过程中发生错误: {str(e)}\")\n \n # 返回默认分析结果\n default_signal = AnalysisSignal(\n agent=\"基本面分析师\",\n signal=\"neutral\",\n confidence=0.5,\n reasoning=\"分析过程中发生错误,返回中性信号\"\n )\n \n return {\n \"fundamentals_analysis\": default_signal,\n \"messages\": []\n }\n \n def _create_fundamentals_signal(self, analysis_result: Dict[str, Any], stock_data: StockData) -> AnalysisSignal:\n \"\"\"创建基本面分析信号\n \n Args:\n analysis_result: 分析结果\n stock_data: 股票数据\n \n Returns:\n AnalysisSignal: 分析信号\n \"\"\"\n signal = analysis_result.get(\"signal\", \"neutral\")\n confidence = analysis_result.get(\"confidence\", 0.5)\n reasoning = analysis_result.get(\"reasoning\", \"未提供分析理由\")\n key_financials = analysis_result.get(\"key_financials\", [])\n \n details = {\n \"ticker\": stock_data.ticker,\n \"key_financials\": key_financials,\n }\n \n return AnalysisSignal(\n agent=\"基本面分析师\",\n signal=signal,\n confidence=confidence,\n reasoning=reasoning,\n details=details\n )\n \n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"使用代理处理数据分析请求\n \n Args:\n prompt: 分析提示\n data: 包含基本面数据和历史数据的数据\n \n Returns:\n Dict[str, Any]: 分析结果\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请以JSON格式返回结果。\n\"\"\"\n # 发送到Camel代理进行分析\n human_message = self.generate_human_message(content=full_prompt)\n response = self.agent.step(human_message)\n self.log_message(response.msgs[0])\n \n # 解析结果\n result = self.parse_json_response(response.msgs[0].content)\n \n # 如果解析结果为空,使用默认值\n if not result:\n result = {\n \"signal\": \"neutral\",\n \"confidence\": 0.5,\n \"reasoning\": \"无法解析分析结果\",\n \"key_financials\": []\n }\n \n return result "], ["/owl/examples/run_qwen_mini_zh.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\n# To run this file, you need to configure the Qwen API key\n# You can obtain your API key from Bailian platform: bailian.console.aliyun.com\n# Set it as QWEN_API_KEY=\"your-api-key\" in your .env file or add it to your environment variables\n\nimport sys\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n SearchToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.societies import RolePlaying\n\nfrom owl.utils import run_society\n\nfrom camel.logger import set_log_level\n\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n \"\"\"\n Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_VL_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"video\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_VL_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_VL_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"document\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_VL_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n output_language=\"Chinese\",\n ).get_tools(),\n SearchToolkit().search_baidu,\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n output_language=\"Chinese\",\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Example research question\n default_task = \"浏览亚马逊并找出一款对程序员有吸引力的产品。请提供产品名称和价格\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/resume-analysis-assistant/run_mcp.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport asyncio\nimport sys\nfrom pathlib import Path\nfrom typing import List\n\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import FunctionTool\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.toolkits import MCPToolkit\n\nfrom owl.utils.enhanced_role_playing import OwlRolePlaying, arun_society\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n# AI/ML Engineer Job Description\nAI_ENGINEER_JOB_DESCRIPTION = \"\"\"\n# AI/ML Engineer Job Description\n\n## About the Role\nWe are seeking a skilled AI/ML Engineer to join our team. The ideal candidate will design, develop, and deploy machine learning models and AI systems that solve complex business problems. You will work closely with cross-functional teams to understand requirements, implement solutions, and continuously improve our AI capabilities.\n\n## Key Responsibilities\n- Design, develop, and implement machine learning models and algorithms\n- Build and maintain scalable ML pipelines for data processing, model training, and inference\n- Collaborate with product teams to understand requirements and translate them into technical solutions\n- Optimize existing models for performance, accuracy, and efficiency\n- Stay current with the latest AI/ML research and technologies\n- Implement and deploy models to production environments\n- Monitor and troubleshoot deployed models\n\n## Required Qualifications\n- Bachelor's or Master's degree in Computer Science, AI, Machine Learning, or related field\n- 3+ years of experience in machine learning or AI development\n- Strong programming skills in Python and familiarity with ML frameworks (TensorFlow, PyTorch, etc.)\n- Experience with deep learning architectures (CNNs, RNNs, Transformers)\n- Knowledge of NLP, computer vision, or other specialized AI domains\n- Experience with cloud platforms (AWS, GCP, Azure) and MLOps tools\n- Strong problem-solving skills and attention to detail\n- Excellent communication and collaboration abilities\n\n## Preferred Qualifications\n- PhD in Machine Learning, AI, or related field\n- Experience with large language models (LLMs) and generative AI\n- Contributions to open-source ML/AI projects\n- Experience with distributed computing and big data technologies\n- Published research in AI/ML conferences or journals\n- Experience with model optimization techniques (quantization, pruning, distillation)\n\"\"\"\n\nasync def construct_society(\n resume_dir: str,\n tools: List[FunctionTool],\n) -> OwlRolePlaying:\n r\"\"\"build a multi-agent OwlRolePlaying instance.\n\n Args:\n question (str): The question to ask.\n tools (List[FunctionTool]): The MCP tools to use.\n \"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.QWEN,\n model_type=ModelType.QWEN_MAX,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\n \"model\": models[\"assistant\"],\n \"tools\": tools,\n }\n\n task_prompt = f\"\"\"\n You are a professional resume analyzer for AI/ML Engineer positions. Your task is to:\n\n 1. Analyze all resume files in the directory: {resume_dir}\n 2. Please note when you retrieve the content of PDF files using the `pdf-reader` tool, the path is mapping to the `/pdfs` directory inside the pdf-reader docker container.\n 3. For each resume, evaluate how well the candidate matches the following job description:\n\n {AI_ENGINEER_JOB_DESCRIPTION}\n\n 4. Score each resume on a scale of 1-100 based on:\n - Technical skills match (40%)\n - Experience relevance (30%)\n - Education and qualifications (20%)\n - Communication and presentation (10%)\n\n 5. Rank all candidates from most to least qualified\n 6. For each candidate, highlight their strengths and areas for improvement\n 7. Output your analysis to a markdown file named './resume_analysis.md' with the following sections:\n - Executive Summary\n - Individual Candidate Assessments (with scores)\n - Ranked List of Candidates\n - Recommendations for Hiring Manager\n\n Be thorough, fair, and objective in your assessment.\n Always execute the MCP tools, don't ask me for confirmation.\n \"\"\"\n\n society = OwlRolePlaying(\n task_prompt=task_prompt,\n with_task_specify=False,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n return society\n\n\nasync def main():\n config_path = Path(__file__).parent / \"mcp_servers_config.json\"\n mcp_toolkit = MCPToolkit(config_path=str(config_path))\n\n try:\n await mcp_toolkit.connect()\n\n # Default resume directory if none provided\n default_resume_dir = \"./resumes/\"\n \n # Get resume directory from command line argument if provided\n resume_dir = sys.argv[1] if len(sys.argv) > 1 else default_resume_dir\n \n print(f\"\\033[94mAnalyzing resumes for AI/ML Engineer position...\\033[0m\")\n\n # Connect to all MCP toolkits\n tools = [*mcp_toolkit.get_tools()]\n society = await construct_society(resume_dir, tools)\n answer, chat_history, token_count = await arun_society(society)\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n print(f\"\\033[94mCompleted! Resume analysis has been saved to ./resume_analysis.md file\\033[0m\")\n\n finally:\n # Make sure to disconnect safely after all operations are completed.\n try:\n await mcp_toolkit.disconnect()\n except Exception:\n print(\"Disconnect failed\")\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/base_agent.py", "\"\"\"\n代理基类模块\n\n定义所有代理的共同基类和接口\n\"\"\"\nfrom typing import Dict, Any, Optional, List\nfrom abc import ABC, abstractmethod\nimport json\nimport logging\nimport re\nfrom camel.agents import ChatAgent\nfrom camel.messages import BaseMessage\n\n# 配置日志\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n handlers=[\n logging.FileHandler(\"logs/agents.log\"),\n logging.StreamHandler()\n ]\n)\n\n\nclass BaseAgent(ABC):\n \"\"\"代理基类\"\"\"\n \n def __init__(self, role_agent: ChatAgent, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化代理\n \n Args:\n role_agent: Camel框架的聊天代理\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n self.agent = role_agent\n self.show_reasoning = show_reasoning\n self.model_name = model_name\n self.logger = logging.getLogger(self.__class__.__name__)\n \n def log_message(self, message: BaseMessage) -> None:\n \"\"\"记录消息\n \n Args:\n message: 要记录的消息\n \"\"\"\n if self.show_reasoning:\n print(f\"\\n{'='*80}\")\n print(f\"【{self.__class__.__name__}】推理过程:\")\n print(f\"{'-'*80}\")\n print(message.content)\n print(f\"{'='*80}\\n\")\n \n # 记录到日志\n self.logger.info(f\"推理过程: {message.content[:100]}...\")\n \n def format_data(self, data: Dict[str, Any]) -> str:\n \"\"\"格式化数据为字符串\n \n Args:\n data: 要格式化的数据\n \n Returns:\n str: 格式化后的字符串\n \"\"\"\n return json.dumps(data, ensure_ascii=False, indent=2)\n \n def parse_json_response(self, response: str) -> Dict[str, Any]:\n \"\"\"从响应中解析JSON\n \n 尝试从响应文本中提取JSON数据,处理各种边缘情况\n \n Args:\n response: 响应文本\n \n Returns:\n Dict[str, Any]: 解析后的JSON数据\n \"\"\"\n try:\n # 尝试直接解析\n return json.loads(response)\n except json.JSONDecodeError:\n pass\n \n # 尝试从Markdown代码块中提取JSON\n json_pattern = r\"```(?:json)?\\s*([\\s\\S]*?)\\s*```\"\n matches = re.findall(json_pattern, response)\n \n if matches:\n for match in matches:\n try:\n return json.loads(match)\n except json.JSONDecodeError:\n continue\n \n # 尝试找到大括号包裹的内容\n brace_pattern = r\"\\{[\\s\\S]*\\}\"\n matches = re.findall(brace_pattern, response)\n \n if matches:\n for match in matches:\n try:\n return json.loads(match)\n except json.JSONDecodeError:\n continue\n \n # 如果所有尝试都失败,返回空字典并记录错误\n self.logger.error(f\"无法从响应中解析JSON: {response}\")\n return {}\n \n @abstractmethod\n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理输入数据并返回结果\n \n Args:\n data: 输入数据\n \n Returns:\n Dict[str, Any]: 处理结果\n \"\"\"\n pass \n\n def generate_human_message(self, content: str) -> BaseMessage:\n \"\"\"生成人类消息\n \n Args:\n content: 消息内容\n \n Returns:\n BaseMessage: 用户消息对象\n \"\"\"\n return BaseMessage.make_user_message(role_name=\"user\", content=content)\n \n def generate_ai_message(self, content: str) -> BaseMessage:\n \"\"\"生成AI消息\n \n Args:\n content: 消息内容\n \n Returns:\n BaseMessage: 助手消息对象\n \"\"\"\n return BaseMessage.make_assistant_message(role_name=\"assistant\", content=content) "], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/debate_room.py", "\"\"\"\n辩论室代理实现\n\"\"\"\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport pandas as pd\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import AnalysisSignal, StockData, ResearchReport\n\nfrom camel.messages import BaseMessage\n\n\nclass DebateRoomAgent(BaseAgent):\n \"\"\"辩论室代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化辩论室代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"debate_room\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"DebateRoomAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理多空观点辩论\n \n Args:\n data: 包含以下键的字典:\n - stock_data: 股票数据对象\n - bull_research: 多头研究报告\n - bear_research: 空头研究报告\n - messages: 处理过程中的消息\n \n Returns:\n Dict[str, Any]: 处理后的数据,包含以下内容:\n - debate_result: 辩论结果信号\n - messages: 处理过程中的消息\n \"\"\"\n # 提取股票数据和研究报告\n stock_data = data.get(\"stock_data\")\n bull_research = data.get(\"bull_research\")\n bear_research = data.get(\"bear_research\")\n \n if not stock_data:\n raise ValueError(\"缺少股票数据\")\n \n if not bull_research or not bear_research:\n raise ValueError(\"缺少多头或空头研究报告\")\n \n self.logger.info(f\"正在召开辩论会议\")\n \n try:\n # 提取股票基本信息\n ticker = stock_data.ticker\n \n # 组织研究报告数据\n debate_data = {\n \"ticker\": ticker,\n \"bull_research\": bull_research.dict(),\n \"bear_research\": bear_research.dict(),\n }\n \n # 使用代理处理数据分析请求\n prompt = f\"\"\"请作为辩论室主持人,整合多头和空头研究员对股票 {ticker} 的观点,形成一个平衡的投资视角。\n 任务要求:\n 1. 公正评估多头和空头论据的优点和弱点\n 2. 识别最具说服力的论点\n 3. 权衡不同因素的重要性\n 4. 形成综合性的市场观点\n 5. 提出平衡的投资建议\n \n 请给出明确的交易信号、置信度和详细理由。\n 返回格式为JSON:\n {{\n \"signal\": \"bullish/bearish/neutral\",\n \"confidence\": 0.7,\n \"reasoning\": \"辩论总结和推理...\",\n \"bull_key_strengths\": [\"优势1\", \"优势2\"],\n \"bull_key_weaknesses\": [\"弱点1\", \"弱点2\"],\n \"bear_key_strengths\": [\"优势1\", \"优势2\"],\n \"bear_key_weaknesses\": [\"弱点1\", \"弱点2\"],\n \"final_verdict\": \"最终投资建议...\"\n }}\n \"\"\"\n \n analysis_result = self._process_data_with_agent(prompt, debate_data)\n \n # 创建辩论结果信号\n debate_result = self._create_debate_signal(analysis_result, ticker)\n \n # 返回处理结果\n return {\n \"debate_result\": debate_result,\n \"messages\": []\n }\n \n except Exception as e:\n self.logger.error(f\"辩论过程中发生错误: {str(e)}\")\n \n # 返回默认辩论结果\n default_signal = AnalysisSignal(\n agent=\"辩论室\",\n signal=\"neutral\",\n confidence=0.5,\n reasoning=\"辩论过程中发生错误,返回中性信号\"\n )\n \n return {\n \"debate_result\": default_signal,\n \"messages\": []\n }\n \n def _create_debate_signal(self, analysis_result: Dict[str, Any], ticker: str) -> AnalysisSignal:\n \"\"\"创建辩论结果信号\n \n Args:\n analysis_result: 分析结果\n ticker: 股票代码\n \n Returns:\n AnalysisSignal: 分析信号\n \"\"\"\n signal = analysis_result.get(\"signal\", \"neutral\")\n confidence = analysis_result.get(\"confidence\", 0.5)\n reasoning = analysis_result.get(\"reasoning\", \"未提供分析理由\")\n final_verdict = analysis_result.get(\"final_verdict\", \"\")\n \n # 整合多空优缺点\n bull_strengths = analysis_result.get(\"bull_key_strengths\", [])\n bull_weaknesses = analysis_result.get(\"bull_key_weaknesses\", [])\n bear_strengths = analysis_result.get(\"bear_key_strengths\", [])\n bear_weaknesses = analysis_result.get(\"bear_key_weaknesses\", [])\n \n details = {\n \"ticker\": ticker,\n \"bull_strengths\": bull_strengths,\n \"bull_weaknesses\": bull_weaknesses,\n \"bear_strengths\": bear_strengths,\n \"bear_weaknesses\": bear_weaknesses,\n \"final_verdict\": final_verdict\n }\n \n return AnalysisSignal(\n agent=\"辩论室\",\n signal=signal,\n confidence=confidence,\n reasoning=reasoning,\n details=details\n )\n \n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"使用代理处理数据分析请求\n \n Args:\n prompt: 分析提示\n data: 包含多空研究报告的数据\n \n Returns:\n Dict[str, Any]: 分析结果\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请以JSON格式返回结果。\n\"\"\"\n # 发送到Camel代理进行分析\n human_message = self.generate_human_message(content=full_prompt)\n response = self.agent.step(human_message)\n self.log_message(response.msgs[0])\n \n # 解析结果\n result = self.parse_json_response(response.msgs[0].content)\n \n # 如果解析结果为空,使用默认值\n if not result:\n result = {\n \"signal\": \"neutral\",\n \"confidence\": 0.5,\n \"reasoning\": \"无法解析辩论结果\",\n \"bull_key_strengths\": [],\n \"bull_key_weaknesses\": [],\n \"bear_key_strengths\": [],\n \"bear_key_weaknesses\": [],\n \"final_verdict\": \"由于分析错误,无法给出最终判断\"\n }\n \n return result "], ["/owl/examples/run_ollama.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# run_ollama.py by tj-scripts(https://github.com/tj-scripts)\n\nimport sys\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n SearchToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType\n\nfrom owl.utils import run_society\n\nfrom camel.societies import RolePlaying\n\nfrom camel.logger import set_log_level\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OLLAMA,\n model_type=\"qwen2.5:72b\",\n url=\"http://localhost:11434/v1\",\n model_config_dict={\"temperature\": 0.8, \"max_tokens\": 1000000},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OLLAMA,\n model_type=\"qwen2.5:72b\",\n url=\"http://localhost:11434/v1\",\n model_config_dict={\"temperature\": 0.2, \"max_tokens\": 1000000},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.OLLAMA,\n model_type=\"llava:latest\",\n url=\"http://localhost:11434/v1\",\n model_config_dict={\"temperature\": 0.4, \"max_tokens\": 1000000},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.OLLAMA,\n model_type=\"qwen2.5:72b\",\n url=\"http://localhost:11434/v1\",\n model_config_dict={\"temperature\": 0.4, \"max_tokens\": 1000000},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.OLLAMA,\n model_type=\"llava:latest\",\n url=\"http://localhost:11434/v1\",\n model_config_dict={\"temperature\": 0.4, \"max_tokens\": 1000000},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n SearchToolkit().search_duckduckgo,\n # SearchToolkit().search_google, # Comment this out if you don't have google search\n SearchToolkit().search_wiki,\n *ExcelToolkit().get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Default research question\n default_task = \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/risk_manager.py", "\"\"\"\n风险管理代理实现\n\"\"\"\nimport logging\nfrom typing import Dict, Any, List, Optional\nimport pandas as pd\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.roles import create_role_agent\nfrom src.models import RiskAnalysis, StockData, Portfolio\n\nfrom camel.messages import BaseMessage\n\n\nclass RiskManagerAgent(BaseAgent):\n \"\"\"风险管理代理类\"\"\"\n \n def __init__(self, show_reasoning: bool = False, model_name: str = \"gemini\"):\n \"\"\"初始化风险管理代理\n \n Args:\n show_reasoning: 是否显示推理过程\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n role_agent = create_role_agent(\"risk_manager\", model_name)\n super().__init__(role_agent, show_reasoning, model_name)\n self.logger = logging.getLogger(\"RiskManagerAgent\")\n \n def process(self, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"处理风险评估\n \n Args:\n data: 包含以下键的字典:\n - stock_data: 股票数据对象\n - debate_result: 辩论结果\n - portfolio: 投资组合信息\n - messages: 处理过程中的消息\n \n Returns:\n Dict[str, Any]: 处理后的数据,包含以下内容:\n - risk_analysis: 风险分析结果\n - messages: 处理过程中的消息\n \"\"\"\n # 提取股票数据和辩论结果\n stock_data = data.get(\"stock_data\")\n debate_result = data.get(\"debate_result\")\n portfolio = data.get(\"portfolio\")\n \n if not stock_data:\n raise ValueError(\"缺少股票数据\")\n \n if not portfolio:\n portfolio = {\"cash\": 100000.0, \"stock\": 0}\n \n self.logger.info(f\"正在进行风险评估\")\n \n try:\n # 提取股票基本信息和历史数据\n ticker = stock_data.ticker\n historical_data = stock_data.historical_data\n \n # 组织风险评估数据\n risk_data = {\n \"ticker\": ticker,\n \"historical_data\": historical_data,\n \"debate_result\": debate_result.dict() if debate_result else None,\n \"portfolio\": portfolio\n }\n \n # 使用代理处理数据分析请求\n prompt = f\"\"\"请作为风险管理经理,评估投资股票 {ticker} 的风险水平,并提供风险管理建议。\n 分析以下方面:\n 1. 投资组合风险指标(波动率、最大回撤等)\n 2. 市场和特定股票的风险水平\n 3. 适当的持仓限制\n 4. 止损水平建议\n 5. 风险分散策略\n \n 请根据分析提供详细的风险管理建议。\n 返回格式为JSON:\n {{\n \"max_position_size\": 0.2, // 建议最大持仓比例\n \"volatility\": 0.15, // 预估股票波动率\n \"risk_score\": 0.7, // 0-1之间的风险分数\n \"max_drawdown\": 0.25, // 预估最大回撤\n \"suggested_position_size\": 0.15, // 建议持仓比例\n \"reasoning\": \"风险评估理由...\"\n }}\n \"\"\"\n \n analysis_result = self._process_data_with_agent(prompt, risk_data)\n \n # 创建风险分析结果\n risk_analysis = self._create_risk_analysis(analysis_result)\n \n # 返回处理结果\n return {\n \"risk_analysis\": risk_analysis,\n \"messages\": []\n }\n \n except Exception as e:\n self.logger.error(f\"风险评估过程中发生错误: {str(e)}\")\n \n # 返回默认风险分析\n default_analysis = RiskAnalysis(\n max_position_size=0.1,\n volatility=0.2,\n risk_score=0.5,\n max_drawdown=0.2,\n suggested_position_size=0.05,\n reasoning=\"风险评估过程中发生错误,使用保守默认值\"\n )\n \n return {\n \"risk_analysis\": default_analysis,\n \"messages\": []\n }\n \n def _create_risk_analysis(self, analysis_result: Dict[str, Any]) -> RiskAnalysis:\n \"\"\"创建风险分析结果\n \n Args:\n analysis_result: 分析结果\n \n Returns:\n RiskAnalysis: 风险分析结果\n \"\"\"\n max_position_size = analysis_result.get(\"max_position_size\", 0.1)\n volatility = analysis_result.get(\"volatility\", 0.2)\n risk_score = analysis_result.get(\"risk_score\", 0.5)\n max_drawdown = analysis_result.get(\"max_drawdown\", 0.2)\n suggested_position_size = analysis_result.get(\"suggested_position_size\", 0.05)\n reasoning = analysis_result.get(\"reasoning\", \"未提供风险评估理由\")\n \n return RiskAnalysis(\n max_position_size=max_position_size,\n volatility=volatility,\n risk_score=risk_score,\n max_drawdown=max_drawdown,\n suggested_position_size=suggested_position_size,\n reasoning=reasoning\n )\n \n def _process_data_with_agent(self, prompt: str, data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"使用代理处理数据分析请求\n \n Args:\n prompt: 分析提示\n data: 包含风险评估相关数据\n \n Returns:\n Dict[str, Any]: 分析结果\n \"\"\"\n # 格式化数据\n data_str = self.format_data(data)\n \n # 创建完整提示\n full_prompt = f\"\"\"{prompt}\n\n数据:\n{data_str}\n\n请以JSON格式返回结果。\n\"\"\"\n # 发送到Camel代理进行分析\n human_message = self.generate_human_message(content=full_prompt)\n response = self.agent.step(human_message)\n self.log_message(response.msgs[0])\n \n # 解析结果\n result = self.parse_json_response(response.msgs[0].content)\n \n # 如果解析结果为空,使用默认值\n if not result:\n result = {\n \"max_position_size\": 0.1,\n \"volatility\": 0.2,\n \"risk_score\": 0.5,\n \"max_drawdown\": 0.2,\n \"suggested_position_size\": 0.05,\n \"reasoning\": \"无法解析风险分析结果,使用保守默认值\"\n }\n \n return result "], ["/owl/examples/run_cli.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n ExcelToolkit,\n SearchToolkit,\n FileWriteToolkit,\n CodeExecutionToolkit,\n BrowserToolkit,\n VideoAnalysisToolkit,\n ImageAnalysisToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.societies import RolePlaying\nfrom camel.logger import set_log_level\n\nfrom owl.utils import run_society, DocumentProcessingToolkit\n\nimport pathlib\n\n# Set the log level to DEBUG for detailed debugging information\nset_log_level(level=\"DEBUG\")\n\n# Get the parent directory of the current file and construct the path to the .env file\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\n\ndef get_user_input(prompt):\n # Get user input and strip leading/trailing whitespace\n return input(prompt).strip()\n\n\ndef get_construct_params() -> dict[str, any]:\n # Welcome message\n print(\"Welcome to owl! Have fun!\")\n\n # Select model platform type\n model_platforms = ModelPlatformType\n print(\"Please select the model platform type:\")\n for i, platform in enumerate(model_platforms, 1):\n print(f\"{i}. {platform}\")\n model_platform_choice = int(\n get_user_input(\"Please enter the model platform number:\")\n )\n selected_model_platform = list(model_platforms)[model_platform_choice - 1]\n print(f\"The model platform you selected is: {selected_model_platform}\")\n\n # Select model type\n models = ModelType\n print(\"Please select the model type:\")\n for i, model in enumerate(models, 1):\n print(f\"{i}. {model}\")\n model_choice = int(get_user_input(\"Please enter the model number:\"))\n selected_model = list(models)[model_choice - 1]\n print(f\"The model you selected is: {selected_model}\")\n\n # Select language\n languages = [\"English\", \"Chinese\"]\n print(\"Please select the language:\")\n for i, lang in enumerate(languages, 1):\n print(f\"{i}. {lang}\")\n language_choice = int(get_user_input(\"Please enter the language number:\"))\n selected_language = languages[language_choice - 1]\n print(f\"The language you selected is: {selected_language}\")\n\n # Enter the question\n question = get_user_input(\"Please enter your question:\")\n print(f\"Your question is: {question}\")\n\n return {\n \"language\": selected_language,\n \"model_type\": selected_model,\n \"model_platform\": selected_model_platform,\n \"question\": question,\n }\n\n\ndef construct_society() -> RolePlaying:\n # Get user input parameters\n params = get_construct_params()\n question = params[\"question\"]\n selected_model_type = params[\"model_type\"]\n selected_model_platform = params[\"model_platform\"]\n selected_language = params[\"language\"]\n\n # Create model instances for different roles\n models = {\n \"user\": ModelFactory.create(\n model_platform=selected_model_platform,\n model_type=selected_model_type,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=selected_model_platform,\n model_type=selected_model_type,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=selected_model_platform,\n model_type=selected_model_type,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=selected_model_platform,\n model_type=selected_model_type,\n model_config_dict={\"temperature\": 0},\n ),\n \"video\": ModelFactory.create(\n model_platform=selected_model_platform,\n model_type=selected_model_type,\n model_config_dict={\"temperature\": 0},\n ),\n \"image\": ModelFactory.create(\n model_platform=selected_model_platform,\n model_type=selected_model_type,\n model_config_dict={\"temperature\": 0},\n ),\n \"document\": ModelFactory.create(\n model_platform=selected_model_platform,\n model_type=selected_model_type,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False,\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *VideoAnalysisToolkit(model=models[\"video\"]).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_google,\n SearchToolkit().search_wiki,\n SearchToolkit().search_baidu,\n SearchToolkit().search_bing,\n *ExcelToolkit().get_tools(),\n *DocumentProcessingToolkit(model=models[\"document\"]).get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n output_language=selected_language,\n )\n\n return society\n\n\ndef main():\n # Construct the society\n society = construct_society()\n # Run the society and get the answer, chat history, and token count\n answer, chat_history, token_count = run_society(society)\n # Print the answer\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run_azure_openai.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport os\nimport sys\nfrom dotenv import load_dotenv\nfrom camel.configs import ChatGPTConfig\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n SearchToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType\n\nfrom owl.utils import OwlRolePlaying, run_society\n\nfrom camel.logger import set_log_level\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> OwlRolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n OwlRolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components using Azure OpenAI\n base_model_config = {\n \"model_platform\": ModelPlatformType.AZURE,\n \"model_type\": os.getenv(\"AZURE_OPENAI_MODEL_TYPE\"),\n \"model_config_dict\": ChatGPTConfig(temperature=0.4, max_tokens=4096).as_dict(),\n }\n\n models = {\n \"user\": ModelFactory.create(**base_model_config),\n \"assistant\": ModelFactory.create(**base_model_config),\n \"browsing\": ModelFactory.create(**base_model_config),\n \"planning\": ModelFactory.create(**base_model_config),\n \"image\": ModelFactory.create(**base_model_config),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_google, # Comment this out if you don't have google search\n SearchToolkit().search_wiki,\n *ExcelToolkit().get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = OwlRolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with Azure OpenAI.\"\"\"\n # Example question\n default_task = \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run_terminal.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nfrom dotenv import load_dotenv\nimport sys\nimport os\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n SearchToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n TerminalToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\n\nfrom owl.utils import run_society\nfrom camel.societies import RolePlaying\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the\n question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_wiki,\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n *TerminalToolkit().get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Example research question\n default_task = f\"\"\"Open Google Search, summarize the number of GitHub stars, forks, etc., of the camel framework of camel-ai, \n and write the numbers into a Python file using the plot package, \n save it to \"+{os.path.join(base_dir, 'final_output')}+\", \n and execute the Python file with the local terminal to display the graph for me.\"\"\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(\n f\"\\033[94mAnswer: {answer}\\nChat History: {chat_history}\\ntoken_count:{token_count}\\033[0m\"\n )\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run_mcp_sse.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport asyncio\nimport sys\nfrom pathlib import Path\nfrom typing import List\n\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import FunctionTool\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.toolkits import MCPToolkit\n\nfrom owl.utils.enhanced_role_playing import OwlRolePlaying, arun_society\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\nasync def construct_society(\n question: str,\n tools: List[FunctionTool],\n) -> OwlRolePlaying:\n r\"\"\"Build a multi-agent OwlRolePlaying instance for GitHub information retrieval.\n\n Args:\n question (str): The GitHub-related question to ask.\n tools (List[FunctionTool]): The MCP tools to use for GitHub interaction.\n \"\"\"\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\n \"model\": models[\"assistant\"],\n \"tools\": tools,\n }\n\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n society = OwlRolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n return society\n\n\nasync def main():\n # Load SSE server configuration\n config_path = Path(__file__).parent / \"mcp_sse_config.json\"\n mcp_toolkit = MCPToolkit(config_path=str(config_path))\n\n try:\n # Connect to MCP server\n await mcp_toolkit.connect()\n print(\"Successfully connected to SSE server\")\n\n # Get available tools\n tools = [*mcp_toolkit.get_tools()]\n\n # Set default task - a simple example query\n default_task = (\n \"What are the most recent pull requests in camel-ai/camel repository?\"\n )\n\n # Use command line argument if provided, otherwise use default task\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Build and run society\n society = await construct_society(task, tools)\n answer, chat_history, token_count = await arun_society(society)\n print(f\"\\nResult: {answer}\")\n\n except KeyboardInterrupt:\n print(\"\\nReceived exit signal, shutting down...\")\n except Exception as e:\n print(f\"Error occurred: {e}\")\n finally:\n # Ensure safe disconnection\n try:\n await mcp_toolkit.disconnect()\n except Exception as e:\n print(f\"Error during disconnect: {e}\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n"], ["/owl/examples/run_gemini.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport sys\nimport pathlib\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n SearchToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.societies import RolePlaying\n\nfrom owl.utils import run_society, DocumentProcessingToolkit\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.GEMINI,\n model_type=ModelType.GEMINI_2_5_PRO_EXP,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.GEMINI,\n model_type=ModelType.GEMINI_2_5_PRO_EXP,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.GEMINI,\n model_type=ModelType.GEMINI_2_5_PRO_EXP,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.GEMINI,\n model_type=ModelType.GEMINI_2_5_PRO_EXP,\n model_config_dict={\"temperature\": 0},\n ),\n \"video\": ModelFactory.create(\n model_platform=ModelPlatformType.GEMINI,\n model_type=ModelType.GEMINI_2_5_PRO_EXP,\n model_config_dict={\"temperature\": 0},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.GEMINI,\n model_type=ModelType.GEMINI_2_5_PRO_EXP,\n model_config_dict={\"temperature\": 0},\n ),\n \"document\": ModelFactory.create(\n model_platform=ModelPlatformType.GEMINI,\n model_type=ModelType.GEMINI_2_5_PRO_EXP,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_google, # Comment this out if you don't have google search\n SearchToolkit().search_wiki,\n *ExcelToolkit().get_tools(),\n *DocumentProcessingToolkit(model=models[\"document\"]).get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Default research question\n default_task = \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run_mini.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport sys\nfrom dotenv import load_dotenv\n\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n SearchToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n CodeExecutionToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\n\nfrom owl.utils import run_society\n\nfrom camel.societies import RolePlaying\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the\n question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_wiki,\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Default research question\n default_task = \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport sys\nimport pathlib\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n AudioAnalysisToolkit,\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n SearchToolkit,\n VideoAnalysisToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.societies import RolePlaying\n\nfrom owl.utils import run_society, DocumentProcessingToolkit\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"video\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"document\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *VideoAnalysisToolkit(model=models[\"video\"]).get_tools(),\n *AudioAnalysisToolkit().get_tools(), # This requires OpenAI Key\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_google, # Comment this out if you don't have google search\n SearchToolkit().search_wiki,\n *ExcelToolkit().get_tools(),\n *DocumentProcessingToolkit(model=models[\"document\"]).get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Default research question\n default_task = \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run_novita_ai.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport sys\nimport pathlib\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.societies import RolePlaying\n\nfrom owl.utils import run_society, DocumentProcessingToolkit\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.NOVITA,\n model_type=ModelType.NOVITA_LLAMA_4_SCOUT_17B,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.NOVITA,\n model_type=ModelType.NOVITA_LLAMA_4_SCOUT_17B,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.NOVITA,\n model_type=ModelType.NOVITA_LLAMA_4_SCOUT_17B,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.NOVITA,\n model_type=ModelType.NOVITA_LLAMA_4_SCOUT_17B,\n model_config_dict={\"temperature\": 0},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.NOVITA,\n model_type=ModelType.NOVITA_LLAMA_4_SCOUT_17B,\n model_config_dict={\"temperature\": 0},\n ),\n \"document\": ModelFactory.create(\n model_platform=ModelPlatformType.NOVITA,\n model_type=ModelType.NOVITA_LLAMA_4_SCOUT_17B,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n *ExcelToolkit().get_tools(),\n *DocumentProcessingToolkit(model=models[\"document\"]).get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Default research question\n default_task = \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run_claude.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport sys\nimport pathlib\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n AudioAnalysisToolkit,\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n SearchToolkit,\n VideoAnalysisToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.societies import RolePlaying\n\nfrom owl.utils import run_society, DocumentProcessingToolkit\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.ANTHROPIC,\n model_type=ModelType.CLAUDE_3_7_SONNET,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.ANTHROPIC,\n model_type=ModelType.CLAUDE_3_7_SONNET,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.ANTHROPIC,\n model_type=ModelType.CLAUDE_3_7_SONNET,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.ANTHROPIC,\n model_type=ModelType.CLAUDE_3_7_SONNET,\n model_config_dict={\"temperature\": 0},\n ),\n \"video\": ModelFactory.create(\n model_platform=ModelPlatformType.ANTHROPIC,\n model_type=ModelType.CLAUDE_3_7_SONNET,\n model_config_dict={\"temperature\": 0},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.ANTHROPIC,\n model_type=ModelType.CLAUDE_3_7_SONNET,\n model_config_dict={\"temperature\": 0},\n ),\n \"document\": ModelFactory.create(\n model_platform=ModelPlatformType.ANTHROPIC,\n model_type=ModelType.CLAUDE_3_7_SONNET,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *VideoAnalysisToolkit(model=models[\"video\"]).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_wiki,\n *ExcelToolkit().get_tools(),\n *DocumentProcessingToolkit(model=models[\"document\"]).get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Default research question\n default_task = \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run_together_ai.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport sys\nimport pathlib\nfrom dotenv import load_dotenv\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\nfrom camel.societies import RolePlaying\n\nfrom owl.utils import run_society, DocumentProcessingToolkit\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.TOGETHER,\n model_type=ModelType.TOGETHER_LLAMA_4_MAVERICK,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.TOGETHER,\n model_type=ModelType.TOGETHER_LLAMA_4_MAVERICK,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.TOGETHER,\n model_type=ModelType.TOGETHER_LLAMA_4_MAVERICK,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.TOGETHER,\n model_type=ModelType.TOGETHER_LLAMA_4_MAVERICK,\n model_config_dict={\"temperature\": 0},\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.TOGETHER,\n model_type=ModelType.TOGETHER_LLAMA_4_MAVERICK,\n model_config_dict={\"temperature\": 0},\n ),\n \"document\": ModelFactory.create(\n model_platform=ModelPlatformType.TOGETHER,\n model_type=ModelType.TOGETHER_LLAMA_4_MAVERICK,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n *ExcelToolkit().get_tools(),\n *DocumentProcessingToolkit(model=models[\"document\"]).get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Default research question\n default_task = \"Open Brave search, summarize the github stars, fork counts, etc. of camel-ai's camel framework, and write the numbers into a python file using the plot package, save it locally, and run the generated python file. Note: You have been provided with the necessary tools to complete this task.\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(f\"\\033[94mAnswer: {answer}\\033[0m\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run_terminal_zh.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nfrom dotenv import load_dotenv\nimport sys\nimport os\nfrom camel.models import ModelFactory\nfrom camel.toolkits import (\n SearchToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n TerminalToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.logger import set_log_level\n\nfrom owl.utils import run_society\nfrom camel.societies import RolePlaying\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\n\ndef construct_society(question: str) -> RolePlaying:\n r\"\"\"Construct a society of agents based on the given question.\n\n Args:\n question (str): The task or question to be addressed by the society.\n\n Returns:\n RolePlaying: A configured society of agents ready to address the\n question.\n \"\"\"\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict={\"temperature\": 0},\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n SearchToolkit().search_duckduckgo,\n SearchToolkit().search_wiki,\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n *TerminalToolkit().get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Configure task parameters\n task_kwargs = {\n \"task_prompt\": question,\n \"with_task_specify\": False,\n }\n\n # Create and return the society\n society = RolePlaying(\n **task_kwargs,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n return society\n\n\ndef main():\n r\"\"\"Main function to run the OWL system with an example question.\"\"\"\n # Example research question\n default_task = f\"\"\"打开百度搜索,总结一下camel-ai的camel框架的github star、fork数目等,并把数字用plot包写成python文件保存到\"+{os.path.join\n(base_dir, 'final_output')}+\",用本地终端执行python文件显示图出来给我\"\"\"\n\n # Override default task if command line argument is provided\n task = sys.argv[1] if len(sys.argv) > 1 else default_task\n\n # Construct and run the society\n society = construct_society(task)\n answer, chat_history, token_count = run_society(society)\n\n # Output the result\n print(\n f\"\\033[94mAnswer: {answer}\\nChat History: {chat_history}\\ntoken_count:{token_count}\\033[0m\"\n )\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/examples/run_gaia_roleplaying.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\nfrom dotenv import load_dotenv\n\n\nimport os\n\nfrom camel.models import ModelFactory\nfrom camel.logger import get_logger\nfrom camel.toolkits import (\n AudioAnalysisToolkit,\n CodeExecutionToolkit,\n ExcelToolkit,\n ImageAnalysisToolkit,\n SearchToolkit,\n VideoAnalysisToolkit,\n BrowserToolkit,\n FileWriteToolkit,\n)\nfrom camel.types import ModelPlatformType, ModelType\nfrom camel.configs import ChatGPTConfig\n\nfrom owl.utils import GAIABenchmark\nfrom camel.logger import set_log_level\n\nimport pathlib\n\nbase_dir = pathlib.Path(__file__).parent.parent\nenv_path = base_dir / \"owl\" / \".env\"\nload_dotenv(dotenv_path=str(env_path))\n\nset_log_level(level=\"DEBUG\")\n\nlogger = get_logger(__name__)\n\n# Configuration\nLEVEL = 1\nSAVE_RESULT = True\ntest_idx = [0]\n\n\ndef main():\n \"\"\"Main function to run the GAIA benchmark.\"\"\"\n # Create cache directory\n cache_dir = \"tmp/\"\n os.makedirs(cache_dir, exist_ok=True)\n result_dir = \"results/\"\n os.makedirs(result_dir, exist_ok=True)\n\n # Create models for different components\n models = {\n \"user\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict=ChatGPTConfig(temperature=0, top_p=1).as_dict(),\n ),\n \"assistant\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict=ChatGPTConfig(temperature=0, top_p=1).as_dict(),\n ),\n \"browsing\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict=ChatGPTConfig(temperature=0, top_p=1).as_dict(),\n ),\n \"planning\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict=ChatGPTConfig(temperature=0, top_p=1).as_dict(),\n ),\n \"video\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict=ChatGPTConfig(temperature=0, top_p=1).as_dict(),\n ),\n \"image\": ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI,\n model_type=ModelType.GPT_4O,\n model_config_dict=ChatGPTConfig(temperature=0, top_p=1).as_dict(),\n ),\n }\n\n # Configure toolkits\n tools = [\n *BrowserToolkit(\n headless=False, # Set to True for headless mode (e.g., on remote servers)\n web_agent_model=models[\"browsing\"],\n planning_agent_model=models[\"planning\"],\n ).get_tools(),\n *VideoAnalysisToolkit(\n model=models[\"video\"]\n ).get_tools(), # This requires OpenAI Key\n *AudioAnalysisToolkit().get_tools(), # This requires OpenAI Key\n *CodeExecutionToolkit(sandbox=\"subprocess\", verbose=True).get_tools(),\n *ImageAnalysisToolkit(model=models[\"image\"]).get_tools(),\n *SearchToolkit().get_tools(),\n *ExcelToolkit().get_tools(),\n *FileWriteToolkit(output_dir=\"./\").get_tools(),\n ]\n\n # Configure agent roles and parameters\n user_agent_kwargs = {\"model\": models[\"user\"]}\n assistant_agent_kwargs = {\"model\": models[\"assistant\"], \"tools\": tools}\n\n # Initialize benchmark\n benchmark = GAIABenchmark(data_dir=\"data/gaia\", save_to=\"results/result.json\")\n\n # Print benchmark information\n print(f\"Number of validation examples: {len(benchmark.valid)}\")\n print(f\"Number of test examples: {len(benchmark.test)}\")\n\n # Run benchmark\n result = benchmark.run(\n on=\"valid\",\n level=LEVEL,\n idx=test_idx,\n save_result=SAVE_RESULT,\n user_role_name=\"user\",\n user_agent_kwargs=user_agent_kwargs,\n assistant_role_name=\"assistant\",\n assistant_agent_kwargs=assistant_agent_kwargs,\n )\n\n # Output results\n logger.info(f\"Correct: {result['correct']}, Total: {result['total']}\")\n logger.info(f\"Accuracy: {result['accuracy']}\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/main.py", "\"\"\"\n基于Camel框架的A股投资代理系统主程序\n\"\"\"\nimport argparse\nimport logging\nimport json\nimport os\nimport sys\nfrom datetime import datetime, timedelta\nfrom typing import Dict, Any, List, Optional\n\n# 添加项目根目录到Python路径\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\nproject_root = os.path.dirname(current_dir)\nsys.path.append(project_root)\n\nfrom src.agents.market_data_agent import MarketDataAgent\nfrom src.agents.technical_analyst import TechnicalAnalystAgent\nfrom src.agents.fundamentals_analyst import FundamentalsAnalystAgent\nfrom src.agents.sentiment_analyst import SentimentAnalystAgent\nfrom src.agents.valuation_analyst import ValuationAnalystAgent\nfrom src.agents.researcher_bull import ResearcherBullAgent\nfrom src.agents.researcher_bear import ResearcherBearAgent\nfrom src.agents.debate_room import DebateRoomAgent\nfrom src.agents.risk_manager import RiskManagerAgent\nfrom src.agents.portfolio_manager import PortfolioManagerAgent\nfrom src.models import Portfolio, TradingDecision, AnalysisSignal, StockData\n\n# 设置日志\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n handlers=[\n logging.FileHandler(\"logs/main.log\"),\n logging.StreamHandler()\n ]\n)\nlogger = logging.getLogger(\"Main\")\n\n\ndef run_investment_analysis(\n ticker: str,\n start_date: Optional[str] = None,\n end_date: Optional[str] = None,\n portfolio: Optional[Dict[str, Any]] = None,\n show_reasoning: bool = False,\n num_of_news: int = 5,\n model_name: str = \"gemini\"\n) -> TradingDecision:\n \"\"\"\n 运行投资分析流程\n \n Args:\n ticker: 股票代码\n start_date: 开始日期 (YYYY-MM-DD)\n end_date: 结束日期 (YYYY-MM-DD)\n portfolio: 当前投资组合状态\n show_reasoning: 是否显示推理过程\n num_of_news: 情绪分析使用的新闻数量\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \n Returns:\n TradingDecision: 交易决策\n \"\"\"\n logger.info(f\"开始对 {ticker} 进行投资分析,使用模型: {model_name}\")\n \n # 设置默认日期\n if not end_date:\n end_date = datetime.now().strftime(\"%Y-%m-%d\")\n if not start_date:\n start_date_obj = datetime.strptime(end_date, \"%Y-%m-%d\") - timedelta(days=365)\n start_date = start_date_obj.strftime(\"%Y-%m-%d\")\n \n # 设置默认投资组合\n if not portfolio:\n portfolio = {\"cash\": 100000.0, \"stock\": 0}\n \n # 初始数据\n data = {\n \"ticker\": ticker,\n \"start_date\": start_date,\n \"end_date\": end_date,\n \"portfolio\": portfolio,\n \"num_of_news\": num_of_news\n }\n \n # 创建代理\n market_data_agent = MarketDataAgent(show_reasoning=show_reasoning, model_name=model_name)\n technical_analyst = TechnicalAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)\n fundamentals_analyst = FundamentalsAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)\n sentiment_analyst = SentimentAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)\n valuation_analyst = ValuationAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)\n researcher_bull = ResearcherBullAgent(show_reasoning=show_reasoning, model_name=model_name)\n researcher_bear = ResearcherBearAgent(show_reasoning=show_reasoning, model_name=model_name)\n debate_room = DebateRoomAgent(show_reasoning=show_reasoning, model_name=model_name)\n risk_manager = RiskManagerAgent(show_reasoning=show_reasoning, model_name=model_name)\n portfolio_manager = PortfolioManagerAgent(show_reasoning=show_reasoning, model_name=model_name)\n \n try:\n # 第一步: 获取市场数据\n logger.info(\"步骤1: 获取市场数据\")\n market_data_result = market_data_agent.process(data)\n \n # 提取股票数据\n stock_data = market_data_result.get(\"stock_data\")\n if not stock_data:\n raise ValueError(\"市场数据代理未返回股票数据\")\n \n # 第二步: 技术分析\n logger.info(\"步骤2: 进行技术分析\")\n technical_data = {\n \"stock_data\": stock_data,\n \"messages\": market_data_result.get(\"messages\", [])\n }\n technical_result = technical_analyst.process(technical_data)\n technical_analysis = technical_result.get(\"technical_analysis\")\n \n # 第三步: 基本面分析\n logger.info(\"步骤3: 进行基本面分析\")\n fundamentals_data = {\n \"stock_data\": stock_data,\n \"messages\": technical_result.get(\"messages\", [])\n }\n fundamentals_result = fundamentals_analyst.process(fundamentals_data)\n fundamentals_analysis = fundamentals_result.get(\"fundamentals_analysis\")\n \n # 第四步: 情绪分析\n logger.info(\"步骤4: 进行情绪分析\")\n sentiment_data = {\n \"stock_data\": stock_data,\n \"messages\": fundamentals_result.get(\"messages\", [])\n }\n sentiment_result = sentiment_analyst.process(sentiment_data)\n sentiment_analysis = sentiment_result.get(\"sentiment_analysis\")\n \n # 第五步: 估值分析\n logger.info(\"步骤5: 进行估值分析\")\n valuation_data = {\n \"stock_data\": stock_data,\n \"fundamentals_analysis\": fundamentals_analysis,\n \"messages\": sentiment_result.get(\"messages\", [])\n }\n valuation_result = valuation_analyst.process(valuation_data)\n valuation_analysis = valuation_result.get(\"valuation_analysis\")\n \n # 第六步: 多头研究员报告\n logger.info(\"步骤6: 生成多头研究报告\")\n bull_data = {\n \"stock_data\": stock_data,\n \"technical_analysis\": technical_analysis,\n \"fundamentals_analysis\": fundamentals_analysis,\n \"sentiment_analysis\": sentiment_analysis,\n \"valuation_analysis\": valuation_analysis,\n \"messages\": valuation_result.get(\"messages\", [])\n }\n bull_result = researcher_bull.process(bull_data)\n bull_research = bull_result.get(\"bull_research\")\n \n # 第七步: 空头研究员报告\n logger.info(\"步骤7: 生成空头研究报告\")\n bear_data = {\n \"stock_data\": stock_data,\n \"technical_analysis\": technical_analysis,\n \"fundamentals_analysis\": fundamentals_analysis,\n \"sentiment_analysis\": sentiment_analysis,\n \"valuation_analysis\": valuation_analysis,\n \"messages\": bull_result.get(\"messages\", [])\n }\n bear_result = researcher_bear.process(bear_data)\n bear_research = bear_result.get(\"bear_research\")\n \n # 第八步: 辩论室\n logger.info(\"步骤8: 举行辩论会\")\n debate_data = {\n \"stock_data\": stock_data,\n \"bull_research\": bull_research,\n \"bear_research\": bear_research,\n \"messages\": bear_result.get(\"messages\", [])\n }\n debate_result = debate_room.process(debate_data)\n debate_signal = debate_result.get(\"debate_result\")\n \n # 第九步: 风险评估\n logger.info(\"步骤9: 进行风险评估\")\n risk_data = {\n \"stock_data\": stock_data,\n \"debate_result\": debate_signal,\n \"portfolio\": portfolio,\n \"messages\": debate_result.get(\"messages\", [])\n }\n risk_result = risk_manager.process(risk_data)\n risk_analysis = risk_result.get(\"risk_analysis\")\n \n # 第十步: 投资组合管理\n logger.info(\"步骤10: 制定最终投资决策\")\n portfolio_data = {\n \"stock_data\": stock_data,\n \"technical_analysis\": technical_analysis,\n \"fundamentals_analysis\": fundamentals_analysis,\n \"sentiment_analysis\": sentiment_analysis,\n \"valuation_analysis\": valuation_analysis,\n \"debate_result\": debate_signal,\n \"risk_analysis\": risk_analysis,\n \"portfolio\": portfolio,\n \"messages\": risk_result.get(\"messages\", [])\n }\n portfolio_result = portfolio_manager.process(portfolio_data)\n trading_decision = portfolio_result.get(\"trading_decision\")\n \n logger.info(f\"投资分析完成,决策: {trading_decision.action}, 数量: {trading_decision.quantity}\")\n return trading_decision\n \n except Exception as e:\n logger.error(f\"投资分析过程中发生错误: {str(e)}\")\n \n # 返回默认决策\n default_decision = TradingDecision(\n action=\"hold\",\n quantity=0,\n confidence=0.5,\n agent_signals=[],\n reasoning=f\"分析过程中发生错误: {str(e)}\"\n )\n return default_decision\n\n\ndef test(ticker: str = \"000001\", model_name: str = \"gemini\"):\n \"\"\"\n 测试函数,使用预设参数快速测试系统功能\n \n Args:\n ticker: 股票代码,默认为\"000001\"(平安银行)\n model_name: 使用的模型名称 (gemini, openai, qwen)\n \"\"\"\n logger.info(f\"开始测试功能,分析股票: {ticker}\")\n \n # 预设参数\n show_reasoning = True # 显示推理过程\n num_of_news = 5 # 获取5条新闻\n initial_capital = 100000.0 # 初始资金10万元\n \n # 日期设置(默认分析最近30天)\n end_date = datetime.now().strftime(\"%Y-%m-%d\")\n start_date_obj = datetime.strptime(end_date, \"%Y-%m-%d\") - timedelta(days=30)\n start_date = start_date_obj.strftime(\"%Y-%m-%d\")\n \n # 创建投资组合\n portfolio = {\n \"cash\": initial_capital,\n \"stock\": 0\n }\n \n print(f\"测试配置:\")\n print(f\"- 股票: {ticker}\")\n print(f\"- 模型: {model_name}\")\n print(f\"- 时间范围: {start_date} 至 {end_date}\")\n print(f\"- 初始资金: {initial_capital}\")\n print(f\"- 新闻数量: {num_of_news}\")\n print(\"\\n开始分析...\\n\")\n \n # 运行投资分析\n decision = run_investment_analysis(\n ticker=ticker,\n start_date=start_date,\n end_date=end_date,\n portfolio=portfolio,\n show_reasoning=show_reasoning,\n num_of_news=num_of_news,\n model_name=model_name\n )\n \n # 输出结果\n print(\"\\n测试结果 - 交易决策:\")\n print(json.dumps(decision.dict(), indent=2, ensure_ascii=False))\n return decision\n\n\ndef main():\n \"\"\"主函数\"\"\"\n # 解析命令行参数\n parser = argparse.ArgumentParser(description=\"基于Camel框架的A股投资代理系统\")\n parser.add_argument(\"--ticker\", type=str, required=True, help=\"股票代码\")\n parser.add_argument(\"--start-date\", type=str, help=\"开始日期 (YYYY-MM-DD)\")\n parser.add_argument(\"--end-date\", type=str, help=\"结束日期 (YYYY-MM-DD)\")\n parser.add_argument(\"--cash\", type=float, default=100000.0, help=\"初始现金\")\n parser.add_argument(\"--stock\", type=int, default=0, help=\"初始股票数量\")\n parser.add_argument(\"--model\", type=str, default=\"qwen\", choices=[\"gemini\", \"openai\", \"qwen\"], help=\"使用的模型\")\n parser.add_argument(\"--news\", type=int, default=10, help=\"情绪分析的新闻数量\")\n parser.add_argument(\"--show-reasoning\", action=\"store_true\", help=\"显示详细推理过程\")\n parser.add_argument(\"--test\", action=\"store_true\", help=\"以测试模式运行,使用默认参数\")\n \n args = parser.parse_args()\n \n # 测试模式\n if args.test:\n test(ticker=args.ticker, model_name=args.model)\n return\n \n # 正常模式,使用命令行参数\n portfolio = {\n \"cash\": args.cash,\n \"stock\": args.stock\n }\n \n decision = run_investment_analysis(\n ticker=args.ticker,\n start_date=args.start_date,\n end_date=args.end_date,\n portfolio=portfolio,\n show_reasoning=args.show_reasoning,\n num_of_news=args.news,\n model_name=args.model\n )\n \n print(json.dumps(decision.dict(), indent=2, ensure_ascii=False))\n\n\nif __name__ == \"__main__\":\n main() "], ["/owl/community_usecase/stock-analysis/agent/sec_agent.py", "\nimport os\nfrom camel.agents.chat_agent import ChatAgent\nfrom pydantic import BaseModel\nfrom typing import List\nfrom camel.agents import ChatAgent\nfrom camel.models import ModelFactory\nfrom camel.types import ModelPlatformType, ModelType\nfrom tools.sec_tools import SECToolkit\nfrom camel.toolkits import FunctionTool\nfrom prompts import get_sec_system_prompt\n\ndef create_sec_agent() -> ChatAgent:\n # Define the model, here in this case we use gpt-4o-mini\n model = ModelFactory.create(\n model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,\n model_type=\"glm-4-flash\",\n api_key=os.getenv(\"ZHIPUAI_API_KEY\"),\n url=os.getenv(\"ZHIPUAI_API_BASE_URL\"),\n model_config_dict={\"temperature\": 0},\n )\n # Create agent with structured output\n agent = ChatAgent(\n system_message=get_sec_system_prompt(),\n model=model,\n tools = [\n *SECToolkit().get_tools()\n ]\n )\n return agent\n\ndef get_sec_summary_for_company(company_stock_name: str) -> str:\n r\"\"\"Retrieve and analyze SEC filing information for a specified company and generate a comprehensive analysis report.\n\n This function retrieves relevant documents from the SEC database using the company's stock symbol,\n analyzes key financial metrics, business developments, risk conditions, market position,\n and generates a structured analysis report.\n\n Args:\n company_stock_name (str): Company stock symbol (e.g., 'AAPL' for Apple Inc.)\n\n Returns:\n str: A comprehensive analysis report containing:\n - Key financial metrics from quarterly and annual reports\n - Important business developments, risks, and market position\n - Management discussion and strategic plans\n - Material changes in operations and financial conditions\n - Important regulatory disclosures and compliance matters\n \n The report is formatted as structured text, limited to 10,000 words,\n highlighting information most relevant and impactful to investors.\n \"\"\"\n\n # Define Summary Prompt\n usr_msg = f\"\"\"Please search and analyze the SEC filings for {company_stock_name} and provide a comprehensive summary report. The report should:\n\n1. Include key financial metrics and performance indicators from recent quarterly and annual reports\n2. Highlight significant business developments, risks, and market position\n3. Analyze management's discussion and strategic initiatives\n4. Note any material changes in operations or financial condition\n5. Summarize important regulatory disclosures and compliance matters\n\nPlease structure the analysis in a clear, concise manner and limit the total response to no more than 10,000 words. Focus on the most relevant and impactful information for investors.\"\"\"\n\n # Sending the message to the agent\n agent = create_sec_agent()\n response = agent.step(usr_msg)\n\n # Check the response (just for illustrative purpose)\n # print(agent.memory.get_context())\n return response.msgs[0].content\n\nget_sec_summary_for_company_tool = FunctionTool(get_sec_summary_for_company)\n\nif __name__ == \"__main__\":\n get_sec_summary_for_company(\"GOOG\")"], ["/owl/community_usecase/a_share_investment_agent_camel/src/tools/api.py", "\"\"\"\n数据API接口模块\n\"\"\"\nimport pandas as pd\nimport akshare as ak\nfrom datetime import datetime\nimport logging\nfrom typing import Optional\n\nlogger = logging.getLogger(__name__)\n\ndef get_price_data(ticker: str, start_date: str, end_date: str) -> Optional[pd.DataFrame]:\n \"\"\"\n 获取股票价格数据\n \n Args:\n ticker: 股票代码\n start_date: 开始日期 (YYYY-MM-DD)\n end_date: 结束日期 (YYYY-MM-DD)\n \n Returns:\n Optional[pd.DataFrame]: 股票价格数据\n \"\"\"\n try:\n logger.info(f\"获取股票 {ticker} 的价格数据\")\n \n # 转换日期格式\n start_date_fmt = datetime.strptime(start_date, \"%Y-%m-%d\").strftime(\"%Y%m%d\")\n end_date_fmt = datetime.strptime(end_date, \"%Y-%m-%d\").strftime(\"%Y%m%d\")\n \n # 使用akshare获取A股历史数据\n df = ak.stock_zh_a_hist(\n symbol=ticker,\n period=\"daily\",\n start_date=start_date_fmt,\n end_date=end_date_fmt,\n adjust=\"qfq\" # 前复权\n )\n \n # 检查df的列数\n logger.info(f\"原始数据列: {df.columns.tolist()}\")\n \n # 调整列名映射以适应实际返回的数据\n column_mappings = {\n '日期': 'date',\n '股票代码': 'code',\n '开盘': 'open',\n '收盘': 'close',\n '最高': 'high',\n '最低': 'low',\n '成交量': 'volume',\n '成交额': 'amount',\n '振幅': 'amplitude',\n '涨跌幅': 'pct_change',\n '涨跌额': 'change',\n '换手率': 'turnover'\n }\n \n # 根据实际列名重命名\n new_columns = []\n for col in df.columns:\n if col in column_mappings:\n new_columns.append(column_mappings[col])\n else:\n # 保留原列名\n new_columns.append(col)\n \n # 应用新列名\n df.columns = new_columns\n \n # 将日期列转换为datetime类型\n df['date'] = pd.to_datetime(df['date'])\n \n logger.info(f\"成功获取价格数据,共 {len(df)} 条记录\")\n return df\n \n except Exception as e:\n logger.error(f\"获取价格数据时发生错误: {str(e)}\")\n return None "], ["/owl/community_usecase/a_share_investment_agent_camel/src/roles.py", "\"\"\"\n角色定义模块\n\n使用Camel框架定义系统中的各种AI代理角色\n\"\"\"\nfrom camel.agents import ChatAgent\nfrom camel.messages import BaseMessage\nfrom camel.models import ModelFactory\nfrom camel.types import ModelType, ModelPlatformType\nfrom camel.configs.qwen_config import QwenConfig\nfrom camel.configs.openai_config import ChatGPTConfig\nimport os\nfrom typing import Dict, Any, List, Optional\nfrom dotenv import load_dotenv\n\n# 加载环境变量\nload_dotenv()\n\n# 获取API密钥和模型配置\nGEMINI_API_KEY = os.getenv(\"GEMINI_API_KEY\")\nGEMINI_MODEL = os.getenv(\"GEMINI_MODEL\", \"gemini-1.5-flash\") # 默认模型\n\nOPENAI_API_KEY = os.getenv(\"OPENAI_API_KEY\")\nOPENAI_MODEL = os.getenv(\"OPENAI_MODEL\", \"gpt-4o\") # 默认模型\n\nQWEN_API_KEY = os.getenv(\"QWEN_API_KEY\")\nQWEN_MODEL = os.getenv(\"QWEN_MODEL\", \"qwen-max\") # 默认模型\nQWEN_API_URL = os.getenv(\"QWEN_API_URL\", \"\") # API URL\n\n# 角色系统提示\nMARKET_DATA_ANALYST_PROMPT = \"\"\"\n你是一名专业的市场数据分析师,负责收集、处理和分析A股市场数据。\n你的主要职责是:\n1. 收集股票的历史价格、交易量和其他市场数据\n2. 计算各种技术指标(如移动平均线、相对强弱指数等)\n3. 整理和预处理数据,确保数据质量和准确性\n4. 标记数据异常并进行适当处理\n\n请以专业、精确的方式分析数据,确保你提供的数据是正确的,并为后续分析提供坚实基础。\n\"\"\"\n\nTECHNICAL_ANALYST_PROMPT = \"\"\"\n你是一名经验丰富的技术分析师,专注于通过技术指标和图表模式分析A股市场。\n你的主要职责是:\n1. 分析价格走势、交易量和技术指标\n2. 识别支撑位和阻力位\n3. 寻找图表模式(如头肩顶、三角形等)\n4. 分析动量和趋势强度\n5. 提供基于技术分析的交易信号\n\n请基于市场数据分析师提供的数据,进行深入的技术分析,并给出明确的交易信号(看涨、看跌或中性)及相应的置信度。\n\"\"\"\n\nFUNDAMENTALS_ANALYST_PROMPT = \"\"\"\n你是一名资深的基本面分析师,专注于分析A股上市公司的财务状况和业务表现。\n你的主要职责是:\n1. 分析公司财务报表(资产负债表、利润表、现金流量表)\n2. 计算和解释关键财务比率(如市盈率、市净率、ROE等)\n3. 评估公司业务模式和竞争优势\n4. 分析行业趋势和公司在行业中的地位\n5. 提供基于基本面的投资建议\n\n请基于市场数据分析师提供的数据,进行深入的基本面分析,并给出明确的交易信号(看涨、看跌或中性)及相应的置信度。\n\"\"\"\n\nSENTIMENT_ANALYST_PROMPT = \"\"\"\n你是一名市场情绪分析师,专注于分析A股市场相关的新闻、社交媒体讨论和市场情绪指标。\n你的主要职责是:\n1. 分析与特定股票相关的新闻报道\n2. 评估市场对该股票的整体情绪(积极、中性或消极)\n3. 识别可能影响市场情绪的重要事件或新闻\n4. 评估市场情绪指标(如恐惧与贪婪指数)\n5. 提供基于情绪分析的交易信号\n\n请基于市场数据分析师提供的数据和新闻内容,进行深入的情绪分析,并给出明确的交易信号(看涨、看跌或中性)及相应的置信度。\n\"\"\"\n\nVALUATION_ANALYST_PROMPT = \"\"\"\n你是一名专业的估值分析师,专注于确定A股上市公司的内在价值。\n你的主要职责是:\n1. 应用不同的估值模型(如DCF、相对估值法)\n2. 计算公司的内在价值\n3. 比较当前市场价格与内在价值\n4. 评估股票是否被高估或低估\n5. 提供基于估值的交易信号\n\n请基于市场数据分析师和基本面分析师提供的数据,进行深入的估值分析,并给出明确的交易信号(看涨、看跌或中性)及相应的置信度。\n\"\"\"\n\nRESEARCHER_BULL_PROMPT = \"\"\"\n你是一名持有看多观点的研究员,专注于寻找支持买入特定A股的理由。\n你的主要职责是:\n1. 分析和解释各类分析师(技术、基本面、情绪、估值)提供的积极信号\n2. 寻找被市场忽视的积极因素\n3. 探索公司未来增长的潜在催化剂\n4. 构建支持买入决策的完整论据\n5. 为投资决策提供看多的研究报告\n\n请基于各位分析师提供的数据和分析,提出最有力的看多论据,并提供一份全面的研究报告。\n\"\"\"\n\nRESEARCHER_BEAR_PROMPT = \"\"\"\n你是一名持有看空观点的研究员,专注于寻找支持卖出特定A股的理由。\n你的主要职责是:\n1. 分析和解释各类分析师(技术、基本面、情绪、估值)提供的消极信号\n2. 寻找被市场忽视的风险因素\n3. 探索可能导致股价下跌的潜在风险\n4. 构建支持卖出决策的完整论据\n5. 为投资决策提供看空的研究报告\n\n请基于各位分析师提供的数据和分析,提出最有力的看空论据,并提供一份全面的研究报告。\n\"\"\"\n\nDEBATE_ROOM_PROMPT = \"\"\"\n你是一个投资辩论室的主持人,负责整合多头和空头研究员的观点,形成一个平衡的投资视角。\n你的主要职责是:\n1. 公正评估多头和空头研究员的论据\n2. 识别双方论据中的优点和弱点\n3. 权衡不同因素的重要性\n4. 形成综合性的市场观点\n5. 提出平衡的投资建议\n\n请基于多头和空头研究员提供的研究报告,进行深入的分析和辩论,并给出一个综合性的市场观点和投资建议。\n\"\"\"\n\nRISK_MANAGER_PROMPT = \"\"\"\n你是一名资深的风险管理经理,负责评估和管理投资决策的风险。\n你的主要职责是:\n1. 计算投资组合的风险指标(如波动率、最大回撤等)\n2. 设定风险限制(如持仓限制、止损水平)\n3. 评估市场和特定股票的风险水平\n4. 根据投资者风险偏好调整风险暴露\n5. 提供风险管理建议\n\n请基于市场数据、投资组合状况和辩论室的综合观点,进行深入的风险分析,并提供明确的风险管理建议,包括建议的持仓规模和风险控制措施。\n\"\"\"\n\nPORTFOLIO_MANAGER_PROMPT = \"\"\"\n你是一名投资组合经理,负责做出最终的投资决策并管理整体投资组合。\n你的主要职责是:\n1. 整合各类分析和建议(技术、基本面、情绪、风险等)\n2. 做出最终的投资决策(买入、卖出或持有)\n3. 确定具体的交易数量和价格\n4. 平衡投资组合的风险与回报\n5. 优化资金分配\n\n请基于各位分析师和风险管理经理提供的信息,做出最终的投资决策,包括具体的交易行动、数量和执行策略。\n\"\"\"\n\n# 创建模型配置\ndef get_model_config(model_name: str = \"gemini\") -> tuple:\n \"\"\"获取模型配置\n \n Args:\n model_name: 模型名称 (gemini, openai, qwen)\n \n Returns:\n tuple: (ModelPlatformType, ModelType, config_dict) 模型平台类型、模型类型和配置字典\n \"\"\"\n model_name = model_name.lower()\n \n if model_name == \"gemini\":\n if not GEMINI_API_KEY:\n raise ValueError(\"缺少Gemini API密钥,请在.env文件中设置GEMINI_API_KEY\")\n return ModelPlatformType.GEMINI, ModelType.GEMINI_1_5_FLASH, {\"api_key\": GEMINI_API_KEY, \"model\": GEMINI_MODEL}\n \n elif model_name == \"openai\":\n if not OPENAI_API_KEY:\n raise ValueError(\"缺少OpenAI API密钥,请在.env文件中设置OPENAI_API_KEY\")\n \n # 返回GPT-4o配置\n return ModelPlatformType.OPENAI, ModelType.GPT_4O, {\"api_key\": OPENAI_API_KEY, \"model\": OPENAI_MODEL}\n \n elif model_name == \"qwen\":\n if not QWEN_API_KEY:\n raise ValueError(\"缺少Qwen API密钥,请在.env文件中设置QWEN_API_KEY\")\n \n # 使用QwenConfig类创建配置,不包含model参数\n qwen_config = QwenConfig(temperature=0.1)\n config = qwen_config.as_dict()\n \n # 移除可能导致错误的参数\n if \"model\" in config:\n del config[\"model\"]\n \n # 使用QWEN_MAX类型\n return ModelPlatformType.QWEN, ModelType.QWEN_MAX, config\n \n else:\n raise ValueError(f\"不支持的模型: {model_name},支持的模型: gemini, openai, qwen\")\n\n\n# 创建角色代理工厂函数\ndef create_role_agent(role: str, model_name: str = \"gemini\") -> ChatAgent:\n \"\"\"创建特定角色的代理\n \n Args:\n role: 角色名称\n model_name: 模型名称 (gemini, openai, qwen)\n \n Returns:\n ChatAgent: 创建的角色代理\n \"\"\"\n # 获取模型配置\n model_platform, model_type, model_config = get_model_config(model_name)\n \n # 获取角色的系统提示\n role_prompts = {\n \"market_data_analyst\": MARKET_DATA_ANALYST_PROMPT,\n \"technical_analyst\": TECHNICAL_ANALYST_PROMPT,\n \"fundamentals_analyst\": FUNDAMENTALS_ANALYST_PROMPT,\n \"sentiment_analyst\": SENTIMENT_ANALYST_PROMPT,\n \"valuation_analyst\": VALUATION_ANALYST_PROMPT,\n \"researcher_bull\": RESEARCHER_BULL_PROMPT,\n \"researcher_bear\": RESEARCHER_BEAR_PROMPT,\n \"debate_room\": DEBATE_ROOM_PROMPT,\n \"risk_manager\": RISK_MANAGER_PROMPT,\n \"portfolio_manager\": PORTFOLIO_MANAGER_PROMPT,\n }\n \n if role not in role_prompts:\n raise ValueError(f\"未知角色: {role}\")\n \n # 格式化角色名称为更友好的显示名称\n display_names = {\n \"market_data_analyst\": \"市场数据分析师\",\n \"technical_analyst\": \"技术分析师\",\n \"fundamentals_analyst\": \"基本面分析师\",\n \"sentiment_analyst\": \"情绪分析师\",\n \"valuation_analyst\": \"估值分析师\",\n \"researcher_bull\": \"多头研究员\",\n \"researcher_bear\": \"空头研究员\",\n \"debate_room\": \"辩论室\",\n \"risk_manager\": \"风险管理经理\",\n \"portfolio_manager\": \"投资组合经理\",\n }\n \n display_name = display_names.get(role, role)\n \n # 创建模型\n model = ModelFactory.create(\n model_platform=model_platform,\n model_type=model_type,\n model_config_dict=model_config\n )\n \n # 创建并返回代理\n return ChatAgent(\n model=model,\n system_message=role_prompts[role]\n ) "], ["/owl/community_usecase/stock-analysis/prompts.py", "# Define Prompts for Agents\n\nfrom datetime import datetime\n\ndef get_system_prompt() -> str:\n r\"\"\"Get the enhanced system prompt for the stock analysis assistant.\"\"\"\n \n current_date = datetime.now().strftime(\"%Y-%m-%d\")\n \n return f\"\"\"\n You are an advanced Stock Analysis Assistant powered by OWL multi-agent technology.\n Your primary task is to provide COMPREHENSIVE, EXTREMELY DETAILED, and HIGHLY SPECIFIC\n stock investment recommendations with practical analysis and actionable advice.\n \n Current Analysis Date: {current_date}\n \n IMPORTANT OUTPUT REQUIREMENTS:\n \n 1. EXTREME DETAIL: Do not summarize or truncate your responses. Provide complete, comprehensive\n information with multiple sections, subsections, and extensive details. The final output\n should be at least 2000 words, ideally 3000-4000 for truly thorough coverage.\n \n 2. COMPANY INFORMATION FOCUS: Include detailed company background, business model, management team,\n competitive landscape, market position, and growth prospects. Emphasize fundamental analysis\n of the company's financial health and operational performance.\n \n 3. COMPREHENSIVE STOCK DATA: Provide in-depth analysis of stock performance metrics, financial ratios,\n valuation models, historical price movements, and trading volumes. Include detailed examination\n of earnings reports, balance sheets, and cash flow statements.\n \n 4. NO TRUNCATION: Never cut off your responses with '...' or similar. Always provide the \n complete thought or explanation.\n \n 5. STRUCTURED OUTPUT: Use clear headings (H1, H2, H3, etc.), bullet points, numbered lists,\n and well-organized sections to present the content in a digestible way.\n \n 6. SPECIFIC INVESTMENT STRATEGIES: Always provide multiple investment approaches, risk assessments,\n entry/exit points, position sizing recommendations, and relevant portfolio considerations.\n \n 7. FILE MANAGEMENT: You may save all information as well-formatted files, but also include\n the entire unabridged content directly in your response. \n \"\"\"\ndef get_sec_system_prompt() -> str:\n r\"\"\"Get the enhanced system prompt for the sec assistant.\"\"\" \n\n return \"\"\"\n You are an advanced SEC Financial Data Analysis Assistant\n Your primary task is to retrieve, analyze and provide DETAILED insights from SEC filings including\n quarterly (10-Q) and annual (10-K) reports.\n\n CORE RESPONSIBILITIES:\n\n 1. DATA RETRIEVAL:\n - Fetch financial statements from SEC EDGAR database\n - Access both quarterly and annual reports\n - Extract key financial metrics and disclosures\n \n 2. FINANCIAL ANALYSIS:\n - Perform comprehensive analysis of income statements\n - Analyze balance sheets and cash flow statements\n - Calculate and interpret key financial ratios\n - Track quarter-over-quarter and year-over-year changes\n \n 3. REPORTING REQUIREMENTS:\n - Present data in clear, structured formats\n - Highlight significant changes and trends\n - Provide detailed explanations of findings\n - Flag any concerning patterns or irregularities\n \n 4. SPECIFIC OUTPUTS:\n - Financial metrics summary\n - Growth analysis\n - Profitability assessment\n - Liquidity analysis\n - Debt and leverage evaluation\n - Cash flow analysis\n \n 5. CONTEXTUAL INSIGHTS:\n - Compare against industry benchmarks\n - Identify potential red flags\n - Evaluate management's commentary\n - Assess risk factors\n \n Always maintain accuracy and completeness in data retrieval and analysis.\n Provide detailed explanations for any significant findings or anomalies.\n \"\"\"\n"], ["/owl/owl/utils/common.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\nimport sys\n\nsys.path.append(\"../\")\n\nimport re\nfrom typing import Optional\nfrom camel.logger import get_logger\n\nlogger = get_logger(__name__)\n\n\ndef extract_pattern(content: str, pattern: str) -> Optional[str]:\n try:\n _pattern = rf\"<{pattern}>(.*?)\"\n match = re.search(_pattern, content, re.DOTALL)\n if match:\n text = match.group(1)\n return text.strip()\n else:\n return None\n except Exception as e:\n logger.warning(f\"Error extracting answer: {e}, current content: {content}\")\n return None\n"], ["/owl/community_usecase/OWL Interview Preparation Assistant/config/prompts.py", "def get_system_prompt() -> str:\n \"\"\"Get the enhanced system prompt for the interview assistant.\"\"\"\n return \"\"\"\n You are an advanced Interview Preparation Assistant powered by OWL multi-agent technology.\n Your primary task is to provide COMPREHENSIVE, EXTREMELY DETAILED, and HIGHLY SPECIFIC\n interview preparation materials with practical examples and actionable advice.\n \n IMPORTANT OUTPUT REQUIREMENTS:\n \n 1. EXTREME DETAIL: Do not summarize or truncate your responses. Provide complete, comprehensive\n information with multiple sections, subsections, and extensive details. The final output\n should be at least 2000 words, ideally 3000-4000 for truly thorough coverage.\n \n 2. PRACTICAL CODE EXAMPLES: For technical roles, include relevant code snippets, detailed \n technical scenarios, and at least 5-10 code samples or system design outlines.\n \n 3. COMPREHENSIVE CONTENT: Create exceptionally thorough content with step-by-step instructions, \n deep explanations, and multiple examples. Never abbreviate or summarize your responses.\n \n 4. NO TRUNCATION: Never cut off your responses with '...' or similar. Always provide the \n complete thought or explanation.\n \n 5. STRUCTURED OUTPUT: Use clear headings (H1, H2, H3, etc.), bullet points, numbered lists,\n and well-organized sections to present the content in a digestible way.\n \n 6. SPECIFIC IMPLEMENTATIONS: For technical roles, always provide multiple code examples, \n approaches, edge cases, and relevant optimizations.\n \n 7. FILE MANAGEMENT: You may save all information as well-formatted files, but also include\n the entire unabridged content directly in your response. \n \"\"\"\n\ndef get_company_research_prompt(company_name: str) -> str:\n \"\"\"Get a specialized prompt for company research.\"\"\"\n return f\"\"\"\n Conduct the most COMPREHENSIVE and EXTREMELY DETAILED research on {company_name} possible.\n The final output must be at least 3000 words, covering the company's history, mission, \n technology stack, culture, interview process, and more. Provide code or architecture \n examples if relevant, and do not abbreviate or summarize. \n \"\"\"\n\ndef get_question_generator_prompt(job_role: str, company_name: str) -> str:\n \"\"\"Get a specialized prompt for interview question generation.\"\"\"\n return f\"\"\"\n Generate an EXTREMELY COMPREHENSIVE, EXHAUSTIVELY DETAILED set of interview questions for \n a {job_role} position at {company_name}. Provide at least 30 questions with deep sample \n answers, code examples, multiple solution approaches, and a total of 3000+ words. \n Do not truncate or summarize.\n \"\"\"\n\ndef get_preparation_plan_prompt(job_role: str, company_name: str) -> str:\n \"\"\"Get a specialized prompt for creating an interview preparation plan.\"\"\"\n return f\"\"\"\n Create a HIGHLY THOROUGH, MULTI-DAY interview preparation plan for a {job_role} position \n at {company_name}. The final plan should exceed 2000 words, with detailed daily tasks, \n technical reviews, code examples (if relevant), and no summary or truncation. \n Cover everything from fundamental skills to advanced interview strategies.\n \"\"\"\n\n"], ["/owl/owl/utils/__init__.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n\nfrom .common import extract_pattern\nfrom .enhanced_role_playing import (\n OwlRolePlaying,\n OwlGAIARolePlaying,\n run_society,\n arun_society,\n)\nfrom .gaia import GAIABenchmark\nfrom .document_toolkit import DocumentProcessingToolkit\n\n__all__ = [\n \"extract_pattern\",\n \"OwlRolePlaying\",\n \"OwlGAIARolePlaying\",\n \"run_society\",\n \"arun_society\",\n \"GAIABenchmark\",\n \"DocumentProcessingToolkit\",\n]\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/models.py", "\"\"\"\n数据模型定义\n\"\"\"\nfrom datetime import datetime\nfrom typing import Dict, List, Optional, Union, Any\nfrom pydantic import BaseModel, Field\nimport json\n\n\nclass StockData(BaseModel):\n \"\"\"股票数据模型\"\"\"\n ticker: str\n historical_data: Dict[str, Any] = Field(default_factory=dict)\n fundamental_data: Dict[str, Any] = Field(default_factory=dict)\n technical_indicators: Dict[str, Any] = Field(default_factory=dict)\n news_data: Dict[str, Any] = Field(default_factory=dict)\n \n \nclass AnalysisSignal(BaseModel):\n \"\"\"分析信号\"\"\"\n agent: str\n signal: str # bullish, bearish, neutral\n confidence: float # 0.0 - 1.0\n reasoning: Optional[str] = None\n details: Optional[Dict[str, Any]] = None\n\n\nclass DateTimeEncoder(json.JSONEncoder):\n \"\"\"处理datetime的JSON编码器\"\"\"\n def default(self, obj):\n if isinstance(obj, datetime):\n return obj.isoformat()\n return super().default(obj)\n\n\nclass TradingDecision(BaseModel):\n \"\"\"交易决策\"\"\"\n action: str # buy, sell, hold\n quantity: int\n confidence: float\n agent_signals: List[AnalysisSignal]\n reasoning: str\n timestamp: Optional[datetime] = None\n \n def __init__(self, **data):\n if 'timestamp' not in data:\n data['timestamp'] = datetime.now()\n super().__init__(**data)\n \n def dict(self):\n \"\"\"返回字典表示,可JSON序列化\"\"\"\n base_dict = super().dict()\n # 转换datetime为ISO格式字符串\n base_dict['timestamp'] = base_dict['timestamp'].isoformat() if base_dict['timestamp'] else None\n return base_dict\n\n\nclass Portfolio(BaseModel):\n \"\"\"投资组合\"\"\"\n cash: float = 100000.0\n stock: int = 0\n stock_value: float = 0.0\n total_value: float = Field(default=0.0)\n holdings: Dict[str, Dict[str, Any]] = Field(default_factory=dict)\n \n def update_total_value(self):\n \"\"\"更新总价值\"\"\"\n self.total_value = self.cash + self.stock_value\n\n\nclass RiskAnalysis(BaseModel):\n \"\"\"风险分析\"\"\"\n max_position_size: float\n volatility: float\n risk_score: float # 0.0 - 1.0\n max_drawdown: float\n suggested_position_size: float\n reasoning: Optional[str] = None\n\n\nclass ResearchReport(BaseModel):\n \"\"\"研究报告\"\"\"\n stance: str # bullish, bearish\n key_points: List[str]\n confidence: float\n technical_summary: Optional[str] = None\n fundamental_summary: Optional[str] = None\n sentiment_summary: Optional[str] = None\n valuation_summary: Optional[str] = None\n reasoning: Optional[str] = None "], ["/owl/examples/__init__.py", "# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========\n"], ["/owl/community_usecase/a_share_investment_agent_camel/src/agents/__init__.py", "\"\"\"\n代理模块初始化\n\"\"\"\n\nfrom src.agents.base_agent import BaseAgent\nfrom src.agents.market_data_agent import MarketDataAgent\nfrom src.agents.technical_analyst import TechnicalAnalystAgent\nfrom src.agents.fundamentals_analyst import FundamentalsAnalystAgent\nfrom src.agents.sentiment_analyst import SentimentAnalystAgent\nfrom src.agents.valuation_analyst import ValuationAnalystAgent\nfrom src.agents.researcher_bull import ResearcherBullAgent\nfrom src.agents.researcher_bear import ResearcherBearAgent\nfrom src.agents.debate_room import DebateRoomAgent\nfrom src.agents.risk_manager import RiskManagerAgent\nfrom src.agents.portfolio_manager import PortfolioManagerAgent\nfrom src.agents.investment_agent import InvestmentAgent\n\n__all__ = [\n 'BaseAgent',\n 'MarketDataAgent', \n 'TechnicalAnalystAgent',\n 'FundamentalsAnalystAgent',\n 'SentimentAnalystAgent',\n 'ValuationAnalystAgent',\n 'ResearcherBullAgent',\n 'ResearcherBearAgent',\n 'DebateRoomAgent',\n 'RiskManagerAgent',\n 'PortfolioManagerAgent',\n 'InvestmentAgent'\n] "], ["/owl/community_usecase/a_share_investment_agent_camel/src/__init__.py", "\"\"\"\n基于Camel框架的A股投资代理系统\n\"\"\"\n\n__version__ = \"0.1.0\" "], ["/owl/community_usecase/a_share_investment_agent_camel/src/tools/__init__.py", "\"\"\"\n工具模块\n\"\"\" "], ["/owl/community_usecase/a_share_investment_agent_camel/src/utils/__init__.py", "\"\"\"\n实用工具模块\n\"\"\" "]], "task_instance_info": {"created_time": "2025-08-20 15:37:35", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Process tabular data entries by extracting key-value pairs, validate their integrity, and store them as configurable system parameters while maintaining a record of processed entries."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```python\n[TASK_BEGIN]\n # Iterate through each row of the DataFrame\n for index, row in data.iterrows():\n # Use column names to access data\n if len(columns) >= 2:\n key = str(row[columns[0]]).strip()\n value = str(row[columns[1]]).strip()\n # Check if key is valid\n if key and is_api_related(key):\n # Add/update environment variable\n success, _ = add_env_var(key, value)\n if success:\n processed_keys.add(key)\n logging.info(f\"Processed env var: {key}=***\")\n else:\n logging.warning(f\"Failed to process env var: {key}\")\n[TASK_END]\n```", "inference_time": "2025-08-20 15-37-48"}, "editdistance_info": {"edit_distance": 12.1495, "calculate_time": "2025-08-20 15:37:48", "true_code_clean": "if len(columns) >= 3:\n key = row[0] if isinstance(row, pd.Series) else row.iloc[0]\n value = row[1] if isinstance(row, pd.Series) else row.iloc[1]\n if (\n key and str(key).strip()\n ): \n logging.info(\n f\"Processing environment variable: {key} = {value}\"\n )\n add_env_var(key, str(value))\n processed_keys.add(key)", "predict_code_clean": " for index, row in data.iterrows():\n if len(columns) >= 2:\n key = str(row[columns[0]]).strip()\n value = str(row[columns[1]]).strip()\n if key and is_api_related(key):\n success, _ = add_env_var(key, value)\n if success:\n processed_keys.add(key)\n logging.info(f\"Processed env var: {key}=***\")\n else:\n logging.warning(f\"Failed to process env var: {key}\")"}}