【AI Agent系列】【阿里AgentScope框架】1. 深入源码:详细解读AgentScope中的智能体定义以及模型配置的流程

简介: 【AI Agent系列】【阿里AgentScope框架】1. 深入源码:详细解读AgentScope中的智能体定义以及模型配置的流程
  • 大家好,我是 同学小张,日常分享AI知识和实战案例
  • 欢迎 点赞 + 关注 👏,持续学习持续干货输出
  • + 一起交流💬,一起进步💪。
  • 微信公众号也可搜【同学小张】 🙏

本站文章一览:


书接上篇文章上篇文章我们运行了第一个AgentScope程序,里面我们创建了两个智能体:DialogAgent对话智能体 和 UserAgent用户智能体。本文我们来深入源码,看AgentScope框架内,这些智能体是如何实现的。

0. 智能体基类 - AgentBase

class AgentBase(Operator, metaclass=_RecordInitSettingMeta):
    """Base class for all agents.
    All agents should inherit from this class and implement the `reply`
    function.
    """

这是AgentScope中智能体的基类,所有智能体的定义都需要继承它,并且重写其 reply 函数。

0.1 初始化过程

0.1.1 总过程

初始化实现的功能:

(1)初始化的过程,name是必须参数。其余都可选。

(2)load_model_by_config_name 来加载模型配置,后面细说。

(3)use_memory 默认为True,使用memory时,memoryTemporaryMemory类型,并接收一个可选的 memory_config 参数。

def __init__(
    self,
    name: str,
    sys_prompt: Optional[str] = None,
    model_config_name: str = None,
    use_memory: bool = True,
    memory_config: Optional[dict] = None,
) -> None:
    r"""Initialize an agent from the given arguments.
    Args:
        name (`str`):
            The name of the agent.
        sys_prompt (`Optional[str]`):
            The system prompt of the agent, which can be passed by args
            or hard-coded in the agent.
        model_config_name (`str`, defaults to None):
            The name of the model config, which is used to load model from
            configuration.
        use_memory (`bool`, defaults to `True`):
            Whether the agent has memory.
        memory_config (`Optional[dict]`):
            The config of memory.
    """
    self.name = name
    self.memory_config = memory_config
    if sys_prompt is not None:
        self.sys_prompt = sys_prompt
    # TODO: support to receive a ModelWrapper instance
    if model_config_name is not None:
        self.model = load_model_by_config_name(model_config_name)
    if use_memory:
        self.memory = TemporaryMemory(memory_config)
    else:
        self.memory = None
    # The global unique id of this agent
    self._agent_id = self.__class__.generate_agent_id()
    # The audience of this agent, which means if this agent generates a
    # response, it will be passed to all agents in the audience.
    self._audience = None

0.1.2 加载模型配置 - load_model_by_config_name

def _get_model_wrapper(model_type: str) -> Type[ModelWrapperBase]:
    ......
    if model_type in ModelWrapperBase.type_registry:
        return ModelWrapperBase.type_registry[  # type: ignore[return-value]
            model_type
        ]
    elif model_type in ModelWrapperBase.registry:
        return ModelWrapperBase.registry[  # type: ignore[return-value]
            model_type
        ]
    elif model_type in ModelWrapperBase.deprecated_type_registry:
        cls = ModelWrapperBase.deprecated_type_registry[model_type]
        ......
        return cls  # type: ignore[return-value]
    else:
        ......
        return PostAPIModelWrapperBase
def load_model_by_config_name(config_name: str) -> ModelWrapperBase:
    """Load the model by config name."""
    ......
    return _get_model_wrapper(model_type=model_type)(**kwargs)

从源码看,这个函数的作用是根据你配置中的模型名称来加载模型的APIWrapper,例如我们上篇文章中的"model_type": "openai"。理论上,这里的"model_type"的值,只要是下面图中的任意一个即可:

0.1.3 模型配置的一些细节

上篇文章中的配置部分我有一些疑问:

今天通过源码知道了其中的门道,看下面关于OpenAI接口的封装:

model_name是在外面赋值的,所以必须要有。

api_key是通过OpenAI接口传递进去的参数,根据我们先前的使用经验,这里可以不传,只要环境变量中存在 OPENAI_API_KEYOPENAI_BASE_URL 即可使用。

