type
status
date
slug
summary
tags
category
icon
password
反向代理方式
#老版本,过时了,1.2已经不支持了
openai.api_base = "https://api.youraddress.com/v1" #在这里设置即可,需要特别注意这里的/v1是必须的,否则报错。前面的地址注意替换即可。
#版本1.2+的方式
from pathlib import Path
from openai import OpenAI
client = OpenAI(
base_url="https://myapi.myapi.com/v1",
api_key="your_api_key"
)
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
]
)
print(completion.choices[0].message)
正向代理方式
直接通过openai.proxy设置openai的代理:
import os
import openai
#已经过时了
openai.api_key = "yourAPIKey"
openai.proxy = "http://your.proxy.address:port" #在这里设置你的代理信息即可
#新版本方式
from pathlib import Path
from openai import OpenAI
#代码部分添加
import os
proxy_url = 'http://127.0.0.1'
proxy_port = '8080'
#设置环境变量
os.environ['http_proxy'] = f'{proxy_url}:{proxy_port}'
os.environ['https_proxy'] = f'{proxy_url}:{proxy_port}'
#在代码开始部分添加
client = OpenAI(
api_key="your_api_key"
)
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
]
)
print(completion.choices[0].message)
或者简写如下:
import httpx
from openai import OpenAI
client = OpenAI(
api_key="",
http_client=httpx.Client(
proxies="http://127.0.0.1:7890",
transport=httpx.HTTPTransport(local_address="0.0.0.0"),
),
)