9.0
重磅
AI SCORE
工具产品2024-02-09 04:36
Ollama宣布OpenAI API完全兼容
Hacker News · ollama.ai#Ollama#开源#成本降低
Editor brief · 编辑速览
本地模型工具Ollama支持OpenAI API接口,程序员可无缝用开源模型替换商业API调用。大幅降低成本和厂商锁定。
Ollama 现已内置兼容 OpenAI Chat Completions API,让你可以在本地用 Ollama 运行更多工具和应用。
首先下载 Ollama 并拉取一个模型,比如 Llama 2 或 Mistral:
ollama pull llama2
要调用 Ollama 的 OpenAI 兼容 API 端点,使用相同的 OpenAI 格式,只需把主机名改成 http://localhost:11434:
curl http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "llama2",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Hello!"
}
]
}'
from openai import OpenAI
client = OpenAI(
base_url = 'http://localhost:11434/v1',
api_key='ollama', # required, but unused
)
response = client.chat.completions.create(
model="llama2",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who won the world series in 2020?"},
{"role": "assistant", "content": "The LA Dodgers won in 2020."},
{"role": "user", "content": "Where was it played?"}
]
)
print(response.choices[0].message.content)
import OpenAI from 'openai'
const openai = new OpenAI({
baseURL: 'http://localhost:11434/v1',
apiKey: 'ollama', // required but unused
})
const completion = await openai.chat.completions.create({
model: 'llama2',
messages: [{ role: 'user', content: 'Why is the sky blue?' }],
})
console.log(completion.choices[0].message.content)
Vercel AI SDK 是一个用于构建对话流式应用的开源库。要开始使用,用 create-next-app 克隆示例仓库:
npx create-next-app --example https://github.com/vercel/ai/tree/main/examples/next-openai example
cd example
然后在 app/api/chat/route.ts 中进行以下两处编辑,将聊天示例更新为使用 Ollama:
const openai = new OpenAI({
baseURL: 'http://localhost:11434/v1',
apiKey: 'ollama',
});
const response = await openai.chat.completions.create({
model: 'llama2',
stream: true,
messages,
});
npm run dev
最后在浏览器中打开示例应用,访问 http://localhost:3000。
Autogen 是微软推出的一个流行开源框架,用于构建多 Agent 应用。对于此示例,我们将使用 Code Llama 模型:
ollama pull codellama
pip install pyautogen
然后创建 Python 脚本 example.py 以在 Autogen 中使用 Ollama:
from autogen import AssistantAgent, UserProxyAgent
config_list = [
{
"model": "codellama",
"base_url": "http://localhost:11434/v1",
"api_key": "ollama",
}
]
assistant = AssistantAgent("assistant", llm_config={"config_list": config_list})
user_proxy = UserProxyAgent("user_proxy", code_execution_config={"work_dir": "coding", "use_docker": False})
user_proxy.initiate_chat(assistant, message="Plot a chart of NVDA and TESLA stock price change YTD.")
最后运行示例,让 assistant 自动编写绘制图表的代码:
python example.py
这是对 OpenAI API 的初步实验性支持。未来考虑的改进包括:
欢迎提交 GitHub issues!更多信息请参阅 OpenAI 兼容性文档。