update wendong

This commit is contained in:
Wendong
2025-03-15 10:02:42 +08:00
parent a12047f299
commit c783c2c8bb
16 changed files with 1110 additions and 757 deletions

View File

@@ -1,6 +1,9 @@
# MODEL & API (See https://docs.camel-ai.org/key_modules/models.html#) #===========================================
# MODEL & API
# (See https://docs.camel-ai.org/key_modules/models.html#)
#===========================================
# OPENAI API # OPENAI API (https://platform.openai.com/api-keys)
# OPENAI_API_KEY= "" # OPENAI_API_KEY= ""
# OPENAI_API_BASE_URL="" # OPENAI_API_BASE_URL=""
@@ -15,15 +18,12 @@
#=========================================== #===========================================
# Google Search API (https://developers.google.com/custom-search/v1/overview) # Google Search API (https://developers.google.com/custom-search/v1/overview)
GOOGLE_API_KEY="" # GOOGLE_API_KEY=""
SEARCH_ENGINE_ID="" # SEARCH_ENGINE_ID=""
# Hugging Face API (https://huggingface.co/join)
HF_TOKEN=""
# Chunkr API (https://chunkr.ai/) # Chunkr API (https://chunkr.ai/)
CHUNKR_API_KEY="" # CHUNKR_API_KEY=""
# Firecrawl API (https://www.firecrawl.dev/) # Firecrawl API (https://www.firecrawl.dev/)
FIRECRAWL_API_KEY="" #FIRECRAWL_API_KEY=""
#FIRECRAWL_API_URL="https://api.firecrawl.dev" #FIRECRAWL_API_URL="https://api.firecrawl.dev"

View File

