【报错解决】使用openai的api时出现APIConnectionError: Connection error.错误

openai api使用

openai包一直更新,升级之后很多接口变了。如果使用1.8版本的openai的话,现在使用api的方式如下:

按照官方文档,你需要做以下几步:

  1. 填写上你的api key
  2. 先定义client
  3. 调用client 的chat completions.create功能
from openai import OpenAI
import os
API_KEY = "your key"
client=OpenAI(api_key= API_KEY)
completion = client.chat.completions.create(
  model="gpt-4",
  messages=[
    {
    
    "role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
    {
    
    "role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}
  ]
)

连接错误问题解决

直接运行上面代码的话,会报错APIConnectionError: Connection error.
因为API需要代理才能访问,要指定HTTP和HTTPS请求的代理服务器。
添加上下面的代码即可。

os.environ["http_proxy"] = "http://localhost:7890"
os.environ["https_proxy"] = "http://localhost:7890"

使用openai api访问其他模型

另外,我们可以通过设置 API_BASE 参数,访问其他需要通过api访问的模型
比如,零一万物模型兼容openai api,就可以通过下面这种方式访问:

import openai
from openai import OpenAI

API_BASE = "https://api.lingyiwanwu.com/v1"
API_KEY = "your key"

os.environ["http_proxy"] = "http://localhost:7890"
os.environ["https_proxy"] = "http://localhost:7890"

client = OpenAI(
    # defaults to os.environ.get("OPENAI_API_KEY")
    api_key=API_KEY,
    base_url=API_BASE
)
completion = client.chat.completions.create(
    model="yi-34b-chat-0205",
    messages=[{
    
    "role": "user", "content": "Hi, who are you?"}]
)
print(completion)

猜你喜欢

转载自blog.csdn.net/a61022706/article/details/137926094