Autogen_core: Model Context
目录
- 示例代码
- 代码解释
- 另一个例子
示例代码
from dataclasses import dataclassfrom autogen_core import AgentId, MessageContext, RoutedAgent, SingleThreadedAgentRuntime, message_handler
from autogen_core.model_context import BufferedChatCompletionContext
from autogen_core.models import AssistantMessage, ChatCompletionClient, SystemMessage, UserMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient
@dataclass
class Message:content: str
class SimpleAgentWithContext(RoutedAgent):def __init__(self, model_client: ChatCompletionClient) -> None:super().__init__("A simple agent")self._system_messages = [SystemMessage(content="You are a helpful AI assistant.")]self._model_client = model_clientself._model_context = BufferedChatCompletionContext(buffer_size=5)@message_handlerasync def handle_user_message(self, message: Message, ctx: MessageContext) -> Message:# Prepare input to the chat completion model.user_message = UserMessage(content=message.content, source="user")# Add message to model context.await self._model_context.add_message(user_message)# Generate a response.response = await self._model_client.create(self._system_messages + (await self._model_context.get_messages()),cancellation_token=ctx.cancellation_token,)# Return with the model's response.assert isinstance(response.content, str)# Add message to model context.await self._model_context.add_message(AssistantMessage(content=response.content, source=self.metadata["type"]))return Message(content=response.content)
runtime = SingleThreadedAgentRuntime()model_client = OpenAIChatCompletionClient(model="GLM-4-Air-0111",api_key = "your api key",base_url="https://open.bigmodel.cn/api/paas/v4/",model_capabilities={"vision": True,"function_calling": True,"json_output": True,})await SimpleAgentWithContext.register(runtime,"simple_agent_context",lambda: SimpleAgentWithContext(model_client),
)
# Start the runtime processing messages.
runtime.start()
agent_id = AgentId("simple_agent_context", "default")# First question.
message = Message("Hello, what are some fun things to do in Seattle?")
print(f"Question: {message.content}")
response = await runtime.send_message(message, agent_id)
print(f"Response: {response.content}")
print("-----")# Second question.
message = Message("What was the first thing you mentioned?")
print(f"Question: {message.content}")
response = await runtime.send_message(message, agent_id)
print(f"Response: {response.content}")# Stop the runtime processing messages.
await runtime.stop()
Question: Hello, what are some fun things to do in Seattle?
Response: Seattle is a vibrant city with a lot to offer! Here are some fun things to do, catering to different interests:**For the Outdoorsy Type:*** **Visit Pike Place Market:** This iconic public market is a must-see. Watch fish mongers throw fish, sample local produce, and grab a bite to eat.
* **Explore the Seattle Great Wheel:** Enjoy stunning views of Elliott Bay and the city skyline from this Ferris wheel on the waterfront.
* **Take a walk or bike ride along the Seattle Waterfront:** Enjoy the fresh air, views of the Puget Sound, and attractions like the Seattle Aquarium.
* **Hike the Chirico Trail at Discovery Park:** This 2.8-mile loop offers beautiful views of Puget Sound and the Olympic Mountains.
* **Go kayaking or stand-up paddleboarding:** Rent a vessel and explore the calm waters of Lake Union or the more adventurous Puget Sound.
* **Visit the Japanese Garden at the Seattle Arboretum:** Stroll through this serene 3.5-acre garden featuring winding paths, water features, and traditional Japanese landscaping.
* **Take a day trip to one of the nearby mountains:** Mount Rainier, Mount Baker, and the Cascades offer incredible hiking, scenic drives, and wildlife viewing opportunities.**For the Culture Enthusiast:*** **Explore the Museum of Pop Culture (MoPOP):** This museum dedicated to contemporary popular culture is a fun and interactive experience, with exhibits on music, science fiction, and fantasy.
* **Visit the Seattle Art Museum (SAM):** Admire a diverse collection of art from around the world, including Native American art and contemporary works.
* **See a show at the 5th Avenue Theatre or the Paramount Theatre:** Catch a Broadway show or a concert in one of these historic venues.
* **Explore the historic Pioneer Square district:** This area features Victorian-era architecture, art galleries, and unique shops.
* **Visit the Ballard Locks (Hiram M. Chittenden Locks):** Watch boats pass between Puget Sound and the Ship Canal, and enjoy the surrounding park.
* **Attend a festival or event:** Seattle hosts numerous festivals throughout the year, including the Seattle International Film Festival, Bumbershoot, and the Capitol Hill Block Party.**For the Foodie:*** **Enjoy a coffee at a local cafe:** Seattle is the birthplace of Starbucks, but you'll find many independent coffee shops offering delicious brews.
* **Try some fresh seafood:** From salmon to Dungeness crab, Seattle is known for its fresh seafood. Canlis, The Pink Door, and Ivar's Acres of Clams are great options.
* **Explore the diverse culinary scene:** Seattle has a wide range of cuisines, from Vietnamese pho to Ethiopian injera. Explore the International District for a variety of options.
* **Visit a food truck pod:** Food truck pods are a great way to sample a variety of cuisines in one location. South Lake Union and Capitol Hill have several pods.**For the Music Lover:*** **Visit the Experience Music Project (now part of MoPOP):** This museum celebrates the history of music, with a focus on Seattle's grunge scene.
* **See a live music show:** Seattle has a thriving music scene, with venues like The Crocodile, Neumos, and The Showbox hosting shows almost every night.
* **Explore the Music Row district on 5th Avenue:** This area is home to several music venues, record stores, and other music-related businesses.**Unique Seattle Experiences:*** **Ride the monorail:** This historic monorail connects downtown Seattle to the Seattle Center.
* **Visit the Seattle Center:** This park, built for the 1962 World's Fair, features the Space Needle, the International Fountain, and other attractions.
* **Take a Bill Speidel's Underground Tour:** Explore the hidden passages and history beneath the city streets.
* **Go on a whale watching tour:** Several companies offer tours to see orcas and other marine wildlife in Puget Sound.**Tips for Planning Your Trip:*** **Best time to visit:** Spring and fall offer pleasant weather and fewer crowds. Summer can be warm and sunny, but also crowded and expensive.
* **Getting around:** Seattle has a good public transportation system, including buses, light rail, and streetcars. Ride-sharing services are also readily available.
* **Book accommodations and activities in advance:** Especially during peak season.This is just a starting point, and there's much more to discover in Seattle! To help me narrow down the options further, tell me:* **When are you planning to visit?**
* **How long will you be in Seattle?**
* **What are your interests (e.g., outdoors, food, art, music)?**
* **Who
-----
Question: What was the first thing you mentioned?
Response: The first thing I mentioned in my response about fun things to do in Seattle was **Visit Pike Place Market**.
代码解释
这段代码使用了一个名为 autogen_core 的库,该库通常用于创建和运行基于AI的聊天代理。代码的目的是创建一个简单的代理,它能够上下文感知地回答用户的问题。下面是代码的逻辑和功能的详细解释:
-
导入必要的类和模块:
dataclass用于定义简单的数据结构。autogen_core中的AgentId、MessageContext、RoutedAgent、SingleThreadedAgentRuntime和message_handler用于创建和管理代理。BufferedChatCompletionContext用于管理聊天上下文。AssistantMessage、ChatCompletionClient、SystemMessage和UserMessage用于构建和发送消息。OpenAIChatCompletionClient是一个用于与OpenAI模型进行交互的客户端。
-
定义
Message数据类:- 这是一个简单的数据结构,用于存储消息的内容。
-
创建
SimpleAgentWithContext类:- 这个类继承自
RoutedAgent,代表一个能够处理消息的代理。 - 构造函数初始化代理的名称、系统消息列表、模型客户端和模型上下文。
handle_user_message方法是一个异步消息处理器,它接收用户消息,将其添加到模型上下文中,并使用模型客户端生成响应。- 生成的响应被添加回模型上下文,并返回给用户。
- 这个类继承自
-
初始化运行时环境和模型客户端:
runtime是一个SingleThreadedAgentRuntime实例,用于管理代理的运行。model_client是一个OpenAIChatCompletionClient实例,配置了特定的模型名称、API密钥和基本URL。
-
注册和启动代理:
SimpleAgentWithContext被注册到运行时环境中,并指定了一个构造函数。- 运行时环境被启动以开始处理消息。
-
发送和接收消息:
- 通过
runtime.send_message方法发送两个问题给代理,并打印出问题和相应的回答。 - 第一个问题是关于在Seattle的有趣活动。
- 第二个问题是关于代理提到的第一个活动。
- 通过
-
停止运行时环境:
- 一旦消息处理完成,运行时环境被停止。
完成的功能:
- 这段代码创建了一个能够理解上下文的聊天代理,它可以接收用户的问题,并根据之前的对话历史生成相关的回答。
- 该代理使用了一个远程的AI模型(通过
OpenAIChatCompletionClient)来生成回答。 - 通过将用户的每个问题和代理的回答存储在上下文中,代理能够理解对话的流程并提供更相关的回答。
请注意,为了使代码能够运行,需要确保 autogen_core 和 autogen_ext 库是可用的,并且 OpenAIChatCompletionClient 能够与指定的模型进行通信。此外,代码中使用了异步编程,这意味着它需要在支持异步操作的Python环境中运行。
另一个例子
from dataclasses import dataclass
from autogen_core import AgentId, MessageContext, RoutedAgent, SingleThreadedAgentRuntime, message_handler
from autogen_core.model_context import BufferedChatCompletionContext
from autogen_core.models import AssistantMessage, ChatCompletionClient, SystemMessage, UserMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient@dataclass
class Message:content: strclass CodeExplainerAgent(RoutedAgent):def __init__(self, model_client: ChatCompletionClient) -> None:super().__init__("A code explainer agent")self._system_messages = [SystemMessage(content="You are an AI assistant specialized in explaining Python code.")]self._model_client = model_clientself._model_context = BufferedChatCompletionContext(buffer_size=5)@message_handlerasync def handle_user_message(self, message: Message, ctx: MessageContext) -> Message:user_message = UserMessage(content=message.content, source="user")await self._model_context.add_message(user_message)response = await self._model_client.create(self._system_messages + (await self._model_context.get_messages()),cancellation_token=ctx.cancellation_token,)assert isinstance(response.content, str)await self._model_context.add_message(AssistantMessage(content=response.content, source=self.metadata["type"]))return Message(content=response.content)runtime = SingleThreadedAgentRuntime()model_client = OpenAIChatCompletionClient(model="GLM-4-Air-0111",api_key="your api key",base_url="https://open.bigmodel.cn/api/paas/v4/",model_capabilities={"vision": True,"function_calling": True,"json_output": True,}
)await CodeExplainerAgent.register(runtime,"code_explainer_agent",lambda: CodeExplainerAgent(model_client),
)runtime.start()
agent_id = AgentId("code_explainer_agent", "default")# 代码解释示例
message = Message("解释以下代码:\n```python\nimport numpy as np\nA = np.array([[1, 2], [3, 4]])\nprint(A.T)\n```")
print(f"Question: {message.content}")
response = await runtime.send_message(message, agent_id)
print(f"Response: {response.content}")
print("-----")# 继续问上下文相关问题
message = Message("代码中的 `.T` 是什么意思?")
print(f"Question: {message.content}")
response = await runtime.send_message(message, agent_id)
print(f"Response: {response.content}")await runtime.stop()
Question: 解释以下代码:
```python
import numpy as np
A = np.array([[1, 2], [3, 4]])
print(A.T)
```
Response: 这段代码首先导入了NumPy库,并将其命名为`np`。NumPy是一个用于科学计算的Python库,它提供了一个强大的N维数组对象和一系列用于快速操作数组的函数。接着,代码创建了一个2x2的NumPy数组`A`,其元素为[[1, 2], [3, 4]]。最后,代码使用`.T`属性来获取数组`A`的转置,并将其打印出来。`.T`属性是NumPy数组的一个特性,它返回数组的转置视图。对于二维数组,这意味着行和列将互换。当运行这段代码时,输出将是:```
[[1 3][2 4]]
```这显示了原始数组`A`的转置,其中第一行[1, 2]变成了第一列,第二行[3, 4]变成了第二列。
-----
Question: 代码中的 `.T` 是什么意思?
Response: 在 NumPy 中,`.T` 属性用于获取数组的转置。转置是一个矩阵操作,它将矩阵的行和列进行互换。例如,如果一个矩阵 `A` 的形状是 `(m, n)`,那么它的转置 `A.T` 的形状将是 `(n, m)`。在您的代码示例中:```python
import numpy as np
A = np.array([[1, 2], [3, 4]])
print(A.T)
````A` 是一个 2x2 的矩阵:```
A = [[1, 2],[3, 4]]
```应用 `.T` 属性后,我们得到 `A` 的转置:```
A.T = [[1, 3],[2, 4]]
```这里,原来的行变成了列,原来的列变成了行。对于更高维度的数组,`.T` 同样适用,并且可以结合 `axes` 参数进行更复杂的转置操作,但那超出了您当前代码的范围。对于大多数矩阵操作,简单地使用 `.T` 就足够了。
参考链接:https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/components/model-context.html
相关文章:
Autogen_core: Model Context
目录 示例代码代码解释另一个例子 示例代码 from dataclasses import dataclassfrom autogen_core import AgentId, MessageContext, RoutedAgent, SingleThreadedAgentRuntime, message_handler from autogen_core.model_context import BufferedChatCompletionContext from …...
SpringBoot AOP 和 事务
SpringBoot 整合 AOP 动态代理技术 JDK 动态代理 JDK 动态代理是 Java 自带的一种代理方式。它要求目标类必须有接口,基于这个接口,JDK 在运行时会动态生成一个代理对象。这个代理对象和目标对象就像 “拜把子” 的兄弟,因为它们都实现了相同…...
Ubuntu全面卸载mysql
如果你已经看到whereis mysql输出了与MySQL相关的路径,说明MySQL仍然存在于系统中。要卸载MySQL,可以按照以下步骤操作,确保完全删除所有相关的文件和配置: 1. 停止MySQL服务 首先,停止MySQL服务: sudo …...
android的gradle
资料: GitHub - ChenSWD/CopyGradleInAction: 备份《Gradle IN Action》书中的源码,添加了部分注释 //github上一个开源项目,外加pdf书 Gradle User Manual gradle官网 讲的挺好的博客 Gradle之重新认识Gradle(项目结构、命令行、tas…...
前端开发之jsencrypt加密解密的使用方法和使用示例
目录 RSA密钥生成选项简介 jsencrypt 使用教程 一、安装 jsencrypt 二、使用 jsencrypt 进行加密和解密 1. 创建密钥对 2. 加密数据 3. 解密数据 三、实际应用示例 加密数据并存储到 localStorage 中: 从 localStorage 中读取加密数据并解密: …...
电路研究9.2.5——合宙Air780EP中GPS 相关命令使用方法研究
注:本命令仅适用于合宙 4G CAT1 模块(Air780EG 系列)。 正好,我们使用的Air780EP好像也有4G CAT1模块,好像也属于Air780EG系列吧。 这个例子好像比较少就个。 18.9 使用方法举例 18.1GPS 开关:ATCGNSPWR 这…...
Python标准库 - os (3) 调度策略、系统信息
文章目录 6 调度策略6.1 调度策略常量6.2 访问和设置进程的调度策略 7 系统信息7.1 系统信息7.2 系统配置信息7.3 系统负载7.4 路径相关常量7.5 生成随机字节 os模块提供了各种操作系统接口。包括环境变量、进程管理、进程调度、文件操作等方面。 这里整理了进程调度和查看系统…...
【NLP251】NLP RNN 系列网络
NLP251 系列主要记录从NLP基础网络结构到知识图谱的学习 1.原理及网络结构 1.1RNN 在Yoshua Bengio论文中( http://proceedings.mlr.press/v28/pascanu13.pdf )证明了梯度求导的一部分环节是一个指数模型…...
【漫话机器学习系列】067.希腊字母(greek letters)-写法、名称、读法和常见用途
希腊字母(Greek Letters) 希腊字母在数学、科学、工程学和编程中广泛使用,常用于表示变量、常量、参数、角度等。以下是希腊字母的完整列表及其常见用途。 大写与小写希腊字母表 大写小写名称(英文)名称(…...
2.文件IO
2.文件IO **1. 文件I/O概述****2. 文件I/O函数接口****3. 文件定位****4. 文件描述符与文件流指针的转换****5. 文件I/O与标准I/O的比较****6. 练习与作业****7. 文件I/O与标准I/O的对应关系****8. 其他注意事项****9. 总结** 1. 文件I/O概述 文件I/O:操作系统为了…...
毕业设计--具有车流量检测功能的智能交通灯设计
摘要: 随着21世纪机动车保有量的持续增加,城市交通拥堵已成为一个日益严重的问题。传统的固定绿灯时长方案导致了大量的时间浪费和交通拥堵。为解决这一问题,本文设计了一款智能交通灯系统,利用车流量检测功能和先进的算法实现了…...
【SpringBoot教程】Spring Boot + MySQL + HikariCP 连接池整合教程
🙋大家好!我是毛毛张! 🌈个人首页: 神马都会亿点点的毛毛张 在前面一篇文章中毛毛张介绍了SpringBoot中数据源与数据库连接池相关概念,今天毛毛张要分享的是关于SpringBoot整合HicariCP连接池相关知识点以及底层源码…...
设计模式的艺术-策略模式
行为型模式的名称、定义、学习难度和使用频率如下表所示: 1.如何理解策略模式 在策略模式中,可以定义一些独立的类来封装不同的算法,每个类封装一种具体的算法。在这里,每个封装算法的类都可以称之为一种策略(Strategy…...
【memgpt】letta 课程1/2:从头实现一个自我编辑、记忆和多步骤推理的代理
llms-as-operating-systems-agent-memory llms-as-operating-systems-agent-memory内存 操作系统的内存管理...
动态规划DP 最长上升子序列模型 合唱队形(题目分析+C++完整代码)
概览检索 动态规划DP 最长上升子序列模型 合唱队形 原题链接 AcWiing 482. 合唱队形 题目描述 N位同学站成一排,音乐老师要请其中的 (N−K)位同学出列,使得剩下的 K位同学排成合唱队形。 合唱队形是指这样的一种队形:设 K位同学从左到右…...
【踩坑】解决Hugging-face下载问题
解决Hugging-face下载问题 问题1:couldnt connect to https://huggingface.co问题2:HTTPSConnectionPool(hostcdn-lfs-us-1.hf-mirror.com, port443)设置hf_transfer加快速度 问题3:requests.exceptions.ChunkedEncodingError: (Connection b…...
Spring AI 在微服务中的应用:支持分布式 AI 推理
1. 引言 在现代企业中,微服务架构 已成为开发复杂系统的主流方式,而 AI 模型推理 也越来越多地被集成到业务流程中。如何在分布式微服务架构下高效地集成 Spring AI,使多个服务可以协同完成 AI 任务,并支持分布式 AI 推理&#x…...
5.3.2 软件设计原则
文章目录 抽象模块化信息隐蔽与独立性衡量 软件设计原则:抽象、模块化、信息隐蔽。 抽象 抽象是抽出事物本质的共同特性。过程抽象是指将一个明确定义功能的操作当作单个实体看待。数据抽象是对数据的类型、操作、取值范围进行定义,然后通过这些操作对数…...
java求职学习day20
1 在线考试系统 1.1 软件开发的流程 需求分析文档、概要设计文档、详细设计文档、编码和测试、安装和调试、维护和升级 1.2 软件的需求分析 在线考试系统的主要功能分析如下: ( 1 )学员系统 (1.1)用户模块&…...
Python NumPy(8):NumPy 位运算、NumPy 字符串函数
1 NumPy 位运算 位运算是一种在二进制数字的位级别上进行操作的一类运算,它们直接操作二进制数字的各个位,而不考虑数字的整体值。NumPy 提供了一系列位运算函数,允许对数组中的元素进行逐位操作,这些操作与 Python 的位运算符类似…...
PowerPaint-V1开源大模型实战:低配RTX3060跑通纯净消除+上下文智能填充
PowerPaint-V1开源大模型实战:低配RTX3060跑通纯净消除上下文智能填充 用最通俗的话,带你玩转最先进的图像修复技术 1. 项目简介:听懂人话的图像修复神器 今天给大家介绍一个特别实用的AI工具——PowerPaint-V1。这可不是普通的修图软件&…...
JAVA进阶-锁
1.悲观锁和乐观锁悲观锁:在修改数据时,一定有别的线程来使用,一定会发生并发冲突,所以在获取数据的时候会加锁。JAVA中的synchronized和lock都是悲观锁。乐观锁:在修改数据时,一定没有别的线程来使用&#…...
Hugging Face离线模型实战:环境变量配置的陷阱与本地路径加载的可靠方案
1. 为什么环境变量配置在离线场景下容易翻车? 最近在部署Hugging Face模型时,我发现官方推荐的环境变量配置方法在实际离线环境中经常失效。这个问题困扰了我很久,直到改用本地路径加载才彻底解决。先说说环境变量方法的坑在哪里。 环境变量看…...
基于机智云与STM32的ESP01S智能配网实战:从调试工具到APP联动
1. ESP01S智能配网的核心价值与场景 当你第一次接触智能硬件开发时,最头疼的莫过于让设备连上Wi-Fi。传统做法需要手动硬编码SSID和密码,每次换网络环境都得重新烧录固件,这简直是对开发者耐心的终极考验。而基于机智云的ESP01S配网方案&…...
小白也能上手:Phi-3-vision-128k图文对话模型快速体验教程
小白也能上手:Phi-3-vision-128k图文对话模型快速体验教程 1. 认识Phi-3-vision-128k图文对话模型 Phi-3-Vision-128K-Instruct是微软推出的轻量级多模态模型,属于Phi-3模型家族的最新成员。这个模型最大的特点是能够同时理解图片和文字,支…...
CCMusic Dashboard技术解析:为何放弃Transformer?CNN在局部时频模式识别上的归纳偏置优势分析
CCMusic Dashboard技术解析:为何放弃Transformer?CNN在局部时频模式识别上的归纳偏置优势分析 获取更多AI镜像 想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频…...
《告别“信号迷宫”:沃虎ChipLAN如何为工业4.0设备打造“直连高速路”》
在工业4.0设备向小型化、高密度、高速率演进的浪潮中,传统环形网络变压器正面临严峻挑战。其固有的绕线工艺、体积限制以及难以精确控制的寄生参数(如分布电容和漏感),在高频信号传输中极易形成“信号迷宫”,导致插入损…...
Qwen3-TTS-Tokenizer保姆级教程:从环境部署到API调用全流程
Qwen3-TTS-Tokenizer保姆级教程:从环境部署到API调用全流程 1. 为什么你需要这个教程 如果你正在寻找一个能够高效处理音频编解码的解决方案,Qwen3-TTS-Tokenizer-12Hz可能是你的理想选择。这个由阿里巴巴Qwen团队开发的模型,能够在保持超高…...
RVC模型开源社区贡献指南:GitHub Pull Request全流程解析
RVC模型开源社区贡献指南:GitHub Pull Request全流程解析 你是不是也用过RVC模型,觉得它很酷,甚至想过“要是能自己改点代码,让它更好用就好了”?或者,你发现了一个小bug,或者有个很棒的新功能…...
寻音捉影·侠客行部署案例:某AI Lab将其作为语音数据清洗前置模块
寻音捉影侠客行部署案例:某AI Lab将其作为语音数据清洗前置模块 1. 引言:当AI Lab遇上音频数据清洗的“江湖侠客” 想象一下,你是一个AI实验室的研究员,手头有堆积如山的语音数据——可能是数千小时的会议录音、用户访谈&#x…...
