如何本地部署OpenAI
前言
本文将深入探讨 OpenAI 本地调用的技术细节,涵盖环境搭建、模型部署、接口调用等方面,并给出案例,阐述 OpenAI 本地调用的技巧,方便使用者快速上手,做自己任务。
一、为什么本地部署
1. 网络限制
不能直接访问,需要上外网,就这需要挂梯子或是科学上网,带来查询不便。
#官方接口表
https://api.openai.com
https://api.openai.com/v1
https://api.openai.com/v1/chat/completions
2. 优势
1, 安全
数据安全与隐私保障: 敏感数据无需上传至云端,有效降低了数据泄露风险,尤其适用于金融、医疗等对数据安全要求较高的领域。
2, 速度
更低的延迟与更高的响应速度: 本地部署消除了网络传输带来的延迟,使得模型推理速度更快,用户体验更加流畅。
3, 定制化
更强的定制化能力: 开发者可以根据具体需求对模型进行 fine-tuning,使其更贴合特定场景和应用。
4, 成本
更低的成本: 对于需要频繁调用模型的场景,本地部署可以节省大量的云端 API 调用费用。
二、调用方式
1. 使用openai库
pip install openai
2. 使用Requests库
pip install requests
三、Openai接口
1. 聊天
from openai import OpenAI
client = OpenAI(
base_url='https://xxxxxx.plus/v1',
# sk-xxx替换为自己的key
api_key='sk-xxx'
)
completion = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system", "content": "You are a helpful assistant."},
{
"role": "user", "content": "Hello!"}
]
)
print(completion.choices[0].message)
下面展示一段问答效果,后面接口返回结果不再展示
completion = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system", "content": "You are a helpful assistant."},
{
"role": "user", "content": "Can you intruduce youself"}
]
)
print(completion.choices[0].message)
#下面是测试结果,只需要运行一个python脚本即可.
(base) root@autodl-container-df76488929-09e9a4d5:~/autodl-tmp# python openaitest.py
ChatCompletionMessage(content='Hello! How can I assist you today?', refusal=None, role='assistant', audio=None, function_call=None, tool_calls=None)
(base) root@autodl-container-df76488929-09e9a4d5:~/autodl-tmp# python openaitest.py
ChatCompletionMessage(content="Sure! I'm an AI developed by OpenAI designed to assist with a variety of tasks. I'm here to provide information, answer questions, help with writing, and support you in whatever way I can. My responses are based on extensive training on diverse datasets up to October 2023. How can I assist you today?", refusal=None, role='assistant', audio=None, function_call=None, tool_calls=None)
2. 图片
from openai import OpenAI
client = OpenAI(
base_url='https://xxxxxx.plus/v1',
# sk-xxx替换为自己的key
api_key='sk-xxx'
)
response = client.chat