camel-ai Agent模块- CriticAgent

发布于:2025-06-25 ⋅ 阅读:(16) ⋅ 点赞:(0)

CriticAgent 简介

在这里插入图片描述

CriticAgent
Specialized agent for evaluating and critiquing responses or solutions. Used in scenarios requiring quality assessment or validation.

翻译成中文的意思是

专门评估和评判回复或解决方案的代理。用于需要质量评估或验证的场景。

CriticAgent 的主要方法

flatten_options

将输入的消息,扁平化为选项,代码如下

    def flatten_options(self, messages: Sequence[BaseMessage]) -> str:
        r"""Flattens the options to the critic.

        Args:
            messages (Sequence[BaseMessage]): A list of `BaseMessage` objects.

        Returns:
            str: A string containing the flattened options to the critic.
        """
        options = [message.content for message in messages]
        flatten_options = (
            f"> Proposals from "
            f"{messages[0].role_name} ({messages[0].role_type}). "
            "Please choose an option:\n"
        )
        for index, option in enumerate(options):
            flatten_options += f"Option {index + 1}:\n{option}\n\n"
            self.options_dict[str(index + 1)] = option
        format = (
            f"Please first enter your choice ([1-{len(self.options_dict)}]) "
            "and then your explanation and comparison: "
        )
        return flatten_options + format

get_option

请求大模型,让大模型根据输入的选项,评估选择合适的选项

    def get_option(self, input_message: BaseMessage) -> str:
        r"""Gets the option selected by the critic.

        Args:
            input_message (BaseMessage): A `BaseMessage` object representing
                the input message.

        Returns:
            str: The option selected by the critic.
        """
        # TODO: Add support for editing options by the critic.
        msg_content = input_message.content
        i = 0
        while i < self.retry_attempts:
            critic_response = self.step(input_message)

            if critic_response.msgs is None or len(critic_response.msgs) == 0:
                raise RuntimeError("Got None critic messages.")
            if critic_response.terminated:
                raise RuntimeError("Critic step failed.")

            critic_msg = critic_response.msg
            if self.verbose:
                print_text_animated(
                    self.logger_color + "\n> Critic response: "
                    f"\x1b[3m{critic_msg.content}\x1b[0m\n"
                )
            choice = self.parse_critic(critic_msg)

            if choice in self.options_dict:
                return self.options_dict[choice]
            else:
                input_message = BaseMessage(
                    role_name=input_message.role_name,
                    role_type=input_message.role_type,
                    meta_dict=input_message.meta_dict,
                    content="> Invalid choice. Please choose again.\n"
                    + msg_content,
                )
                i += 1
        warnings.warn(
            "Critic failed to get a valid option. "
            f"After {self.retry_attempts} attempts. "
            "Returning a random option."
        )
        return random.choice(list(self.options_dict.values()))

代码示例:评估最喜欢的编程语言

代码结构
在这里插入图片描述

  1. gpt_4o_model.py
from camel.messages import BaseMessage
from camel.models import ModelFactory
from camel.types import ModelPlatformType, RoleType, OpenAIBackendRole
from dotenv import load_dotenv
import os

load_dotenv(override=True)

base_url = os.getenv("gpt_base_url")
api_key = os.getenv("gpt_api_key")

model = ModelFactory.create(
    model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
    model_type="gpt-4o-mini",
    url=base_url,
    api_key=api_key
)


if __name__ == '__main__':
    openai_msg = BaseMessage(
            role_name="user",
            role_type=RoleType.USER,
            meta_dict=dict(),
            content="你好,你是谁",
    ).to_openai_message(OpenAIBackendRole.USER)
    messages = [
        openai_msg
    ]
    res = model.run(messages)
    print(res.choices[0].message.content)

  1. critic_agent.py
from camel.agents import CriticAgent
from camel.messages import BaseMessage
from camel.types import RoleType
from model.gpt_4o_model import model
from camel.logger import set_log_level

# Set the logging level
set_log_level('DEBUG')

criticAgent = CriticAgent(
    system_message= BaseMessage(
        "critic",
        RoleType.CRITIC,
        None,
        content=(
            "你是一位资深程序员,比较输入编程语言的优缺点,选择一个你最喜欢的编程语言,并且说明理由,请用中文回答"
        ),
    ),
    model=model,
    verbose=True
)

messages = [
    BaseMessage(
        role_name="user",
        role_type=RoleType.USER,
        meta_dict=dict(),
        content="Python",
    ),
    BaseMessage(
        role_name="user",
        role_type=RoleType.USER,
        meta_dict=dict(),
        content="Java",
    ),
]

