这个系列文章记录了学习微软 AutoGen 的过程,与 smolagents 学习笔记系列一样,仍然以官方教程+自己的理解为主线,中间可能穿插几个番外支线的形式写博客。
【注意】:在阅读这篇文章之前需要确保已经按照其 Installation
小节完成必要的安装,这部分基本没什么内容,这里我以 conda 方式管理环境为例将浓缩一下步骤:
$ conda create -n autogen python=3.12
$ conda activate autogen
$ pip install -U "autogen-agentchat"
$ pip install "autogen-ext[openai]" "autogen-ext[azure]"
这篇文章瞄准的是官网教程 Tutorial
小节中的 Models
部分,官网教程中的第一小节 Introduction
只有一页内容,主要是提供了几个跳转链接,下面是上述三个小节的链接,感兴趣的可以进入查看下,我在此处的第一篇就直接从 Models
开始:
- Installation:https://microsoft.github.io/autogen/stable/user-guide/agentchat-user-guide/installation.html# ;
- Introduction:https://microsoft.github.io/autogen/stable/user-guide/agentchat-user-guide/tutorial/index.html ;
- Models:https://microsoft.github.io/autogen/stable/user-guide/agentchat-user-guide/tutorial/models.html# ;
OpenAI
【注意】:
- AutoGen与OpenAI的绑定比较强,教程中会出现大量的在线API调用,建议在某宝上买一点Token体验下,初学者用多5刀就足够体验完这个系列的教程内容了;
- 示例尽量不要用 openai.py, ollama.py, autogen.py 这种文件名,因为很容易让解释器从示例中找类进而引发循环载入,建议都用 demo.py 命名。如果你遇到了奇奇怪怪的报错,首先应该检查你的文件名是否正确;
官网提供的代码拼接起来是无法直接运行的,因为其将await
字段没有包在async
函数中,这里需要对其进行修改:
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_core.models import UserMessage
import asyncio, osos.environ["OPENAI_API_KEY"] = "你的API Key,通常以sk-开头"openai_model_client = OpenAIChatCompletionClient(model="gpt-4o-2024-08-06",# api_key="sk-...", # Optional if you have an OPENAI_API_KEY environment variable set.
)async def main():result = await openai_model_client.create([UserMessage(content="What is the capital of France?", source="user")])print(result)asyncio.run(main())
运行后结果如下:
$ python demo.pyfinish_reason='stop' content='The capital of France is Paris.' usage=RequestUsage(prompt_tokens=15, completion_tokens=8) cached=False logprobs=None thought=None
Azure OpenAI && Azure AI Foundry && Gemini
- Azure OpenAI、Azure AI Foundry 这两个示例需要你在微软的 Azure 云上已经部署好一个 OpenAI 的模型,我后面会在番外篇记录如何部署,届时再回头对这部分示例代码进行详解。如果你已经在Azure上部署好了模型,可以自己尝试运行一下代码;
- Gemini 是谷歌提供的一个模型,我申请到API Key后会在这里进行补充;
Ollama
接下来这个小节是重头戏,因为我先前的几片学习笔记和我平时的实验环境都使用的是Ollama本地模型或HuggingFace在线模型。
在运行示例代码之前你需要确认本地有哪些可用模型,后面引用的模型名 必须以命令输出的为准:
$ ollama list
(LLM) ~/Desktop/AutoGen $ ollama list
NAME ID SIZE MODIFIED
llama3:latest 365c0bd3c000 4.7 GB 2 weeks ago
官网的示例同样不能直接运行,修改后如下:
from autogen_core.models import UserMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient
import asynciomodel_client = OpenAIChatCompletionClient(model="llama3:latest", # 填写你本地可用的模型名base_url="http://localhost:11434/v1",api_key="placeholder",model_info={"vision": False,"function_calling": True,"json_output": False,"family": "unknown",},
)async def main():response = await model_client.create([UserMessage(content="What is the capital of France?", source="user")])print(response)if __name__ == "__main__":asyncio.run(main())
运行输出如下:
$ python demo.pyfinish_reason='stop' content='The capital of France is Paris.' usage=RequestUsage(prompt_tokens=17, completion_tokens=8) cached=False logprobs=None thought=None
Semantic Kernel Adapter
这部分其实介绍的是如何使用AutoGen提供的 Semantic Kernel 适配器,这玩意简单来说就是把输入 prompt 经过多部拆解,并在必要时检索外部数据,转化为更好的 prompt 给模型。这个也是微软开源的一个项目,后面我也会出一个Semantic Kernel的学习笔记系列。
根据官网文档介绍,AutoGen 提供了多个 Semantic Kernel 适配器:
semantic-kernel-anthropic
: Install this extra to use Anthropic models.semantic-kernel-google
: Install this extra to use Google Gemini models.semantic-kernel-ollama
: Install this extra to use Ollama models.semantic-kernel-mistralai
: Install this extra to use MistralAI models.semantic-kernel-aws
: Install this extra to use AWS models.semantic-kernel-hugging-face
: Install this extra to use Hugging Face models.
如果你想要安装哪个适配器则用下面的命令:
$ pip install "autogen-ext[适配器名]"
官网的demo中使用的是 Anthropic
公司的接口,这样的话又需要我们去申请API,所以我这里的示例就直接只用Ollama的适配器,这个是纯本地的模型就不涉及API问题,首先根据官网教程安装这个适配器:
pip install "autogen-ext[semantic-kernel-ollama]"
然后对官网代码进行改动:
import os, asynciofrom autogen_core.models import UserMessage
from autogen_ext.models.semantic_kernel import SKChatCompletionAdapter
from semantic_kernel import Kernel
# from semantic_kernel.connectors.ai.anthropic import AnthropicChatCompletion, AnthropicChatPromptExecutionSettings
from semantic_kernel.connectors.ai.ollama import OllamaChatCompletion, OllamaChatPromptExecutionSettings
from semantic_kernel.memory.null_memory import NullMemory# 创建Ollama客户端
sk_client = OllamaChatCompletion(ai_model_id="llama3:latest"
)
# 设置推理参数,这里只对温度进行了设置
settings = OllamaChatPromptExecutionSettings(temperature=0.2,
)# 适配Ollama客户端到适配器上
anthropic_model_client = SKChatCompletionAdapter(sk_client, kernel=Kernel(memory=NullMemory()), prompt_settings=settings
)# 发送一个模型到Ollama模型上
async def main():model_result = await anthropic_model_client.create(messages=[UserMessage(content="What is the capital of France?", source="User")])print(model_result)if __name__ == "__main__":asyncio.run(main())
运行结果如下:
$ python demo.py
finish_reason='stop' content='The capital of France is Paris.' usage=RequestUsage(prompt_tokens=17, completion_tokens=8) cached=False logprobs=None thought=None
题外话
其实根据上面这么多个实例我们可以发现,对于同一个问题而言所有模型输出的结果基本一致:
- OpenAI:
finish_reason='stop' content='The capital of France is Paris.' usage=RequestUsage(prompt_tokens=15, completion_tokens=8) cached=False logprobs=None thought=None
- Ollama without SK adaptor:
finish_reason='stop' content='The capital of France is Paris.' usage=RequestUsage(prompt_tokens=17, completion_tokens=8) cached=False logprobs=None thought=None
- Ollama with SK adaptor:
finish_reason='stop' content='The capital of France is Paris.' usage=RequestUsage(prompt_tokens=17, completion_tokens=8) cached=False logprobs=None thought=None
那么,我们就可以对Agent性能或者期望进行一次总结:
- 我们期望 Agent 每次都输出标准格式的内容,因为这样方便从中提取有效信息。
- 我们期望不同体量的 Agent 输出的结果基本一致,这样方便压缩成本;
- 我们期望对于同一个问题,Agent 的输出最好保持稳定,这样可以用来判定模型有效性;
如果你之前有阅读并实操过我关于 smolagents 库的笔记的话会发现模型每次输出的结果都存在变化,很难做到一次就得到最终答案,即便模型可能在第一次就给出了结论,但因为格式等原因会多次轮询模型。
这里其实就体现了 Agent 设计的优劣了,因为LLM最重要的是 prompt ,一个好的 Agent 会提供更严谨的提示词与恰当的参数来限制模型的内容,甚至规定好格式只允许模型这样输出,这样就可以拉低模型性能之间的差距,因为我们知道参数量越大的模型越容易遵守你的制定的规则,因为它能够读懂你的规则,所以让满血的模型数据规定格式内容是非常容易的,但对于量化模型而言就很困难了。