Agent_camel框架学习记录(2)


原作者链接🔗:https://fmhw1n4zpn.feishu.cn/docx/AF4XdOZpIo6TOaxzDK8cxInNnCe

2.3.3 使用开源模型:Ollama

Ollama 是一个开源机器学习框架,专注于让用户轻松使用语言模型。它基于 llama.cpp 实现,支持 CPU/GPU 推理,并兼容 OpenAI 接口。

安装与使用 Qwen2.5

1
ollama pull qwen2.5:7b

模型加载方式:

1
2
3
4
5
6
7
8
from camel.models import ModelFactory
from camel.types import ModelPlatformType

model = ModelFactory.create(
model_platform=ModelPlatformType.OLLAMA,
model_type="qwen2.5",
model_config_dict={"temperature": 0.4},
)

自行构建的qwen2.5:7b模型下的多行问答Agent:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from camel.agents import ChatAgent
from camel.models import ModelFactory
from camel.types import ModelPlatformType
import sys
from camel.messages import BaseMessage

model = ModelFactory.create(
model_platform=ModelPlatformType.OLLAMA,
model_type="qwen2.5:7b", # Use the model name displayed in 'ollama list'
model_config_dict={
"temperature": 0.4,
},
url="http://localhost:11434/v1/"
)

agent = ChatAgent(
model=model,
output_language='中文'
)

print("与 CAMEL 代理开始对话 (输入 '退出' 结束):")

while True:
print("你: (输入多行内容,空行结束)")
user_input_lines = []
while True:
line = input()
if line.lower() == '退出':
print("对话结束。")
sys.exit() # 完全退出程序
if not line.strip(): # 空行结束输入
break
user_input_lines.append(line)

if user_input_lines: # 如果有输入内容
user_input = '\n'.join(user_input_lines)
else:
continue # 空输入则重新开始循环

# Create a BaseMessage from user input
user_msg = BaseMessage.make_user_message(
role_name="User",
content=user_input
)

# Get model response
response = agent.step(user_msg)
if response and response.msgs:
print(f"代理: {response.msgs[0].content}")
else:
print("代理: 未收到有效回复。")

2.4.3 BaseMessage 消息处理

1
2
3
4
5
6
7
8
9
10
11
12
from camel.messages import BaseMessage

# 创建消息
user_msg = BaseMessage.make_user_message(role_name="User_1", content="Hi")
assistant_msg = BaseMessage.make_assistant_message(role_name="Assistant_1", content="Hello!")

# 更新消息内容
updated_msg = user_msg.create_new_instance("Hi, tell me more about CAMEL")

# 转换为 OpenAI 消息格式
from camel.types import OpenAIBackendRole
openai_msg = user_msg.to_openai_message(role_at_backend=OpenAIBackendRole.USER)

通过BassMessage实现Agent处理图片/视频等多模态信息:
首先展示本地图片的多模态理解示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from camel.agents import ChatAgent
from camel.models import ModelFactory
from camel.types import ModelPlatformType
from camel.messages import BaseMessage

from io import BytesIO
import requests
from PIL import Image

from dotenv import load_dotenv
import os

# 加载环境变量
load_dotenv(dotenv_path='.env') # 确保.env文件存在且路径正确
api_key = os.getenv('MODELSCOPE_SDK_TOKEN') # 使用环境变量获取密钥

model = ModelFactory.create(
model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
model_type="Qwen/Qwen2.5-VL-72B-Instruct",
api_key=api_key,
url=os.environ.get("OPENAI_COMPATIBILIY_API_BASE_URL", "https://api-inference.modelscope.cn/v1/"), # 环境变量优先,不存在则使用默认值
model_config_dict={"temperature": 0.4, "max_tokens": 4096},
)

# 实例化ChatAgent
agent = ChatAgent(model=model,output_language='中文')

# 本地图片
image_path = "微信图片_2025-07-11_223853_723.jpg"
img = Image.open(image_path) # 直接打开图片文件