1. 对话智能体 - DialogAgent

定义如下:通过 sys_prompt 参数指定其承担的角色,例如 “你是一个Python专家” 让其充当Python专家给你解决问题。

class DialogAgent(AgentBase):
    """A simple agent used to perform a dialogue. Your can set its role by
    `sys_prompt`."""

1.1 初始化过程

def __init__(
    self,
    name: str,
    sys_prompt: str,
    model_config_name: str,
    use_memory: bool = True,
    memory_config: Optional[dict] = None,
    prompt_type: Optional[PromptType] = None,
) -> None:
    """Initialize the dialog agent.
    Arguments:
        name (`str`):
            The name of the agent.
        sys_prompt (`Optional[str]`):
            The system prompt of the agent, which can be passed by args
            or hard-coded in the agent.
        model_config_name (`str`):
            The name of the model config, which is used to load model from
            configuration.
        use_memory (`bool`, defaults to `True`):
            Whether the agent has memory.
        memory_config (`Optional[dict]`):
            The config of memory.
        prompt_type (`Optional[PromptType]`, defaults to
        `PromptType.LIST`):
            The type of the prompt organization, chosen from
            `PromptType.LIST` or `PromptType.STRING`.
    """

初始化参数namesys_promptmodel_config_name是必须设置的。

1.2 重写 reply 函数

这个reply函数是必须重写的。下面来看源码:

def reply(self, x: dict = None) -> dict:
    """Reply function of the agent. Processes the input data,
    generates a prompt using the current dialogue memory and system
    prompt, and invokes the language model to produce a response. The
    response is then formatted and added to the dialogue memory.
    Args:
        x (`dict`, defaults to `None`):
            A dictionary representing the user's input to the agent. This
            input is added to the dialogue memory if provided. Defaults to
            None.
    Returns:
        A dictionary representing the message generated by the agent in
        response to the user's input.
    """
    # record the input if needed
    if self.memory:
        self.memory.add(x)
    # prepare prompt
    prompt = self.model.format(
        Msg("system", self.sys_prompt, role="system"),
        self.memory and self.memory.get_memory(),  # type: ignore[arg-type]
    )
    # call llm and generate response
    response = self.model(prompt).text
    msg = Msg(self.name, response, role="assistant")
    # Print/speak the message in this agent's voice
    self.speak(msg)
    # Record the message in memory
    if self.memory:
        self.memory.add(msg)
    return msg

(1)首先是 memory 的操作,开始时将输入信息添加到 memory 中,结束前将大模型的回复写入到 memory 中:

if self.memory:
    self.memory.add(x)
......
if self.memory:
    self.memory.add(msg)

(2)prompt组装部分:将 system_promptmemory的内容组装成OpenAI需要的message列表。

def format(
    self,
    *args: Union[Msg, Sequence[Msg]],
) -> List[dict]:
......
    messages = []
    for arg in args:
        if arg is None:
            continue
        if isinstance(arg, Msg):
            messages.append(
                {
                    "role": arg.role,
                    "name": arg.name,
                    "content": _convert_to_str(arg.content),
                },
            )
        elif isinstance(arg, list):
            messages.extend(self.format(*arg))
        ......
    return messages
prompt = self.model.format(
    Msg("system", self.sys_prompt, role="system"),
    self.memory and self.memory.get_memory(),  # type: ignore[arg-type]
)

(3)调用大模型获取结果

response = self.model(prompt).text

1.3 小结

所以,对话智能体的实现就是将 system_prompt 和 对话的 memory 组装成prompt,然后让大模型回复。

2. 用户智能体 - UserAgent

2.1 初始化过程

所有参数都是可选的,默认名称是 “User” :

class UserAgent(AgentBase):
    """User agent class"""
    def __init__(self, name: str = "User", require_url: bool = False) -> None:
        """Initialize a UserAgent object.
        Arguments:
            name (`str`, defaults to `"User"`):
                The name of the agent. Defaults to "User".
            require_url (`bool`, defaults to `False`):
                Whether the agent requires user to input a URL. Defaults to
                False. The URL can lead to a website, a file,
                or a directory. It will be added into the generated message
                in field `url`.
        """
        super().__init__(name=name)
        self.name = name
        self.require_url = require_url