flatten_options = criticAgent.flatten_options(messages)
print(flatten_options)
print(criticAgent.options_dict)

input_message = BaseMessage(
    role_name="user",
    role_type=RoleType.USER,
    meta_dict=dict(),
    content=flatten_options,
)
res = criticAgent.get_option(input_message)
print(res)

这段代码展示了如何使用CAMEL框架中的CriticAgent来比较两种编程语言(Python和Java)的优缺点并做出选择。主要功能模块解析如下:

  1. 初始化设置‌:
    通过set_log_level(‘DEBUG’)启用调试日志级别,便于跟踪程序运行细节。
    创建CriticAgent实例时定义了系统消息,指定该智能体扮演资深程序员角色,要求用中文比较编程语言优劣
    在这里插入图片描述

  2. 输入处理‌:
    构造包含两种编程语言(Python/Java)的BaseMessage列表作为输入选项1
    调用flatten_options方法将消息列表扁平化为字符串格式,同时构建选项字典映射
    在这里插入图片描述

  3. 决策过程‌:
    将扁平化后的选项内容封装为新BaseMessage作为输入。通过get_option方法触发智能体的分析决策,最终输出包含语言比较结果和推荐选择的响应
    在这里插入图片描述
    该实现体现了CAMEL框架中角色扮演智能体的典型工作流程:角色定义→输入处理→决策生成。

运行 critic_agent.py,得到如下结果

2025-06-19 22:51:58,192 - camel - DEBUG - Logging level set to: 10
2025-06-19 22:51:58,971 - camel - DEBUG - Logging level set to: 10
> Proposals from user (RoleType.USER). Please choose an option:
Option 1:
Python

Option 2:
Java

Please first enter your choice ([1-2]) and then your explanation and comparison: 
{'1': 'Python', '2': 'Java'}
2025-06-19 22:52:09,645 - camel.agents.chat_agent - INFO - Model gpt-4o-mini, index 0, processed these messages: [{'role': 'system', 'content': '你是一位资深程序员,比较输入编程语言的优缺点,选择一个你最喜欢的编程语言,并且说明理由,请用中文回答'}, {'role': 'user', 'content': '> Proposals from user (RoleType.USER). Please choose an option:\nOption 1:\nPython\n\nOption 2:\nJava\n\nPlease first enter your choice ([1-2]) and then your explanation and comparison: '}]

> Critic response: 我选择Option 1:Python。

### 优缺点比较:

#### Python的优点:
1. **简洁易读**:Python的语法非常简洁,代码可读性高,适合初学者学习和理解。
2. **丰富的库和框架**:Python拥有大量的第三方库和框架,例如NumPy、Pandas、Django等,能够大大提高开发效率。
3. **跨平台**:Python支持多种操作系统,包括Windows、Mac和Linux,具有良好的可移植性。
4. **社区支持**:Python有一个活跃的开发者社区,能够提供持续的支持和丰富的学习资源。
5. **多用途**:Python可以用于数据科学、机器学习、网页开发、自动化脚本等多个领域,适用范围广泛。

#### Python的缺点:
1. **性能较慢**:相比于Java等编译型语言,Python的运行速度相对较慢,尤其在高性能要求的场合。
2. **移动开发支持不足**:尽管有一些库支持移动开发,但相较于Java,Python在这方面的生态并不成熟。

#### Java的优点:
1. **性能较好**:Java是一种编译型语言,运行效率高,性能表现优于Python,特别适合大规模企业级应用。
2. **强类型**:Java是强类型语言,能够在编译阶段捕捉到更多的错误,减少运行时的问题。
3. **丰富的工具支持**:Java生态系统中有很多成熟的工具和IDE(如Eclipse、IntelliJ IDEA),能帮助开发者提高工作效率。
4. **跨平台**:Java的“写一次,处处运行”理念(通过JVM),使得Java程序可以在不同平台上轻松运行。

#### Java的缺点:
1. **语法较为复杂**:Java的语法相对较繁琐,不如Python简单易懂,学习曲线较陡。
2. **冗长的代码**:Java的代码通常比Python要多,导致开发时写代码的时间增加。

### 结论:
虽然Java在性能和企业级应用中表现出色,但我仍然更偏爱Python。Python的简洁性和丰富的库支持使得我能够在众多项目中快速实现功能,提升开发效率,尤其是在数据科学和机器学习领域的应用更加突出。因此,我选择Python作为我最喜欢的编程语言。
Python

延伸阅读

  1. camel-ai-agent

网站公告

今日签到

点亮在社区的每一天
去签到