user_msg = BaseMessage.make_user_message(
role_name="User",
content="请描述这张图片的内容",
image_list=[img] # 使用image_list参数传入PIL.Image对象列表
)

response = agent.step(user_msg) # 1. 将包含图片的用户消息发送给AI代理
print(response.msgs[0].content) # 2. 打印AI代理的回复内容

图片示例

以上的图片示例运行后的结果:

1
2
PS D:\Camel_Test_Project> & D:/Download/Python/py-3.11.9/python.exe d:/Camel_Test_Project/Multimodal_images.py      
这张图片显示了一位正在打羽毛球的人。他穿着黑色的T恤和红色的短裤,脚上穿着白色的运动鞋。他的右手持着羽毛球拍,似乎在准备击球或刚刚完成一次击球动作。背景是一个室内羽毛球场地,可以看到彩色的观 众席和一些放置在地上的物品,如背包和鞋子。场地的地面是绿色的,标有白色的线条,用于划分比赛区域

2.4.4 与 ChatAgent 协作

1
2
3
4
from camel.agents import ChatAgent
chat_agent = ChatAgent(model=model, system_message="You are a helpful assistant", output_language='zh')
response = chat_agent.step("介绍一下 CAMEL AI")
print(response.msgs[0].content)

2.5.3 上下文学习 (ICL)

ICL 通过上下文中的示例(Few-shot/One-shot/Zero-shot)指导模型生成答案。

1
2
3
4
5
6
英文转法文任务示例:
Translate English to French.
apple -> pomme
car -> voiture
cat -> chat
dog ->

2.5.4 思维链 (CoT)

通过逐步展示推理过程提升模型表现:

1
2
Q: Roger 有 5 个网球,他又买了 2 罐,每罐 3 个,共多少?
A: 他有 5 + 2*3 = 11 个网球。

2.5.5 使用 CAMEL 的 Prompt

使用 TaskSpecifyAgent 创建特定任务提示:

1
2
3
4
5
6
7
8
9
10
from camel.agents import TaskSpecifyAgent

task_specify_agent = TaskSpecifyAgent(
model=model, task_type=TaskType.AI_SOCIETY, output_language='中文'
)
response = task_specify_agent.run(
task_prompt="get promotion",
meta_dict=dict(assistant_role="Engineer", user_role="Employee", word_limit=100)
)
print(response)

使用 TextPrompt 自定义模板:

1
2
3
4
from camel.prompts import TextPrompt
prompt = TextPrompt('Hi {name}, you are {age} years old.')
formatted = prompt.format(name="John", age=30)
print(formatted) # Hi John, you are 30 years old.

更多见官方文档:https://github.com/camel-ai/camel

2.6Memory记忆系统

CAMEL AI 记忆系统集成操作流程

  1. 理论基础
    1.1 CAMEL 记忆存储机制

Key-Value 存储: 简单键值对存储,适合结构化数据
Graph 存储: 图数据库存储,适合关系型数据
Vector 存储: 向量数据库存储,适合语义检索

1.2 核心数据结构

Chat_history: 规范化存储智能体对话记录
Context: 从 chat_history 中提取的上下文信息
权重机制: 基于重要性评分筛选关键信息

1.3 工作原理
大模型基于预测机制生成文本,通过权重筛选从历史记录中获取有效上下文,确保在 token 限制内提供最重要的信息。
2. 环境准备以及记忆系统构建初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from camel.memories import (
LongtermAgentMemory,#核心记忆管理器,负责存储和检索对话历史
MemoryRecord,
ScoreBasedContextCreator,#基于评分的上下文创建器
ChatHistoryBlock,#存储聊天历史记录的数据块
VectorDBBlock,#向量数据库块
)
#载入基础配置
from camel.messages import BaseMessage
from camel.types import ModelType, OpenAIBackendRole
from camel.utils import OpenAITokenCounter
from camel.embeddings import SentenceTransformerEncoder
from camel.agents import ChatAgent
from camel.models import ModelFactory
from camel.types import ModelPlatformType

#载入环境配置
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv('MODELSCOPE_SDK_TOKEN')

