{"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 \"\"\")\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我们的愿景是彻底改变AI代理协作解决现实世界任务的方式。通过利用动态代理交互,OWL能够在多个领域实现更自然、高效和稳健的任务自动化。
\n利用维基百科、谷歌搜索和其他在线资源获取最新信息。
\n支持处理互联网或本地的视频、图像和音频数据。
\n使用Playwright框架模拟浏览器交互,实现网页操作自动化。
\n从各种文档格式中提取内容,并转换为易于处理的格式。
\n使用解释器编写和运行Python代码,实现自动化数据处理。
\n提供丰富的工具包,支持搜索、数据分析、代码执行等多种功能。
\n便捷管理API密钥和环境配置,安全存储敏感信息。
\nPowered 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(\"