@@ -25,22 +25,23 @@ from camel.toolkits import (
) )
from camel.types import ModelPlatformType, ModelType from camel.types import ModelPlatformType, ModelType
from camel.logger import set_log_level from camel.logger import set_log_level
from camel.societies import RolePlaying
from owl.utils import OwlRolePlaying, run_society, DocumentProcessingToolkit from owl.utils import run_society, DocumentProcessingToolkit
load_dotenv() load_dotenv()
set_log_level(level="DEBUG") set_log_level(level="DEBUG")
def construct_society(question: str) -> OwlRolePlaying: def construct_society(question: str) -> RolePlaying:
r"""Construct a society of agents based on the given question. r"""Construct a society of agents based on the given question.
Args: Args:
question (str): The task or question to be addressed by the society. question (str): The task or question to be addressed by the society.
Returns: Returns:
OwlRolePlaying: A configured society of agents ready to address the question. RolePlaying: A configured society of agents ready to address the question.
""" """
# Create models for different components # Create models for different components
@@ -112,7 +113,7 @@ def construct_society(question: str) -> OwlRolePlaying:
} }
# Create and return the society # Create and return the society
society = OwlRolePlaying( society = RolePlaying(
**task_kwargs, **task_kwargs,
user_role_name="user", user_role_name="user",
user_agent_kwargs=user_agent_kwargs, user_agent_kwargs=user_agent_kwargs,

View File

@@ -31,7 +31,9 @@ from camel.toolkits import (
from camel.types import ModelPlatformType, ModelType from camel.types import ModelPlatformType, ModelType
from owl.utils import OwlRolePlaying, run_society, DocumentProcessingToolkit from owl.utils import run_society
from camel.societies import RolePlaying
from camel.logger import set_log_level from camel.logger import set_log_level
@@ -40,14 +42,14 @@ set_log_level(level="DEBUG")
load_dotenv() load_dotenv()
def construct_society(question: str) -> OwlRolePlaying: def construct_society(question: str) -> RolePlaying:
r"""Construct a society of agents based on the given question. r"""Construct a society of agents based on the given question.
Args: Args:
question (str): The task or question to be addressed by the society. question (str): The task or question to be addressed by the society.
Returns: Returns:
OwlRolePlaying: A configured society of agents ready to address the question. RolePlaying: A configured society of agents ready to address the question.
""" """
# Create models for different components # Create models for different components
@@ -84,7 +86,7 @@ def construct_society(question: str) -> OwlRolePlaying:
} }
# Create and return the society # Create and return the society
society = OwlRolePlaying( society = RolePlaying(
**task_kwargs, **task_kwargs,
user_role_name="user", user_role_name="user",
user_agent_kwargs=user_agent_kwargs, user_agent_kwargs=user_agent_kwargs,
@@ -99,9 +101,7 @@ def construct_society(question: str) -> OwlRolePlaying:
def main(): def main():
r"""Main function to run the OWL system with an example question.""" r"""Main function to run the OWL system with an example question."""
# Example research question # Example research question
question = ( question = "搜索OWL项目最近的新闻并生成一篇报告最后保存到本地。"
"搜索OWL项目最近的新闻并生成一篇报告最后保存到本地。"
)
# Construct and run the society # Construct and run the society
society = construct_society(question) society = construct_society(question)

View File

@@ -22,20 +22,22 @@ from camel.toolkits import (
from camel.types import ModelPlatformType, ModelType from camel.types import ModelPlatformType, ModelType
from camel.logger import set_log_level from camel.logger import set_log_level
from owl.utils import OwlRolePlaying, run_society from owl.utils import run_society
from camel.societies import RolePlaying
load_dotenv() load_dotenv()
set_log_level(level="DEBUG") set_log_level(level="DEBUG")
def construct_society(question: str) -> OwlRolePlaying: def construct_society(question: str) -> RolePlaying:
r"""Construct a society of agents based on the given question. r"""Construct a society of agents based on the given question.
Args: Args:
question (str): The task or question to be addressed by the society. question (str): The task or question to be addressed by the society.
Returns: Returns:
OwlRolePlaying: A configured society of agents ready to address the RolePlaying: A configured society of agents ready to address the
question. question.
""" """
@@ -86,7 +88,7 @@ def construct_society(question: str) -> OwlRolePlaying:
} }
# Create and return the society # Create and return the society
society = OwlRolePlaying( society = RolePlaying(
**task_kwargs, **task_kwargs,
user_role_name="user", user_role_name="user",
user_agent_kwargs=user_agent_kwargs, user_agent_kwargs=user_agent_kwargs,

View File

@@ -25,7 +25,9 @@ from camel.toolkits import (
) )
from camel.types import ModelPlatformType from camel.types import ModelPlatformType
from owl.utils import OwlRolePlaying, run_society from owl.utils import run_society
from camel.societies import RolePlaying
from camel.logger import set_log_level from camel.logger import set_log_level
@@ -34,14 +36,14 @@ set_log_level(level="DEBUG")
load_dotenv() load_dotenv()
def construct_society(question: str) -> OwlRolePlaying: def construct_society(question: str) -> RolePlaying:
r"""Construct a society of agents based on the given question. r"""Construct a society of agents based on the given question.
Args: Args:
question (str): The task or question to be addressed by the society. question (str): The task or question to be addressed by the society.
Returns: Returns:
OwlRolePlaying: A configured society of agents ready to address the question. RolePlaying: A configured society of agents ready to address the question.
""" """
# Create models for different components # Create models for different components
@@ -105,7 +107,7 @@ def construct_society(question: str) -> OwlRolePlaying:
} }
# Create and return the society # Create and return the society
society = OwlRolePlaying( society = RolePlaying(
**task_kwargs, **task_kwargs,
user_role_name="user", user_role_name="user",
user_agent_kwargs=user_agent_kwargs, user_agent_kwargs=user_agent_kwargs,

View File

@@ -25,8 +25,8 @@ from camel.toolkits import (
) )
from camel.types import ModelPlatformType from camel.types import ModelPlatformType
from owl.utils import OwlRolePlaying, run_society from owl.utils import run_society
from camel.societies import RolePlaying
from camel.logger import set_log_level from camel.logger import set_log_level
set_log_level(level="DEBUG") set_log_level(level="DEBUG")
@@ -34,14 +34,14 @@ set_log_level(level="DEBUG")
load_dotenv() load_dotenv()
def construct_society(question: str) -> OwlRolePlaying: def construct_society(question: str) -> RolePlaying:
r"""Construct a society of agents based on the given question. r"""Construct a society of agents based on the given question.
Args: Args:
question (str): The task or question to be addressed by the society. question (str): The task or question to be addressed by the society.
Returns: Returns:
OwlRolePlaying: A configured society of agents ready to address the question. RolePlaying: A configured society of agents ready to address the question.
""" """
# Create models for different components # Create models for different components
@@ -110,7 +110,7 @@ def construct_society(question: str) -> OwlRolePlaying:
} }
# Create and return the society # Create and return the society
society = OwlRolePlaying( society = RolePlaying(
**task_kwargs, **task_kwargs,
user_role_name="user", user_role_name="user",
user_agent_kwargs=user_agent_kwargs, user_agent_kwargs=user_agent_kwargs,

View File

@@ -22,7 +22,9 @@ from camel.models import ModelFactory
from camel.toolkits import BrowserToolkit, SearchToolkit, FileWriteToolkit from camel.toolkits import BrowserToolkit, SearchToolkit, FileWriteToolkit
from camel.types import ModelPlatformType, ModelType from camel.types import ModelPlatformType, ModelType
from owl.utils import OwlRolePlaying, run_society from owl.utils import run_society
from camel.societies import RolePlaying
from camel.logger import set_log_level from camel.logger import set_log_level
@@ -31,7 +33,7 @@ set_log_level(level="DEBUG")
load_dotenv() load_dotenv()
def construct_society(question: str) -> OwlRolePlaying: def construct_society(question: str) -> RolePlaying:
r"""Construct the society based on the question.""" r"""Construct the society based on the question."""
user_role_name = "user" user_role_name = "user"
@@ -82,7 +84,7 @@ def construct_society(question: str) -> OwlRolePlaying:
"with_task_specify": False, "with_task_specify": False,
} }
society = OwlRolePlaying( society = RolePlaying(
**task_kwargs, **task_kwargs,
user_role_name=user_role_name, user_role_name=user_role_name,
user_agent_kwargs=user_agent_kwargs, user_agent_kwargs=user_agent_kwargs,

View File

@@ -28,8 +28,9 @@ from camel.toolkits import (
FileWriteToolkit, FileWriteToolkit,
) )
from camel.types import ModelPlatformType, ModelType from camel.types import ModelPlatformType, ModelType
from camel.societies import RolePlaying
from owl.utils import OwlRolePlaying, run_society, DocumentProcessingToolkit from owl.utils import run_society, DocumentProcessingToolkit
from camel.logger import set_log_level from camel.logger import set_log_level
@@ -38,7 +39,7 @@ set_log_level(level="DEBUG")
load_dotenv() load_dotenv()
def construct_society(question: str) -> OwlRolePlaying: def construct_society(question: str) -> RolePlaying:
""" """
Construct a society of agents based on the given question. Construct a society of agents based on the given question.
@@ -46,7 +47,7 @@ def construct_society(question: str) -> OwlRolePlaying:
question (str): The task or question to be addressed by the society. question (str): The task or question to be addressed by the society.
Returns: Returns:
OwlRolePlaying: A configured society of agents ready to address the question. RolePlaying: A configured society of agents ready to address the question.
""" """
# Create models for different components # Create models for different components
@@ -118,7 +119,7 @@ def construct_society(question: str) -> OwlRolePlaying:
} }
# Create and return the society # Create and return the society
society = OwlRolePlaying( society = RolePlaying(
**task_kwargs, **task_kwargs,
user_role_name="user", user_role_name="user",
user_agent_kwargs=user_agent_kwargs, user_agent_kwargs=user_agent_kwargs,

View File

@@ -18,26 +18,28 @@ from camel.toolkits import (
SearchToolkit, SearchToolkit,
BrowserToolkit, BrowserToolkit,
FileWriteToolkit, FileWriteToolkit,
TerminalToolkit TerminalToolkit,
) )
from camel.types import ModelPlatformType, ModelType from camel.types import ModelPlatformType, ModelType
from camel.logger import set_log_level from camel.logger import set_log_level
from owl.utils import OwlRolePlaying, run_society from owl.utils import run_society
from camel.societies import RolePlaying
load_dotenv() load_dotenv()
set_log_level(level="DEBUG") set_log_level(level="DEBUG")
# Get current script directory # Get current script directory
base_dir = os.path.dirname(os.path.abspath(__file__)) base_dir = os.path.dirname(os.path.abspath(__file__))
def construct_society(question: str) -> OwlRolePlaying:
def construct_society(question: str) -> RolePlaying:
r"""Construct a society of agents based on the given question. r"""Construct a society of agents based on the given question.
Args: Args:
question (str): The task or question to be addressed by the society. question (str): The task or question to be addressed by the society.
Returns: Returns:
OwlRolePlaying: A configured society of agents ready to address the RolePlaying: A configured society of agents ready to address the
question. question.
""" """
@@ -89,7 +91,7 @@ def construct_society(question: str) -> OwlRolePlaying:
} }
# Create and return the society # Create and return the society
society = OwlRolePlaying( society = RolePlaying(
**task_kwargs, **task_kwargs,
user_role_name="user", user_role_name="user",
user_agent_kwargs=user_agent_kwargs, user_agent_kwargs=user_agent_kwargs,
@@ -113,7 +115,9 @@ def main():
answer, chat_history, token_count = run_society(society) answer, chat_history, token_count = run_society(society)
# Output the result # Output the result
print(f"\033[94mAnswer: {answer}\nChat History: {chat_history}\ntoken_count:{token_count}\033[0m") print(
f"\033[94mAnswer: {answer}\nChat History: {chat_history}\ntoken_count:{token_count}\033[0m"
)
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -18,27 +18,31 @@ from camel.toolkits import (
SearchToolkit, SearchToolkit,
BrowserToolkit, BrowserToolkit,
FileWriteToolkit, FileWriteToolkit,
TerminalToolkit TerminalToolkit,
) )
from camel.types import ModelPlatformType, ModelType from camel.types import ModelPlatformType, ModelType
from camel.logger import set_log_level from camel.logger import set_log_level
from owl.utils import OwlRolePlaying, run_society from owl.utils import run_society
from camel.societies import RolePlaying
import os
load_dotenv() load_dotenv()
set_log_level(level="DEBUG") set_log_level(level="DEBUG")
import os
# Get current script directory # Get current script directory
base_dir = os.path.dirname(os.path.abspath(__file__)) base_dir = os.path.dirname(os.path.abspath(__file__))
def construct_society(question: str) -> OwlRolePlaying:
def construct_society(question: str) -> RolePlaying:
r"""Construct a society of agents based on the given question. r"""Construct a society of agents based on the given question.
Args: Args:
question (str): The task or question to be addressed by the society. question (str): The task or question to be addressed by the society.
Returns: Returns:
OwlRolePlaying: A configured society of agents ready to address the RolePlaying: A configured society of agents ready to address the
question. question.
""" """
@@ -90,7 +94,7 @@ def construct_society(question: str) -> OwlRolePlaying:
} }
# Create and return the society # Create and return the society
society = OwlRolePlaying( society = RolePlaying(
**task_kwargs, **task_kwargs,
user_role_name="user", user_role_name="user",
user_agent_kwargs=user_agent_kwargs, user_agent_kwargs=user_agent_kwargs,
@@ -112,7 +116,9 @@ def main():
answer, chat_history, token_count = run_society(society) answer, chat_history, token_count = run_society(society)
# Output the result # Output the result
print(f"\033[94mAnswer: {answer}\nChat History: {chat_history}\ntoken_count:{token_count}\033[0m") print(
f"\033[94mAnswer: {answer}\nChat History: {chat_history}\ntoken_count:{token_count}\033[0m"
)
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -1,14 +1,25 @@
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
# Import from the correct module path # Import from the correct module path
from owl.utils import run_society from owl.utils import run_society
import os import os
import gradio as gr import gradio as gr
import time from typing import Tuple, List, Dict
import json
from typing import Tuple, List, Dict, Any
import importlib import importlib
from dotenv import load_dotenv, set_key, find_dotenv, unset_key from dotenv import load_dotenv, set_key, find_dotenv, unset_key
os.environ['PYTHONIOENCODING'] = 'utf-8' os.environ["PYTHONIOENCODING"] = "utf-8"
# Enhanced CSS with navigation bar and additional styling # Enhanced CSS with navigation bar and additional styling
custom_css = """ custom_css = """
@@ -250,14 +261,14 @@ button.primary:hover {
# Dictionary containing module descriptions # Dictionary containing module descriptions
MODULE_DESCRIPTIONS = { MODULE_DESCRIPTIONS = {
"run": "默认模式使用OpenAI模型的默认的智能体协作模式适合大多数任务。", "run": "默认模式使用OpenAI模型的默认的智能体协作模式适合大多数任务。",
"run_mini":"使用使用OpenAI模型最小化配置处理任务", "run_mini": "使用使用OpenAI模型最小化配置处理任务",
"run_deepseek_zh":"使用deepseek模型处理中文任务", "run_deepseek_zh": "使用deepseek模型处理中文任务",
"run_terminal_zh": "终端模式可执行命令行操作支持网络搜索、文件处理等功能。适合需要系统交互的任务使用OpenAI模型", "run_terminal_zh": "终端模式可执行命令行操作支持网络搜索、文件处理等功能。适合需要系统交互的任务使用OpenAI模型",
"run_gaia_roleplaying":"GAIA基准测试实现用于评估Agent能力", "run_gaia_roleplaying": "GAIA基准测试实现用于评估Agent能力",
"run_openai_compatiable_model":"使用openai兼容模型处理任务", "run_openai_compatiable_model": "使用openai兼容模型处理任务",
"run_ollama":"使用本地ollama模型处理任务", "run_ollama": "使用本地ollama模型处理任务",
"run_qwen_mini_zh":"使用qwen模型最小化配置处理任务", "run_qwen_mini_zh": "使用qwen模型最小化配置处理任务",
"run_qwen_zh":"使用qwen模型处理任务", "run_qwen_zh": "使用qwen模型处理任务",
} }
# 默认环境变量模板 # 默认环境变量模板
@@ -292,12 +303,13 @@ FIRECRAWL_API_KEY=""
#FIRECRAWL_API_URL="https://api.firecrawl.dev" #FIRECRAWL_API_URL="https://api.firecrawl.dev"
""" """
def format_chat_history(chat_history: List[Dict[str, str]]) -> List[List[str]]: def format_chat_history(chat_history: List[Dict[str, str]]) -> List[List[str]]:
"""将聊天历史格式化为Gradio聊天组件可接受的格式 """将聊天历史格式化为Gradio聊天组件可接受的格式
Args: Args:
chat_history: 原始聊天历史 chat_history: 原始聊天历史
Returns: Returns:
List[List[str]]: 格式化后的聊天历史 List[List[str]]: 格式化后的聊天历史
""" """
@@ -305,22 +317,23 @@ def format_chat_history(chat_history: List[Dict[str, str]]) -> List[List[str]]:
for message in chat_history: for message in chat_history:
user_msg = message.get("user", "") user_msg = message.get("user", "")
assistant_msg = message.get("assistant", "") assistant_msg = message.get("assistant", "")
if user_msg: if user_msg:
formatted_history.append([user_msg, None]) formatted_history.append([user_msg, None])
if assistant_msg and formatted_history: if assistant_msg and formatted_history:
formatted_history[-1][1] = assistant_msg formatted_history[-1][1] = assistant_msg
elif assistant_msg: elif assistant_msg:
formatted_history.append([None, assistant_msg]) formatted_history.append([None, assistant_msg])
return formatted_history return formatted_history
def validate_input(question: str) -> bool: def validate_input(question: str) -> bool:
"""验证用户输入是否有效 """验证用户输入是否有效
Args: Args:
question: 用户问题 question: 用户问题
Returns: Returns:
bool: 输入是否有效 bool: 输入是否有效
""" """
@@ -329,121 +342,111 @@ def validate_input(question: str) -> bool:
return False return False
return True return True
def run_owl(question: str, example_module: str) -> Tuple[str, List[List[str]], str, str]:
def run_owl(
question: str, example_module: str
) -> Tuple[str, List[List[str]], str, str]:
"""运行OWL系统并返回结果 """运行OWL系统并返回结果
Args: Args:
question: 用户问题 question: 用户问题
example_module: 要导入的示例模块名(如 "run_terminal_zh""run_deep" example_module: 要导入的示例模块名(如 "run_terminal_zh""run_deep"
Returns: Returns:
Tuple[...]: 回答、聊天历史、令牌计数、状态 Tuple[...]: 回答、聊天历史、令牌计数、状态
""" """
# 验证输入 # 验证输入
if not validate_input(question): if not validate_input(question):
return ( return ("请输入有效的问题", [], "0", "❌ 错误: 输入无效")
"请输入有效的问题",
[],
"0",
"❌ 错误: 输入无效"
)
try: try:
# 确保环境变量已加载 # 确保环境变量已加载
load_dotenv(find_dotenv(), override=True) load_dotenv(find_dotenv(), override=True)
# 检查模块是否在MODULE_DESCRIPTIONS中 # 检查模块是否在MODULE_DESCRIPTIONS中
if example_module not in MODULE_DESCRIPTIONS: if example_module not in MODULE_DESCRIPTIONS:
return ( return (
f"所选模块 '{example_module}' 不受支持", f"所选模块 '{example_module}' 不受支持",
[], [],
"0", "0",
f"❌ 错误: 不支持的模块" "❌ 错误: 不支持的模块",
) )
# 动态导入目标模块 # 动态导入目标模块
module_path = f"owl.examples.{example_module}" module_path = f"owl.examples.{example_module}"
try: try:
module = importlib.import_module(module_path) module = importlib.import_module(module_path)
except ImportError as ie: except ImportError as ie:
return ( return (
f"无法导入模块: {module_path}", f"无法导入模块: {module_path}",
[], [],
"0", "0",
f"❌ 错误: 模块 {example_module} 不存在或无法加载 - {str(ie)}" f"❌ 错误: 模块 {example_module} 不存在或无法加载 - {str(ie)}",
) )
except Exception as e: except Exception as e:
return ( return (f"导入模块时发生错误: {module_path}", [], "0", f"❌ 错误: {str(e)}")
f"导入模块时发生错误: {module_path}",
[],
"0",
f"❌ 错误: {str(e)}"
)
# 检查是否包含construct_society函数 # 检查是否包含construct_society函数
if not hasattr(module, "construct_society"): if not hasattr(module, "construct_society"):
return ( return (
f"模块 {module_path} 中未找到 construct_society 函数", f"模块 {module_path} 中未找到 construct_society 函数",
[], [],
"0", "0",
f"❌ 错误: 模块接口不兼容" "❌ 错误: 模块接口不兼容",
) )
# 构建社会模拟 # 构建社会模拟
try: try:
society = module.construct_society(question) society = module.construct_society(question)
except Exception as e: except Exception as e:
return ( return (
f"构建社会模拟时发生错误: {str(e)}", f"构建社会模拟时发生错误: {str(e)}",
[], [],
"0", "0",
f"❌ 错误: 构建失败 - {str(e)}" f"❌ 错误: 构建失败 - {str(e)}",
) )
# 运行社会模拟 # 运行社会模拟
try: try:
answer, chat_history, token_info = run_society(society) answer, chat_history, token_info = run_society(society)
except Exception as e: except Exception as e:
return ( return (
f"运行社会模拟时发生错误: {str(e)}", f"运行社会模拟时发生错误: {str(e)}",
[], [],
"0", "0",
f"❌ 错误: 运行失败 - {str(e)}" f"❌ 错误: 运行失败 - {str(e)}",
) )
# 格式化聊天历史 # 格式化聊天历史
try: try:
formatted_chat_history = format_chat_history(chat_history) formatted_chat_history = format_chat_history(chat_history)
except Exception as e: except Exception:
# 如果格式化失败,返回空历史记录但继续处理 # 如果格式化失败,返回空历史记录但继续处理
formatted_chat_history = [] formatted_chat_history = []
# 安全地获取令牌计数 # 安全地获取令牌计数
if not isinstance(token_info, dict): if not isinstance(token_info, dict):
token_info = {} token_info = {}
completion_tokens = token_info.get("completion_token_count", 0) completion_tokens = token_info.get("completion_token_count", 0)
prompt_tokens = token_info.get("prompt_token_count", 0) prompt_tokens = token_info.get("prompt_token_count", 0)
total_tokens = completion_tokens + prompt_tokens total_tokens = completion_tokens + prompt_tokens
return ( return (
answer, answer,
formatted_chat_history, formatted_chat_history,
f"完成令牌: {completion_tokens:,} | 提示令牌: {prompt_tokens:,} | 总计: {total_tokens:,}", f"完成令牌: {completion_tokens:,} | 提示令牌: {prompt_tokens:,} | 总计: {total_tokens:,}",
"✅ 成功完成" "✅ 成功完成",
) )
except Exception as e: except Exception as e:
return ( return (f"发生错误: {str(e)}", [], "0", f"❌ 错误: {str(e)}")
f"发生错误: {str(e)}",
[],
"0",
f"❌ 错误: {str(e)}"
)
def update_module_description(module_name: str) -> str: def update_module_description(module_name: str) -> str:
"""返回所选模块的描述""" """返回所选模块的描述"""
return MODULE_DESCRIPTIONS.get(module_name, "无可用描述") return MODULE_DESCRIPTIONS.get(module_name, "无可用描述")
# 环境变量管理功能 # 环境变量管理功能
def init_env_file(): def init_env_file():
"""初始化.env文件如果不存在""" """初始化.env文件如果不存在"""
@@ -454,11 +457,12 @@ def init_env_file():
dotenv_path = find_dotenv() dotenv_path = find_dotenv()
return dotenv_path return dotenv_path
def load_env_vars(): def load_env_vars():
"""加载环境变量并返回字典格式""" """加载环境变量并返回字典格式"""
dotenv_path = init_env_file() dotenv_path = init_env_file()
load_dotenv(dotenv_path, override=True) load_dotenv(dotenv_path, override=True)
env_vars = {} env_vars = {}
with open(dotenv_path, "r") as f: with open(dotenv_path, "r") as f:
for line in f: for line in f:
@@ -466,79 +470,84 @@ def load_env_vars():
if line and not line.startswith("#"): if line and not line.startswith("#"):
if "=" in line: if "=" in line:
key, value = line.split("=", 1) key, value = line.split("=", 1)
env_vars[key.strip()] = value.strip().strip('"\'') env_vars[key.strip()] = value.strip().strip("\"'")
return env_vars return env_vars
def save_env_vars(env_vars): def save_env_vars(env_vars):
"""保存环境变量到.env文件""" """保存环境变量到.env文件"""
try: try:
dotenv_path = init_env_file() dotenv_path = init_env_file()
# 保存每个环境变量 # 保存每个环境变量
for key, value in env_vars.items(): for key, value in env_vars.items():
if key and key.strip(): # 确保键不为空 if key and key.strip(): # 确保键不为空
set_key(dotenv_path, key.strip(), value.strip()) set_key(dotenv_path, key.strip(), value.strip())
# 重新加载环境变量以确保生效 # 重新加载环境变量以确保生效
load_dotenv(dotenv_path, override=True) load_dotenv(dotenv_path, override=True)
return True, "环境变量已成功保存!" return True, "环境变量已成功保存!"
except Exception as e: except Exception as e:
return False, f"保存环境变量时出错: {str(e)}" return False, f"保存环境变量时出错: {str(e)}"
def add_env_var(key, value): def add_env_var(key, value):
"""添加或更新单个环境变量""" """添加或更新单个环境变量"""
try: try:
if not key or not key.strip(): if not key or not key.strip():
return False, "变量名不能为空" return False, "变量名不能为空"
dotenv_path = init_env_file() dotenv_path = init_env_file()
set_key(dotenv_path, key.strip(), value.strip()) set_key(dotenv_path, key.strip(), value.strip())
load_dotenv(dotenv_path, override=True) load_dotenv(dotenv_path, override=True)
return True, f"环境变量 {key} 已成功添加/更新!" return True, f"环境变量 {key} 已成功添加/更新!"
except Exception as e: except Exception as e:
return False, f"添加环境变量时出错: {str(e)}" return False, f"添加环境变量时出错: {str(e)}"
def delete_env_var(key): def delete_env_var(key):
"""删除环境变量""" """删除环境变量"""
try: try:
if not key or not key.strip(): if not key or not key.strip():
return False, "变量名不能为空" return False, "变量名不能为空"
dotenv_path = init_env_file() dotenv_path = init_env_file()
unset_key(dotenv_path, key.strip()) unset_key(dotenv_path, key.strip())
# 从当前进程环境中也删除 # 从当前进程环境中也删除
if key in os.environ: if key in os.environ:
del os.environ[key] del os.environ[key]
return True, f"环境变量 {key} 已成功删除!" return True, f"环境变量 {key} 已成功删除!"
except Exception as e: except Exception as e:
return False, f"删除环境变量时出错: {str(e)}" return False, f"删除环境变量时出错: {str(e)}"
def mask_sensitive_value(key: str, value: str) -> str: def mask_sensitive_value(key: str, value: str) -> str:
"""对敏感信息进行掩码处理 """对敏感信息进行掩码处理
Args: Args:
key: 环境变量名 key: 环境变量名
value: 环境变量值 value: 环境变量值
Returns: Returns:
str: 处理后的值 str: 处理后的值
""" """
# 定义需要掩码的敏感关键词 # 定义需要掩码的敏感关键词
sensitive_keywords = ['key', 'token', 'secret', 'password', 'api'] sensitive_keywords = ["key", "token", "secret", "password", "api"]
# 检查是否包含敏感关键词(不区分大小写) # 检查是否包含敏感关键词(不区分大小写)
is_sensitive = any(keyword in key.lower() for keyword in sensitive_keywords) is_sensitive = any(keyword in key.lower() for keyword in sensitive_keywords)
if is_sensitive and value: if is_sensitive and value:
# 如果是敏感信息且有值,则显示掩码 # 如果是敏感信息且有值,则显示掩码
return '*' * 8 return "*" * 8
return value return value
def update_env_table(): def update_env_table():
"""更新环境变量表格显示,对敏感信息进行掩码处理""" """更新环境变量表格显示,对敏感信息进行掩码处理"""
env_vars = load_env_vars() env_vars = load_env_vars()
@@ -546,6 +555,7 @@ def update_env_table():
masked_env_vars = [[k, mask_sensitive_value(k, v)] for k, v in env_vars.items()] masked_env_vars = [[k, mask_sensitive_value(k, v)] for k, v in env_vars.items()]
return masked_env_vars return masked_env_vars
def create_ui(): def create_ui():
"""创建增强版Gradio界面""" """创建增强版Gradio界面"""
with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="blue")) as app: with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="blue")) as app:
@@ -569,7 +579,7 @@ def create_ui():
<p>我们的愿景是彻底改变AI代理协作解决现实世界任务的方式。通过利用动态代理交互OWL能够在多个领域实现更自然、高效和稳健的任务自动化。</p> <p>我们的愿景是彻底改变AI代理协作解决现实世界任务的方式。通过利用动态代理交互OWL能够在多个领域实现更自然、高效和稳健的任务自动化。</p>
</div> </div>
""") """)
with gr.Row(elem_id="features"): with gr.Row(elem_id="features"):
gr.HTML(""" gr.HTML("""
<div class="features-section"> <div class="features-section">
@@ -610,7 +620,7 @@ def create_ui():
</div> </div>
</div> </div>
""") """)
with gr.Row(): with gr.Row():
with gr.Column(scale=2): with gr.Column(scale=2):
question_input = gr.Textbox( question_input = gr.Textbox(
@@ -620,26 +630,28 @@ def create_ui():
elem_id="question_input", elem_id="question_input",
show_copy_button=True, show_copy_button=True,
) )
# 增强版模块选择下拉菜单 # 增强版模块选择下拉菜单
# 只包含MODULE_DESCRIPTIONS中定义的模块 # 只包含MODULE_DESCRIPTIONS中定义的模块
module_dropdown = gr.Dropdown( module_dropdown = gr.Dropdown(
choices=list(MODULE_DESCRIPTIONS.keys()), choices=list(MODULE_DESCRIPTIONS.keys()),
value="run_terminal_zh", value="run_terminal_zh",
label="选择功能模块", label="选择功能模块",
interactive=True interactive=True,
) )
# 模块描述文本框 # 模块描述文本框
module_description = gr.Textbox( module_description = gr.Textbox(
value=MODULE_DESCRIPTIONS["run_terminal_zh"], value=MODULE_DESCRIPTIONS["run_terminal_zh"],
label="模块描述", label="模块描述",
interactive=False, interactive=False,
elem_classes="module-info" elem_classes="module-info",
) )
run_button = gr.Button("运行", variant="primary", elem_classes="primary") run_button = gr.Button(
"运行", variant="primary", elem_classes="primary"
)
with gr.Column(scale=1): with gr.Column(scale=1):
gr.Markdown(""" gr.Markdown("""
### 使用指南 ### 使用指南
@@ -651,127 +663,103 @@ def create_ui():
> **高级提示**: 对于复杂任务,可以尝试指定具体步骤和预期结果 > **高级提示**: 对于复杂任务,可以尝试指定具体步骤和预期结果
""") """)
status_output = gr.Textbox(label="状态", interactive=False) status_output = gr.Textbox(label="状态", interactive=False)
with gr.Tabs(): with gr.Tabs():
with gr.TabItem("回答"): with gr.TabItem("回答"):
answer_output = gr.Textbox( answer_output = gr.Textbox(
label="回答", label="回答", lines=10, elem_classes="answer-box"
lines=10,
elem_classes="answer-box"
) )
with gr.TabItem("对话历史"): with gr.TabItem("对话历史"):
chat_output = gr.Chatbot( chat_output = gr.Chatbot(
label="完整对话记录", label="完整对话记录", elem_classes="chat-container", height=500
elem_classes="chat-container",
height=500
) )
token_count_output = gr.Textbox( token_count_output = gr.Textbox(
label="令牌计数", label="令牌计数", interactive=False, elem_classes="token-count"
interactive=False,
elem_classes="token-count"
) )
# 示例问题 # 示例问题
examples = [ examples = [
"打开百度搜索总结一下camel-ai的camel框架的github star、fork数目等并把数字用plot包写成python文件保存到本地用本地终端执行python文件显示图出来给我", "打开百度搜索总结一下camel-ai的camel框架的github star、fork数目等并把数字用plot包写成python文件保存到本地用本地终端执行python文件显示图出来给我",
"请分析GitHub上CAMEL-AI项目的最新统计数据。找出该项目的星标数量、贡献者数量和最近的活跃度。", "请分析GitHub上CAMEL-AI项目的最新统计数据。找出该项目的星标数量、贡献者数量和最近的活跃度。",
"浏览亚马逊并找出一款对程序员有吸引力的产品。请提供产品名称和价格", "浏览亚马逊并找出一款对程序员有吸引力的产品。请提供产品名称和价格",
"写一个hello world的python文件保存到本地", "写一个hello world的python文件保存到本地",
] ]
gr.Examples( gr.Examples(examples=examples, inputs=question_input)
examples=examples,
inputs=question_input
)
# 新增: 环境变量管理选项卡 # 新增: 环境变量管理选项卡
with gr.TabItem("环境变量管理", id="env-settings"): with gr.TabItem("环境变量管理", id="env-settings"):
gr.Markdown(""" gr.Markdown("""
## 环境变量管理 ## 环境变量管理
在此处设置模型API密钥和其他服务凭证。这些信息将保存在本地的`.env`文件中确保您的API密钥安全存储且不会上传到网络。 在此处设置模型API密钥和其他服务凭证。这些信息将保存在本地的`.env`文件中确保您的API密钥安全存储且不会上传到网络。
""") """)
# 环境变量表格
env_table = gr.Dataframe(
headers=["变量名", ""],
datatype=["str", "str"],
row_count=10,
col_count=(2, "fixed"),
value=update_env_table,
label="当前环境变量",
interactive=False
)
with gr.Row():
with gr.Column(scale=1):
new_env_key = gr.Textbox(label="变量名", placeholder="例如: OPENAI_API_KEY")
with gr.Column(scale=2):
new_env_value = gr.Textbox(label="", placeholder="输入API密钥或其他配置值")
with gr.Row():
add_env_button = gr.Button("添加/更新变量", variant="primary")
refresh_button = gr.Button("刷新变量列表")
delete_env_button = gr.Button("删除选定变量", variant="stop")
env_status = gr.Textbox(label="状态", interactive=False)
# 变量选择器(用于删除)
env_var_to_delete = gr.Dropdown(
choices=[],
label="选择要删除的变量",
interactive=True
)
# 更新变量选择器的选项
def update_delete_dropdown():
env_vars = load_env_vars()
return gr.Dropdown.update(choices=list(env_vars.keys()))
# 连接事件处理函数
add_env_button.click(
fn=lambda k, v: add_env_var(k, v),
inputs=[new_env_key, new_env_value],
outputs=[env_status]
).then(
fn=update_env_table,
outputs=[env_table]
).then(
fn=update_delete_dropdown,
outputs=[env_var_to_delete]
).then(
fn=lambda: ("", ""), # 修改为返回两个空字符串的元组
outputs=[new_env_key, new_env_value]
)
refresh_button.click(
fn=update_env_table,
outputs=[env_table]
).then(
fn=update_delete_dropdown,
outputs=[env_var_to_delete]
)
delete_env_button.click(
fn=lambda k: delete_env_var(k),
inputs=[env_var_to_delete],
outputs=[env_status]
).then(
fn=update_env_table,
outputs=[env_table]
).then(
fn=update_delete_dropdown,
outputs=[env_var_to_delete]
)
# 环境变量表格
env_table = gr.Dataframe(
headers=["变量名", ""],
datatype=["str", "str"],
row_count=10,
col_count=(2, "fixed"),
value=update_env_table,
label="当前环境变量",
interactive=False,
)
with gr.Row():
with gr.Column(scale=1):
new_env_key = gr.Textbox(
label="变量名", placeholder="例如: OPENAI_API_KEY"
)
with gr.Column(scale=2):
new_env_value = gr.Textbox(
label="", placeholder="输入API密钥或其他配置值"
)
with gr.Row():
add_env_button = gr.Button("添加/更新变量", variant="primary")
refresh_button = gr.Button("刷新变量列表")
delete_env_button = gr.Button("删除选定变量", variant="stop")
env_status = gr.Textbox(label="状态", interactive=False)
# 变量选择器(用于删除)
env_var_to_delete = gr.Dropdown(
choices=[], label="选择要删除的变量", interactive=True
)
# 更新变量选择器的选项
def update_delete_dropdown():
env_vars = load_env_vars()
return gr.Dropdown.update(choices=list(env_vars.keys()))
# 连接事件处理函数
add_env_button.click(
fn=lambda k, v: add_env_var(k, v),
inputs=[new_env_key, new_env_value],
outputs=[env_status],
).then(fn=update_env_table, outputs=[env_table]).then(
fn=update_delete_dropdown, outputs=[env_var_to_delete]
).then(
fn=lambda: ("", ""), # 修改为返回两个空字符串的元组
outputs=[new_env_key, new_env_value],
)
refresh_button.click(fn=update_env_table, outputs=[env_table]).then(
fn=update_delete_dropdown, outputs=[env_var_to_delete]
)
delete_env_button.click(
fn=lambda k: delete_env_var(k),
inputs=[env_var_to_delete],
outputs=[env_status],
).then(fn=update_env_table, outputs=[env_table]).then(
fn=update_delete_dropdown, outputs=[env_var_to_delete]
)
gr.HTML(""" gr.HTML("""
<div class="footer" id="about"> <div class="footer" id="about">
<h3>关于 OWL 多智能体协作系统</h3> <h3>关于 OWL 多智能体协作系统</h3>
@@ -780,23 +768,24 @@ def create_ui():
<p><a href="https://github.com/camel-ai/owl" target="_blank">GitHub</a></p> <p><a href="https://github.com/camel-ai/owl" target="_blank">GitHub</a></p>
</div> </div>
""") """)
# 设置事件处理 # 设置事件处理
run_button.click( run_button.click(
fn=run_owl, fn=run_owl,
inputs=[question_input, module_dropdown], inputs=[question_input, module_dropdown],
outputs=[answer_output, chat_output, token_count_output, status_output] outputs=[answer_output, chat_output, token_count_output, status_output],
) )
# 模块选择更新描述 # 模块选择更新描述
module_dropdown.change( module_dropdown.change(
fn=update_module_description, fn=update_module_description,
inputs=module_dropdown, inputs=module_dropdown,
outputs=module_description outputs=module_description,
) )
return app return app
# 主函数 # 主函数
def main(): def main():
try: try:
@@ -807,7 +796,9 @@ def main():
except Exception as e: except Exception as e:
print(f"启动应用程序时发生错误: {str(e)}") print(f"启动应用程序时发生错误: {str(e)}")
import traceback import traceback
traceback.print_exc() traceback.print_exc()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@@ -381,6 +381,12 @@ Now please give me instructions to solve over overall task step by step. If the
""" """
input_msg = society.init_chat(init_prompt) input_msg = society.init_chat(init_prompt)
for _round in range(round_limit): for _round in range(round_limit):
# Check if previous user response had TASK_DONE before getting next assistant response
if _round > 0 and (
"TASK_DONE" in input_msg.content or "任务已完成" in input_msg.content
):
break
assistant_response, user_response = society.step(input_msg) assistant_response, user_response = society.step(input_msg)
overall_completion_token_count += ( overall_completion_token_count += (
assistant_response.info["usage"]["completion_tokens"] assistant_response.info["usage"]["completion_tokens"]
@@ -408,10 +414,12 @@ Now please give me instructions to solve over overall task step by step. If the
f"Round #{_round} assistant_response:\n {assistant_response.msgs[0].content}" f"Round #{_round} assistant_response:\n {assistant_response.msgs[0].content}"
) )
# Check other termination conditions
if ( if (
assistant_response.terminated assistant_response.terminated
or user_response.terminated or user_response.terminated
or "TASK_DONE" in user_response.msg.content or "TASK_DONE" in user_response.msg.content
or "任务已完成" in user_response.msg.content
): ):
break break