#初始化记忆系统
memory = LongtermAgentMemory(
context_creator=ScoreBasedContextCreator(
token_counter=OpenAITokenCounter(ModelType.GPT_4O_MINI),
token_limit=1024, # 使用 token 计数器限制上下文长度(1024 tokens)
),
chat_history_block=ChatHistoryBlock(), # 聊天历史存储
vector_db_block=VectorDBBlock(
embedding=SentenceTransformerEncoder(model_name="BAAI/bge-m3")
), # 向量数据库存储,使用 BGE-M3 模型进行文本嵌入
)

#创建记忆记录
records = [
MemoryRecord(
message=BaseMessage.make_user_message(
role_name="User",
content="什么是CAMEL AI?"
),
role_at_backend=OpenAIBackendRole.USER,
),
MemoryRecord(
message=BaseMessage.make_assistant_message(
role_name="Agent",
content="CAMEL-AI是第一个LLM多智能体框架,并且是一个致力于寻找智能体 scaling law 的开源社区。"
),
role_at_backend=OpenAIBackendRole.ASSISTANT,
),
]

#写入记忆数据
memory.write_records(records)

#验证记忆系统
context, token_count = memory.get_context()
print(f"上下文: {context}")
print(f"Token 消耗: {token_count}")


###创建基础智能体
# 定义系统消息
sys_msg = "你是一个好奇的智能体,正在探索宇宙的奥秘。"

# 初始化模型
model = ModelFactory.create(
model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
model_type="Qwen/Qwen2.5-72B-Instruct",
url='https://api-inference.modelscope.cn/v1/',
api_key=api_key
)

# 创建智能体
agent = ChatAgent(system_message=sys_msg, model=model)

###测试无记忆状态
usr_msg = "告诉我基于我们讨论的内容,哪个是第一个LLM多智能体框架?"
response = agent.step(usr_msg)
print("无记忆状态响应:", response.msgs[0].content)

关键组件说明:
ScoreBasedContextCreator: 基于评分的上下文创建器
ChatHistoryBlock: 聊天记录存储块
VectorDBBlock: 向量数据库块,支持语义检索

  1. 测试无记忆状态的输出结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
PS D:\Camel_Test_Project> & D:/Download/Python/py-3.11.9/python.exe d:/Camel_Test_Project/test_Memory_all.py
W0715 11:51:47.852000 17616 site-packages\torch\distributed\elastic\multiprocessing\redirects.py:29] NOTE: Redirects are currently not supported in Windows or MacOs.
上下文: [{'role': 'user', 'content': '什么是CAMEL AI?'}, {'role': 'assistant', 'content': 'CAMEL-AI是第一个LLM多智能体框架,并且是一个致力于寻找智能体 scaling law 的开源社区。'}]
Token 消耗: 52
无记忆状态响应: 目前,关于“第一个LLM(大语言模型)多智能体框架”的确切定义和时间点可能存在一定的模糊性,因为这一领域的发展非常迅速,而且不同的项目和研究可能从不同的角度来定义“多智能体框架”。 然而,可以提到一些较早的、具有代表性的项目,它们在大语言模型与多智能体系统结合方面进行了开创性的工作。

