OpenAI开源了多智能体编排的工程swarm,今天介绍一下swarm与OLLAMA如何结合使用的教程,在本地构建自己的多智能体服务,并给大家实践演示几个案例。
安装步骤
- 安装
ollama
,在官网下载对应操作系统的版本即可,下载后用ollama部署大模型,网上教程很多,本文不再描述。 - 安装
ollama
的python接口:
pip install ollama
- 安装
swarm
框架:
pip install git+https://github.com/openai/swarm.git
注意,这一步的前提是已经安装了git
,如果本地没有安装请先行下载安装
服务构建示例
swarm官网给出的使用示例如下:
from swarm import Swarm, Agentclient = Swarm()def transfer_to_agent_b():return agent_bagent_a = Agent(name="Agent A",instructions="You are a helpful agent.",functions=[transfer_to_agent_b],
)agent_b = Agent(name="Agent B",instructions="Only speak in Haikus.",
)response = client.run(agent=agent_a,messages=[{"role": "user", "content": "I want to talk to agent B."}],
)print(response.messages[-1]["content"])
在这个示例的基础上,与ollama
以及在ollama
中安装的大模型结合的方法如下:
from swarm import Swarm, Agent# 利用OpenAI的接口(安装swarm时会自动下载),建立与ollama服务连接的客户端
from openai import OpenAI
ollama_client = OpenAI(base_url = 'http://localhost:11434/v1',api_key='ollama', # required, but unused
)# 在swarm构建时,指定与ollama连接的客户端
client = Swarm(client=ollama_client)def transfer_to_agent_b():return agent_bagent_a = Agent(name="Agent A",model="qwen2.5:7b", # 在构建智能体时指定ollama中的模型,传入在ollama中构建好的大模型名称即可,例如qwen2.5:7binstructions="You are a helpful agent.",functions=[transfer_to_agent_b],
)agent_b = Agent(name="Agent B",model="qwen2.5:7b", # 在构建智能体时指定ollama中的模型,传入在ollama中构建好的大模型名称即可,例如qwen2.5:7binstructions="Only speak in Haikus.",
)response = client.run(agent=agent_a,messages=[{"role": "user", "content": "I want to talk to agent B."}],
)print(response.messages[-1]["content"])
总结一下,若想将swarm
和ollama
结合,比官方示例多了三步,非常简单:
- 利用OpenAI的接口(安装swarm时会自动下载),建立与ollama服务连接的客户端
- 在swarm构建时,指定与ollama连接的客户端
- 在构建智能体时指定ollama中的模型
大家可以利用上述三个步骤自行尝试改造swarm
开源代码中提供的示例进行尝试,后面有时间也会讲讲swarm框架的具体用法供大家参考。