前提
1、部署
需要开通azure的openai部署, 如未开通,可参考文章进行开通:微软Azure申请OpenAI以及部署使用教程
2、寻找必备资料
开通成功之后,需要获取必备的资料,才能进行后续的操作
-
api-version: azure的api版本,在这里查看learn.microsoft.com/en-us/azure…, 当前最新的是2023-08-01-preview -
ApiKey: API的密钥, 在部署的实例的的key & endpoint页面上找到 -
EndPoint: 部署的地址,在部署的实例的key & endpoint页面上找到 -
Deployment Name:模型的部署名,在模型部署的页面上,可以找到
一、调用
如果模型是 gpt 3.5 gpt 4等,不能用Completions模式, 需要用 Chat模式,否则会报错。报错信息类似
openai.error.InvalidRequestError: The completion operation does not work with the specified model, gpt-35-turbo. Please choose different model and try again. You can learn more about which models can be used with each operation here: https://go.microsoft.com/fwlink/?linkid=2197993.
1、使用Openai的官方库
主要差别是,申明
openai.api_type = "azure",在创建实例的时候,需要添加 engine参数,也就是在azure上面部署的 deployment name
import openai
openai.api_type = "azure"
openai.api_base = "https://aaaaaa.openai.azure.com/" #上面的End point
openai.api_version = "2023-08-01-preview"
openai.api_key = 'xxxxx'
# 用chat模式
chat_completion = openai.ChatCompletion.create(
engine="gpt-35-turbo",
messages=[
{"role": "system", "content": "你是语言专家,帮我把英文翻译成中文"},
{"role": "user", "content": "Hello world"},
]
)
print(chat_completion.choices[0].message.content)
2、在Langchain上使用
Chat模式,在langchin上是AzureChatOpenAI,所以不能用AzureOpenAI,否则会报错。
实例代码如下
import os
from langchain import PromptTemplate, LLMChain
from langchain.chat_models import AzureChatOpenAI
#初始化配置
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_VERSION"] = "2023-08-01-preview"
os.environ["OPENAI_API_BASE"] = "https://xxxx.openai.azure.com/" #上面的End point
os.environ["OPENAI_API_KEY"] = "xxxxxxxxx"
# 创建实例 Azure OpenAI
llm = AzureChatOpenAI(
deployment_name="gpt-35-turbo", #上面的deployment name
model_name="gpt-35-turbo" #deployment 对应的model
)
prompt=PromptTemplate(
template="请问,{country}的首都是哪里 ?",
input_variables=["country"],
)
chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run("中国"))