**Multi-Agent Systems with Large Language Models (LLMs)**: 虽然很难确定一个具体的“第一”,但 可以指出的是,随着大语言模型如GPT-3等的出现,研究人员开始探索将这些模型应用于多智能体系统中。例如,2021年左右,一些研究团队开始尝试使用大语言模型作为智能体之间的通信工具,或者作为增强单个智 能体决策能力的方法。
**ReAct for Multi-Agent Collaboration**: 2022年,来自斯坦福大学的研究者提出了一种名为ReAct的方法,它利用大型预训练语言模型来促进多智能体协作。这个框架展示了如何通过自然语言处理技术让智能 体之间进行更有效的沟通与合作,被认为是该领域的早期重要贡献之一。
**ReAct for Multi-Agent Collaboration**: 2022年,来自斯坦福大学的研究者提出了一种名为ReAct的方法,它利用大型预训练语言模型来促进多智能体协作。这个框架展示了如何通过自然语言处理技术让智能
**ReAct for Multi-Agent Collaboration**: 2022年,来自斯坦福大学的研究者提出了一种名为ReAct的
**ReAct for Multi-Agent Collaboration**: 2022年,来自斯坦福大学的研究者提出了一种名为ReAct的方法,它利用大型预训练语言模型来促进多智能体协作。这个框架展示了如何通过自然语言处理技术让智能
**ReAct for Multi-Agent Collaboration**: 2022年,来自斯坦福大学的研究者提出了一种名为ReAct的
**ReAct for Multi-Agent Collaboration**: 2022年,来自斯坦福大学的研究者提出了一种名为ReAct的方法,它利用大型预训练语言模型来促进多智能体协作。这个框架展示了如何通过自然语言处理技术让智能 体之间进行更有效的沟通与合作,被认为是该领域的早期重要贡献之一。
**ReAct for Multi-Agent Collaboration**: 2022年,来自斯坦福大学的研究者提出了一种名为ReAct的方法,它利用大型预训练语言模型来促进多智能体协作。这个框架展示了如何通过自然语言处理技术让智能 体之间进行更有效的沟通与合作,被认为是该领域的早期重要贡献之一。
方法,它利用大型预训练语言模型来促进多智能体协作。这个框架展示了如何通过自然语言处理技术让智能体之间进行更有效的沟通与合作,被认为是该领域的早期重要贡献之一。

需要注意的是,上述信息基于当前可获得的数据,并且随着新研究的不断涌现,这一领域的先驱者可能会有 所变化。如果你有特定的研究或项目想要了解,请提供更多信息,我将尽力为你提供详细的答案。
  1. 记忆系统集成
    4.1 集成记忆到智能体
    python# 关键步骤:将记忆系统赋值给智能体
    agent.memory = memory
    4.2 测试集成效果
    python# 使用相同的问题测试
    response = agent.step(usr_msg)
    print(“集成记忆后响应:”, response.msgs[0].content)

5.测试结果,成功响应:

1
集成记忆后响应: CAMEL-AI 是一个专注于研究和开发大规模语言模型(LLM)在多智能体系统中应用的框架 。它旨在通过构建和实验不同的多智能体交互模式,来探索和理解智能体之间的协作、竞争以及这些互动如 何影响整体系统的性能和效率。根据您的问题,CAMEL-AI 被认为是第一个LLM多智能体框架。这个框架不仅 促进了对智能体 scaling law 的研究,还为研究人员和开发者提供了一个开放平台,以测试新的算法和理论。

2.7 Tools 工具系统

2.7.1 工具说明

工具(Tools)是大语言模型(LLM)与外部世界交互的桥梁。虽然 LLM 拥有强大的语言理解与生成能力,但它本质上是一个“封闭系统”,无法直接:

  • 获取实时信息(如天气、新闻)
  • 访问外部数据(如数据库、文件)
  • 执行具体操作(如发送邮件、控制设备)

为克服这些局限,CAMEL 提供了“工具”机制,使模型能够:

  • 通过 API 获取实时数据
  • 调用外部服务
  • 执行特定任务
  • 与其他系统交互

✅ 工具的本质是一个带有名称、描述、输入参数与输出类型的 函数接口

CAMEL 支持:

  • 内置工具
  • 自定义工具
  • 工具包(Toolkit)

2.7.2 动手实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from camel.agents import ChatAgent
from camel.models import ModelFactory
from camel.types import ModelPlatformType
import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.getenv('MODELSCOPE_SDK_TOKEN')

# 初始化模型
model = ModelFactory.create(
model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
model_type="Qwen/Qwen2.5-72B-Instruct",
url='https://api-inference.modelscope.cn/v1/',
api_key=api_key
)

# 初始化 ChatAgent(未配工具)
agent = ChatAgent(
system_message="你是一个数学大师,擅长各种数学问题。",
model=model,
output_language='中文',
tools=[]
)