2.2 重写 reply 函数

实现的功能就是接收用户输入:content = user_input(timeout=timeout)

def user_input(
    prefix: str = "User input: ",
    timeout: Optional[int] = None,
) -> str:
    """get user input"""
    if hasattr(thread_local_data, "uid"):
        content = get_player_input(
            timeout=timeout,
            uid=thread_local_data.uid,
        )
    else:
        if timeout:
            from inputimeout import inputimeout, TimeoutOccurred
            try:
                content = inputimeout(prefix, timeout=timeout)
            except TimeoutOccurred as exc:
                raise TimeoutError("timed out") from exc
        else:
            content = input(prefix)
    return content
def reply(
    self,
    x: dict = None,
    required_keys: Optional[Union[list[str], str]] = None,
    timeout: Optional[int] = None,
) -> dict:
    ......
    if self.memory:
        self.memory.add(x)
    ......
    content = user_input(timeout=timeout)
    ......
    # Add to memory
    if self.memory:
        self.memory.add(msg)
    return msg

2.3 小结

所以,UserAgent的作用就是接收用户输入,让人参与到多智能体的交互中。

3. 总结

本文主要看了下AgentScope中智能体agent的定义源码,深入学习了agent初始化的过程,配置的加载等流程。挑选了两个简单的agent - DialogAgent 和 UserAgent进行了详细学习。个性化Agent的定义,需要继承AgentBase基类,重写其reply函数,在reply函数中,定义个性化Agent的个性化动作。

AgentScope目前还有一些其它的个性化Agent,例如react_agent、rpc_agent等,咱们后面用到再学。

如果觉得本文对你有帮助,麻烦点个赞和关注呗 ~~~


  • 大家好,我是 同学小张,日常分享AI知识和实战案例
  • 欢迎 点赞 + 关注 👏,持续学习持续干货输出
  • 一起交流💬,一起进步💪。
  • 微信公众号也可搜【同学小张】 🙏

本站文章一览:

相关文章
|
17天前
|
传感器 机器学习/深度学习 人工智能
AI Agent 十问十答,降低认知摩擦
本文探讨了AI Agent的相关概念和技术细节,包括其定义、与传统软件的区别、构成组件、工作原理及优化方法。AI Agent是一种基于大语言模型(LLM)的智能代理,能感知环境、推理决策并执行任务。相比传统自动化软件,AI Agent具备更强的理解力和自主性,可处理复杂任务。文章分析了Chatbot向AI Agent演进的趋势及其驱动因素,并详解了提升AI Agent效果的关键要素如模型质量、工具选择和指令设计。此外,还讨论了Workflow与LLM的结合方式以及单智能体与多智能体系统的优劣,为理解和应用AI Agent提供了全面视角。
778 170
|
27天前
|
机器学习/深度学习 人工智能 PyTorch
模型手动绑骨3天,AI花3分钟搞定!UniRig:清华开源通用骨骼自动绑定框架,助力3D动画制作
UniRig是清华大学与VAST联合研发的自动骨骼绑定框架,基于自回归模型与交叉注意力机制,支持多样化3D模型的骨骼生成与蒙皮权重预测,其创新的骨骼树标记化技术显著提升动画制作效率。
230 27
模型手动绑骨3天,AI花3分钟搞定!UniRig:清华开源通用骨骼自动绑定框架,助力3D动画制作
|
21天前
|
人工智能 自然语言处理 数据可视化
让AI单次生成4万字!WriteHERE:开源AI长文写作框架,单次生成超长文本,小说报告一键搞定!
WriteHERE是基于异质递归规划技术的开源AI写作框架,能动态分解写作任务并管理任务依赖关系,支持单次生成超过4万字的专业报告。
98 2
让AI单次生成4万字!WriteHERE:开源AI长文写作框架,单次生成超长文本,小说报告一键搞定!
|
27天前
|
人工智能 开发框架 决策智能
谷歌开源多智能体开发框架 Agent Development Kit:百行代码构建复杂AI代理,覆盖整个开发周期!
谷歌开源的Agent Development Kit(ADK)是首个代码优先的Python工具包,通过多智能体架构和灵活编排系统,支持开发者在百行代码内构建复杂AI代理,提供预置工具库与动态工作流定义能力。
186 3
谷歌开源多智能体开发框架 Agent Development Kit:百行代码构建复杂AI代理,覆盖整个开发周期!
|
7天前
|
人工智能 监控 JavaScript
MCP实战之Agent自主决策-让 AI玩转贪吃蛇
MCP服务器通过提供资源、工具、提示模板三大能力,推动AI实现多轮交互与实体操作。当前生态包含Manus、OpenManus等项目,阿里等企业积极合作,Cursor等工具已集成MCP市场。本文以贪吃蛇游戏为例,演示MCP Server实现流程:客户端连接服务端获取能力集,AI调用工具(如start_game、get_state)控制游戏,通过多轮交互实现动态操作,展示MCP在本地实践中的核心机制与挑战。
135 18
MCP实战之Agent自主决策-让 AI玩转贪吃蛇
|
14天前
|
机器学习/深度学习 人工智能 JSON
这个AI把arXiv变成代码工厂,快速复现顶会算法!Paper2Code:AI论文自动转代码神器,多智能体框架颠覆科研复现
Paper2Code是由韩国科学技术院与DeepAuto.ai联合开发的多智能体框架,通过规划、分析和代码生成三阶段流程,将机器学习论文自动转化为可执行代码仓库,显著提升科研复现效率。
136 18
这个AI把arXiv变成代码工厂,快速复现顶会算法!Paper2Code:AI论文自动转代码神器,多智能体框架颠覆科研复现
|
6天前
|
机器学习/深度学习 人工智能 算法
破解生成式AI认知边界:框架思维引擎如何重塑产业智能化未来
该内容深入解析了核心技术架构,涵盖思维链强化系统(DTT)、认知框架建模体系和实时纠偏算法体系。DTT通过多级问题拆解、混合精度推理及分布式验证,大幅提升复杂问题处理能力;认知框架结合知识图谱与逻辑推理,实现精准医疗诊断等应用;实时纠偏算法则通过多级验证机制保障事实与逻辑准确性。整体架构分应用层、框架层和基础层,支持高效、可信的跨领域适配。技术创新体现在混合计算加速、持续学习机制等方面,显著优于传统模型,在事实准确性、逻辑连续性及响应速度上优势明显。
53 28
|
19天前
|
人工智能 自然语言处理 监控
Cooragent:清华 LeapLab 开源 AI Agent 协作框架,一句话召唤AI军团!
Cooragent 是清华大学 LeapLab 团队推出的开源 AI Agent 协作框架,支持基于简单描述快速创建 Agent 并实现多 Agent 协作,具备 Prompt-Free 设计和本地部署能力。
185 6
Cooragent:清华 LeapLab 开源 AI Agent 协作框架,一句话召唤AI军团!
|
27天前
|
人工智能 自然语言处理 JavaScript
测试工程师要失业?Magnitude:开源AI Agent驱动的端到端测试框架,让Web测试更智能,自动完善测试用例!
Magnitude是一个基于视觉AI代理的开源端到端测试框架,通过自然语言构建测试用例,结合推理代理和视觉代理实现智能化的Web应用测试,支持本地运行和CI/CD集成。
206 15
测试工程师要失业?Magnitude:开源AI Agent驱动的端到端测试框架,让Web测试更智能,自动完善测试用例!
|
8天前
|
存储 人工智能 NoSQL
表格存储:为 AI 注入“记忆”,构建大规模、高性能、低成本的 Agent Memory 数据底座
本文探讨了AI Agent市场爆发增长背景下的存储需求,重点介绍了Tablestore在Agent Memory存储中的优势。2025年被视为AI Agent市场元年,关键事件推动技术发展。AI Agent的存储分为Memory(短期记忆)和Knowledge(长期知识)。Tablestore通过高性能、低成本持久化存储、灵活的Schemaless设计等特性满足Memory场景需求;在Knowledge场景中,其多元索引支持全文、向量检索等功能,优化成本与稳定性。实际案例包括通义App、某浏览器及阿里云多项服务,展示Tablestore的卓越表现。最后邀请加入钉钉群共同探讨AI技术。
593 9