1安装python库
使用pip
安装openai库,注意gpt3.5-turbo
模型需要python>=3.9
的版本支持,本文演示的python版本是python==3.10.10
pip install openai
2创建api key
需要提前在openai
官网上注册好账号,然后打开https://platform.openai.com/account/api-keys
就可以创建接口keys
每个账号注册完成会有18美元在里面,每次调用api,就会花费里面的余额,注意余额也有过期时间。
3费用介绍
调用gpt3.5-turbo
的费用如下,可以看到每1000个token是0.002美元
关于token,官方也给出了说法
Multiple models, each with different capabilities and price points. Prices are per 1,000 tokens. You can think of tokens as pieces of words, where 1,000 tokens is about 750 words. This paragraph is 35 tokens.
原意就是1000个token大概是750个单词,而上面这段话有35个token。所以,不用过于担心这个费用的问题。
4 API调用
官方给出了两种调用Api的方法,分别是url
请求和调用python
包。
【1】使用curl
工具请求
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "Say this is a test!"}],
"temperature": 0.7
}'
请求后返回的格式为:
{
"id":"chatcmpl-abc123",
"object":"chat.completion",
"created":1677858242,
"model":"gpt-3.5-turbo-0301",
"usage":{
"prompt_tokens":<