# 定义用户消息发送消息给agent
usr_msg = "2的平方根是多少?"
response = agent.step(usr_msg)
print(response.msgs[0].content)

输出约为:2的平方根是 1.414

可以看到模型给出了回答,但是精度不够。我们需要更高的精度,现在创建自定义函数工具:

使用FunctionTool

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from camel.toolkits import FunctionTool
import math

def calculate_sqrt(x: float) -> float:
r"""计算一个数的平方根。

Args:
x (float): 需要计算平方根的数字。

Returns:
float: 输入数字的平方根。
"""
return math.sqrt(x)

# 用 FunctionTool 包装该函数
sqrt_tool = FunctionTool(calculate_sqrt)

# 创建带工具的 agent
agent = ChatAgent(
system_message="你是一个数学大师,遇到数学问题你要调用工具。",
model=model,
output_language='中文',
tools=[sqrt_tool]
)

response = agent.step("2的平方根是多少?")
print(response.msgs[0].content)
print(response.info["tool_calls"])

2.7.3 进阶案例:AI Society + 工具系统

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from camel.toolkits import SearchToolkit, MathToolkit
from camel.societies import RolePlaying
from camel.types.agents import ToolCallingRecord
from camel.models import ModelFactory
from camel.types import ModelPlatformType
from colorama import Fore
import os
from dotenv import load_dotenv

# 环境配置
load_dotenv()
api_key = os.getenv('MODELSCOPE_SDK_TOKEN')

# 创建模型
model = ModelFactory.create(
model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
model_type="Qwen/Qwen2.5-72B-Instruct",
url='https://api-inference.modelscope.cn/v1/',
api_key=api_key
)

# 定义工具包
tools_list = [
*SearchToolkit().get_tools(),
*MathToolkit().get_tools()
]

# 设置任务
task_prompt = ("假设现在是2024年,牛津大学的成立年份,并计算出其当前年龄。"
"然后再将这个年龄加上10年。使用百度搜索工具。")

# 设置角色扮演
role_play_session = RolePlaying(
assistant_role_name="搜索者",
user_role_name="教授",
assistant_agent_kwargs=dict(model=model, tools=tools_list),
user_agent_kwargs=dict(model=model),
task_prompt=task_prompt,
with_task_specify=False,
output_language='中文'
)

# 初始化对话
input_msg = role_play_session.init_chat()

# 改进的对话循环 - 添加安全机制
max_turns = 10
turn_count = 0

print(Fore.CYAN + f"开始执行任务: {task_prompt}\n")
print(Fore.YELLOW + "=" * 60)

while turn_count < max_turns:
try:
assistant_response, user_response = role_play_session.step(input_msg)

# 简化但必要的输出
print(Fore.WHITE + f"\n[Turn {turn_count + 1}]")
print(Fore.GREEN + f"助手: {assistant_response.msg.content}")
print(Fore.BLUE + f"用户: {user_response.msg.content}")

# 显示工具调用信息
if assistant_response.info['tool_calls']:
print(Fore.MAGENTA + f"工具调用: {assistant_response.info['tool_calls']}")

# 检查终止条件
if assistant_response.terminated or user_response.terminated:
print(Fore.RED + "对话终止")
if assistant_response.terminated:
print(Fore.RED + f"助手终止原因: {assistant_response.info.get('termination_reasons', '未知')}")
if user_response.terminated:
print(Fore.RED + f"用户终止原因: {user_response.info.get('termination_reasons', '未知')}")
break

# 检查任务完成标识
if "CAMEL_TASK_DONE" in user_response.msg.content:
print(Fore.GREEN + "任务完成!")
break

input_msg = assistant_response.msg
turn_count += 1

print(Fore.YELLOW + "-" * 60)

except Exception as e:
print(Fore.RED + f"执行错误: {e}")
break


可通过 response.info["tool_calls"] 查看工具调用记录,验证是否使用工具而非“编造”。