File diff suppressed because it is too large Load Diff

View File

@@ -21,7 +21,7 @@ keywords = [
"learning-systems" "learning-systems"
] ]
dependencies = [ dependencies = [
"camel-ai[all]==0.2.27", "camel-ai[all]==0.2.30",
"chunkr-ai>=0.0.41", "chunkr-ai>=0.0.41",
"docx2markdown>=0.1.1", "docx2markdown>=0.1.1",
"gradio>=3.50.2", "gradio>=3.50.2",

View File

@@ -1,4 +1,4 @@
camel-ai[all]==0.2.27 camel-ai[all]==0.2.30
chunkr-ai>=0.0.41 chunkr-ai>=0.0.41
docx2markdown>=0.1.1 docx2markdown>=0.1.1
gradio>=3.50.2 gradio>=3.50.2

8
uv.lock generated
View File

@@ -482,7 +482,7 @@ wheels = [
[[package]] [[package]]
name = "camel-ai" name = "camel-ai"
version = "0.2.27" version = "0.2.30"
source = { registry = "https://pypi.org/simple" } source = { registry = "https://pypi.org/simple" }
dependencies = [ dependencies = [
{ name = "colorama" }, { name = "colorama" },
@@ -499,9 +499,9 @@ dependencies = [
{ name = "pyyaml" }, { name = "pyyaml" },
{ name = "tiktoken" }, { name = "tiktoken" },
] ]
sdist = { url = "https://files.pythonhosted.org/packages/ff/27/2bce666ae7f7d0db276d037b3afe84a460e782438e5cacc08de20417233b/camel_ai-0.2.27.tar.gz", hash = "sha256:4689245ad48f51e5e602d2651cf463afe212bcf046633a19c2189574c1f3481a", size = 441363 } sdist = { url = "https://files.pythonhosted.org/packages/ef/86/57cbcae86d2d60dab0aad31b5302525c75f45ff5edc3c3819a378fa9e12c/camel_ai-0.2.30.tar.gz", hash = "sha256:e1639376e70e9cf1477eca88d1bdc1813855cbd1db683528e1f93027b6aa0b0a", size = 442842 }
wheels = [ wheels = [
{ url = "https://files.pythonhosted.org/packages/b0/fa/94f5b41cb6babc81aac00494b170ec2bea058b6c00f477ceb3e886c49177/camel_ai-0.2.27-py3-none-any.whl", hash = "sha256:c4a6597791faf2f2161c56c2579e60850557b126135b29af77ebd08fa0774e0b", size = 746387 }, { url = "https://files.pythonhosted.org/packages/85/fe/8f1d17896aedbc9e0dfa1bff40d560e5a6808d9b727e04c293be6be5954f/camel_ai-0.2.30-py3-none-any.whl", hash = "sha256:e09eec860331cdb4da4e49f46f5d45345a81820c5847556fdf9e7827dd9bbfa9", size = 752672 },
] ]
[package.optional-dependencies] [package.optional-dependencies]
@@ -3575,7 +3575,7 @@ dependencies = [
[package.metadata] [package.metadata]
requires-dist = [ requires-dist = [
{ name = "camel-ai", extras = ["all"], specifier = "==0.2.27" }, { name = "camel-ai", extras = ["all"], specifier = "==0.2.30" },
{ name = "chunkr-ai", specifier = ">=0.0.41" }, { name = "chunkr-ai", specifier = ">=0.0.41" },
{ name = "docx2markdown", specifier = ">=0.1.1" }, { name = "docx2markdown", specifier = ">=0.1.1" },
{ name = "gradio", specifier = ">=3.50.2" }, { name = "gradio", specifier = ">=3.50.2" },