.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "build_tutorial/message.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_build_tutorial_message.py: .. _message: 消息 ==================== 消息是一种专用的数据结构,用于信息交换。 在 AgentScope 中,我们使用消息在智能体之间进行通信。 消息的最重要字段是:name、role 和 content。 name 和 role 字段标识消息的发送者,content 字段包含实际信息。 .. Note:: role 字段必须选择 `"system"`、`"assistant"`、 `"user"` 其中之一。 .. GENERATED FROM PYTHON SOURCE LINES 16-20 .. code-block:: Python from agentscope.message import Msg import json .. GENERATED FROM PYTHON SOURCE LINES 21-25 创建消息 ---------------- 可以通过指定 name、role 和 content 字段来创建消息。 .. GENERATED FROM PYTHON SOURCE LINES 25-36 .. code-block:: Python msg = Msg( name="Jarvis", role="assistant", content="嗨!我能为您效劳吗?", ) print(f'消息发送者:"{msg.name}"') print(f'发送者角色:"{msg.role}"') print(f'消息内容:"{msg.content}"') .. rst-class:: sphx-glr-script-out .. code-block:: none 消息发送者:"Jarvis" 发送者角色:"assistant" 消息内容:"嗨!我能为您效劳吗?" .. GENERATED FROM PYTHON SOURCE LINES 37-41 序列化 ---------------- 消息可以序列化为 JSON 格式的字符串。 .. GENERATED FROM PYTHON SOURCE LINES 41-47 .. code-block:: Python serialized_msg = msg.to_dict() print(type(serialized_msg)) print(json.dumps(serialized_msg, indent=4)) .. rst-class:: sphx-glr-script-out .. code-block:: none { "__module__": "agentscope.message.msg", "__name__": "Msg", "role": "assistant", "timestamp": "2025-03-10 03:39:25", "metadata": null, "id": "3410106dc0fe4157b9b0b732c5e1812a", "name": "Jarvis", "url": null, "content": "\u55e8\uff01\u6211\u80fd\u4e3a\u60a8\u6548\u52b3\u5417\uff1f" } .. GENERATED FROM PYTHON SOURCE LINES 48-52 反序列化 ---------------- 从 JSON 格式的字典反序列化消息。 .. GENERATED FROM PYTHON SOURCE LINES 52-59 .. code-block:: Python new_msg = Msg.from_dict(serialized_msg) print(new_msg) print(f'消息发送者:"{new_msg.name}"') print(f'发送者角色:"{new_msg.role}"') print(f'消息内容:"{new_msg.content}"') .. rst-class:: sphx-glr-script-out .. code-block:: none 消息发送者:"Jarvis" 发送者角色:"assistant" 消息内容:"嗨!我能为您效劳吗?" .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.002 seconds) .. _sphx_glr_download_build_tutorial_message.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: message.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: message.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: message.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_