这段代码是一个完整的 CAMEL AI 多智能体协作系统实现,以下将详细分析其功能架构和实现机制。

  1. 系统架构分析
    1.1 核心组件结构
    ┌─────────────────────────────────────────────────────────────┐
    │ CAMEL AI 多智能体系统 │
    ├─────────────────────────────────────────────────────────────┤
    │ 环境配置层 │ 模型工厂层 │ 工具包层 │ 角色扮演层 │ 执行控制层 │
    │ ├─ 环境变量 │ ├─ 模型创建 │ ├─ 搜索 │ ├─ 双智能体 │ ├─ 安全机制 │
    │ ├─ API配置 │ ├─ 平台适配 │ ├─ 计算 │ ├─ 任务分配 │ ├─ 异常处理 │
    │ └─ 密钥管理 │ └─ 连接建立 │ └─ 工具链 │ └─ 协作模式 │ └─ 循环控制 │
    └─────────────────────────────────────────────────────────────┘
    1.2 数据流向分析
    用户任务 → 角色扮演系统 → 智能体交互 → 工具调用 → 结果返回 → 任务完成
    ↓ ↓ ↓ ↓ ↓ ↓
    任务解析 角色分配 消息传递 功能执行 数据处理 状态更新
  2. 详细功能实现
    2.1 环境配置与模型初始化
1
2
3
python# 环境配置层
load_dotenv()
api_key = os.getenv('MODELSCOPE_SDK_TOKEN')

模型工厂层

1
2
3
4
5
6
model = ModelFactory.create(
model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
model_type="Qwen/Qwen2.5-72B-Instruct",
url='https://api-inference.modelscope.cn/v1/',
api_key=api_key
)

功能特点:
配置解耦: 使用环境变量管理敏感信息
平台抽象: 支持多种模型平台的统一接口
模型选择: 使用 Qwen2.5-72B 大模型作为推理引擎

2.2 工具包集成机制

1
2
3
4
pythontools_list = [
*SearchToolkit().get_tools(),
*MathToolkit().get_tools()
]

工具能力分析:

SearchToolkit:

百度搜索、谷歌搜索、DuckDuckGo搜索
信息检索和网络查询能力

MathToolkit:

数学计算、公式求解
数值分析和统计计算

扩展性: 使用解包操作符支持动态工具添加

2.3 角色扮演系统设计
pythonrole_play_session = RolePlaying(
assistant_role_name=”搜索者”,
user_role_name=”教授”,
assistant_agent_kwargs=dict(model=model, tools=tools_list),
user_agent_kwargs=dict(model=model),
task_prompt=task_prompt,
with_task_specify=False,
output_language=’中文’
)
角色分工机制:
搜索者(Assistant):
具备工具调用能力
负责信息检索和计算执行
主动解决问题的执行者

教授(User):
任务分析和指导
结果验证和反馈
决策和监督角色

2.4 任务驱动的协作模式

1
2
pythontask_prompt = ("假设现在是2024年,牛津大学的成立年份,并计算出其当前年龄。"
"然后再将这个年龄加上10年。使用百度搜索工具。")

任务分解策略:
信息获取: 搜索牛津大学成立年份
数据处理: 计算当前年龄 (2024 - 成立年份)
进一步计算: 年龄 + 10 年
工具约束: 明确使用百度搜索工具

  1. 执行控制机制
    3.1 安全的循环控制
1
2
3
4
pythonmax_turns = 10
turn_count = 0

while turn_count < max_turns:

安全机制:
轮次限制: 防止无限循环
计数器: 跟踪执行进度
资源保护: 避免资源耗尽

3.2 异常处理机制

1
2
3
4
5
pythontry:
assistant_response, user_response = role_play_session.step(input_msg)
except Exception as e:
print(Fore.RED + f"执行错误: {e}")
break

错误处理策略:
捕获异常: 网络错误、API调用失败
友好提示: 彩色输出错误信息
优雅退出: 避免程序崩溃

3.3 终止条件检查

