赞
踩
import openai
openai.api_key = "{上面复制的key}"
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who won the world series in 2020?"},
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
{"role": "user", "content": "Where was it played?"}
]
)
print(completion.choices[0].message)
使用api_base:
import openai
openai.api_key = "sk-NYsoG3VBKDiTuvdtC969F95aFc4f45379aD3854a93602327"
openai.api_base="https://key.wenwen-ai.com/v1"
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
]
)
print(completion.choices[0].message)
但是现在api的调用改版了,需要使用新的调用方式,也很简单。
You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.
You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface.
Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`
A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742
由于我的api已经使用完了,所以可以某宝上买一个api_key,直接使用;
新版本就是把ChatCompletion变成了chat.completions
from openai import OpenAI
api_key = ''
client = OpenAI(api_key=api_key)
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who won the world series in 2020?"},
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
{"role": "user", "content": "Where was it played?"}
]
)
print(response.choices[0].message.content)
或者:加上base_url:
from openai import OpenAI client = OpenAI( api_key="xxx", base_url = 'xxx' ) def get_completion(prompt, model="gpt-3.5-turbo-1106"): messages = [{"role": "user", "content": prompt}] response = client.chat.completions.create( model=model, messages=messages, temperature=0.7, ) return response.choices[0].message.content prompt = "你好,ChatGPT!" print(get_completion(prompt))
免费的api项目地址:
https://github.com/popjane/free_chatgpt_api
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。