2024.10.30 OpenAI swarm和Ollama快速构建本地多智能体服务
OpenAI 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, Agent
client = Swarm()
def transfer_to_agent_b():
return agent_b
agent_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_b
agent_a = Agent(
name="Agent A",
model="qwen2.5:7b", # 在构建智能体时指定ollama中的模型,传入在ollama中构建好的大模型名称即可,例如qwen2.5:7b
instructions="You are a helpful agent.",
functions=[transfer_to_agent_b],
)
agent_b = Agent(
name="Agent B",
model="qwen2.5:7b", # 在构建智能体时指定ollama中的模型,传入在ollama中构建好的大模型名称即可,例如qwen2.5:7b
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"])
总结一下,若想将swarm和ollama结合,比官方示例多了三步,非常简单:
利用OpenA的接口(安装swarm时会自动下载),建立与ollama服务连接的客户端 在swarm构建时,指定与ollama连接的客户端 在构建智能体时指定ollama中的模型 大家可以利用上述三个步骤自行尝试改造swarm开源代码中提供的示例进行尝试,后面有时间也会讲讲swarm框架的具体用法供大家参考。