1
2
3
4
5
6
7
8
python# 智能体主动终止
if assistant_response.terminated or user_response.terminated:
print(Fore.RED + "对话终止")

# 任务完成检查
if "CAMEL_TASK_DONE" in user_response.msg.content:
print(Fore.GREEN + "任务完成!")
break

多重终止机制:
智能体终止: 基于内部逻辑判断
任务完成: 基于特定标识符
强制终止: 基于轮次限制

  1. 系统优势
    4.1 架构优势
    模块化设计: 各组件独立可替换
    可扩展性: 支持新工具和角色的添加
    平台无关: 支持多种模型平台

4.2 功能优势
智能协作: 双智能体协同工作
工具集成: 多种工具无缝集成
任务导向: 明确的任务驱动机制

代码运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
开始执行任务: 假设现在是2024年,牛津大学的成立年份,并计算出其当前年龄。然后再将这个年龄加上10 年。使用百度搜索工具。

============================================================
Warning: No results found. Check if Baidu HTML structure has changed.
Warning: No results found. Check if Baidu HTML structure has changed.
Warning: No results found. Check if Baidu HTML structure has changed.
Warning: No results found. Check if Baidu HTML structure has changed.
Warning: No results found. Check if Baidu HTML structure has changed.
Warning: No results found. Check if Baidu HTML structure has changed.

[Turn 1]
助手: 看来通过搜索引擎直接获取牛津大学的确切成立年份遇到了一些困难,因为多次尝试使用不同的关键 词组合(如“建立年份”、“创立时间”等)都没有返回有效的结果。不过,根据普遍的历史记录和教育资料, 牛津大学的成立年份通常被认为是1096年左右。这是因为牛津大学没有确切的建校日期,但有记录显示,早 在1096年就已经有了教学活动。

接下来,我们可以基于这一信息继续完成任务。假设现在是2024年,我们将使用1096年作为牛津大学的成立 年份来计算其当前年龄,并在此基础上再加上10年。

Solution: 首先计算牛津大学在2024年的年龄,然后将这个年龄加上10年。计算方法如下:
1. 计算2024年时牛津大学的年龄:2024 - 1096 = 928年。
2. 将这个年龄加上10年:928 + 10 = 938年。

因此,如果现在是2024年,那么牛津大学的年龄将是928年,再加上10年后,它的年龄将是938年。

Next request.
用户: Instruction: 使用百度搜索工具查找牛津大学的成立年份。
Input: None
工具调用: [ToolCallingRecord(tool_name='search_baidu', args={'query': '牛津大学 成立年份', 'max_results': 1}, result={'results': []}, tool_call_id='call_03377cb5855047779966f1'), ToolCallingRecord(tool_name='search_google', args={'query': '牛津大学 成立年份', 'num_result_pages': 1}, result=[{'error': 'google search failed.'}], tool_call_id='call_5e2d126b8c5c4d0ab61830'), ToolCallingRecord(tool_name='search_bing', args={'query': '牛津大学 成立年份', 'max_results': 1}, result={'results': [{'result_id': 1, 'snippet': '', 'title': '火遍全网的牛津阅读树应该怎么刷?孩子才愿意自主学习 ...', 'link': 'https://www.zhihu.com/tardis/bd/art/710913755'}]}, tool_call_id='call_d0611c8f52ed40088d6f04'), ToolCallingRecord(tool_name='search_baidu', args={'query': '牛津大学 创建时间', 'max_results': 1}, result={'results': []}, tool_call_id='call_1030fde3d5e5488e802e00'), ToolCallingRecord(tool_name='search_baidu', args={'query': '牛津大学 建校时间', 'max_results': 1}, result={'results': []}, tool_call_id='call_d8c4ed8c89d24413abdd99'), ToolCallingRecord(tool_name='search_baidu', args={'query': '牛津大学 建立时间', 'max_results': 1}, result={'results': []}, tool_call_id='call_85c1047a67004062838bd4'), ToolCallingRecord(tool_name='search_baidu', args={'query': '牛津大学 创立时间', 'max_results': 1}, result={'results': []}, tool_call_id='call_3c6ad476db73499c9f3430'), ToolCallingRecord(tool_name='search_google', args={'query': '牛津大学 创立时间', 'num_result_pages': 1}, result=[{'error': 'google search failed.'}], tool_call_id='call_8ef4dccfd97b43a6a5b84c'), ToolCallingRecord(tool_name='search_bing', args={'query': '牛津大学 创立时间', 'max_results': 1}, result={'results': [{'result_id': 1, 'snippet': '', 'title': '火遍全网的牛津阅读树应该怎么刷?孩子才愿意自主学习 ...', 'link': 'https://www.zhihu.com/tardis/bd/art/710913755'}]}, tool_call_id='call_e7187dd15c614c5cb6431f'), ToolCallingRecord(tool_name='search_baidu', args={'query': '牛津大学 建立年份', 'max_results': 1}, result={'results': []}, tool_call_id='call_20a26bcda1f749b4ad1451')]
------------------------------------------------------------

