Original link: https://fugary.com/?p=459
First, you already have a ChatGPT
account and log in, then you can apply for API key
.
After the test, a scientific Internet environment is required, and the country needs to be restricted, otherwise the following message will appear, and you need to switch your own scientific Internet line:
Not available
OpenAI’s services are not available in your country.
data preparation
API
of ChatGPT
uses two values组织ID
and API key
, but Organization ID
is not required and can not be provided.
Organization ID
The Organization ID is taken directly from the settings, copy it out:
Apply for an API key
Enter URL: https://platform.openai.com/
Enter [View API keys] in the upper right corner: https://platform.openai.com/account/api-keys
Click [Create new secret key]:
Generated successfully, copy it out and save it by yourself, you will only see it once, if you forget, you can only delete and regenerate one.
By default, there is a balance of 18 US dollars, and the latest registration seems to be only 5 US dollars.
ChatGPT
has its own set of billing rules, how many Token
will be prompted for each response, and charged according to the number of Token
.
Develop with Python
Reference document: https://platform.openai.com/docs/api-reference
First of all, there is already a Python
environment. If there is no environment, it will not work.
Test call with Python
Installation dependencies:
pip install openai
Develop test code:
import os import openai if __name__ == "__main__": openai.organization = os.getenv("OPENAI_ORGANIZATION_ID") openai.api_key = os.getenv("OPENAI_API_KEY") models = openai.Model.list() for model in models.data: print(model.id)
Some supported models can be seen here.
Different models have different functions, such as voice-to-text, code completion, text completion, chat, etc.
test dialogue
You can see the models that can be used in the above test. Here we choose gpt-3.5-turbo
chat model to realize simple dialogue.
Model said documentation: https://platform.openai.com/docs/models/overview
import os import openai if __name__ == "__main__": openai.organization = os.getenv("OPENAI_ORGANIZATION_ID") openai.api_key = os.getenv("OPENAI_API_KEY") result = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "user", "content": "简要介绍下Python魔法函数"} ] ) print(result) if result.choices: print(result.choices[0].message.content)
Running will output relevant information:
For more usage methods, please refer to the documentation:
https://platform.openai.com/docs/guides/chat/introduction
This article is transferred from: https://fugary.com/?p=459
This site is only for collection, and the copyright belongs to the original author.