[Turn 2]
助手: 尽管多次尝试通过不同的搜索引擎和关键词组合查询牛津大学的确切成立年份,但似乎无法从这些搜 索结果中直接获得准确的信息。然而,根据广泛接受的历史资料,牛津大学的成立年份通常被认定为1096年 左右。

基于此信息,我们已经完成了之前的计算步骤,即假设现在是2024年,牛津大学的年龄为928年;再过10年后,它的年龄将会是938年。

既然已经确认了计算结果,我们的任务可以结束了。如果您有任何其他问题或需要进一步的帮助,请随时告 诉我!

任务已完成。
用户: Instruction: 确认计算结果并结束任务。
Input: None
------------------------------------------------------------

[Turn 3]
助手: 根据维基百科的资料,牛津大学的教学活动可以追溯到1096年,这是英语世界中最古老的大学,也是 世界上持续运营的第二古老大学。因此,我们可以确认牛津大学的成立年份为1096年。

按照之前的计算方法:
1. 如果现在是2024年,牛津大学的年龄为:2024 - 1096 = 928年。
2. 再加上10年后的年龄为:928 + 10 = 938年。

任务已经完成。如果您还有其他问题或需要进一步的帮助,请告诉我!

任务已完成。
用户: CAMEL_TASK_DONE
工具调用: [ToolCallingRecord(tool_name='search_wiki', args={'entity': '牛津大学'}, result='There is no page in Wikipedia corresponding to entity 牛津大学, please specify another word to describe the entity to be searched.', tool_call_id='call_adbbda4b67004ea3b38de2'), ToolCallingRecord(tool_name='search_wiki', args={'entity': 'Oxford University'}, result="The University of Oxfo任务已经完成。如果您还有其他问题或需要进一步的帮助,请告诉我!

任务已完成。
用户: CAMEL_TASK_DONE
工具调用: [ToolCallingRecord(tool_name='search_wiki', args={'entity': '牛津大学'}, result='There is no page in Wikipedia corresponding to entity 牛津大学, please specify another word to describe the entity to be searched.', tool_call_id='call_adbbda4b67004ea3b38de2'), ToolCallingRecord(tool_name='search_wiki', args={'entity': 'Oxford University'}, result="The University of Oxfo工具调用: [ToolCallingRecord(tool_name='search_wiki', args={'entity': '牛津大学'}, result='There is no page in Wikipedia corresponding to entity 牛津大学, please specify another word to describe the entity to be searched.', tool_call_id='rd is a collegiatrd is a collegiate research university in Oxford, England. There is evidence of teaching as early as 1096, making it the oldest university in the English-speaking world and the world's second-oldest university in continuous operation.\nIt expanded rapidly from 1167, when Henry II prohibited English students from attending the University of Paris. When disputes erupted between students and the Oxford townspeople, some Oxford academics fled northeast to Cambridge, where they established the University of Cambridge in 1209. The two English ancient universities share many common features and are jointly referred to as Oxbridge.", tool_call_id='call_4456a1825530488a804b6b')]
任务完成!