openai

⭐Introduction to the author: I am a sophomore majoring in network engineering, continue to learn Java, and strive to output high-quality articles
⭐Author's homepage: @追梦空穹
⭐The column I belong to: Artificial Intelligence .

1 Introduction

OpenAI provides a library called OpenAI API for interacting with their AI models.
Here is a brief introduction to the OpenAI library:

  1. OpenAI API is a Python library for accessing and using OpenAI models. By using the OpenAI API, you can easily interact with some powerful language models, such as GPT-3. This enables you to integrate natural language processing and generation tasks into your application.
  2. Using the OpenAI API, you can implement dialogue, question answering, text generation, and more by providing input text to the model and receiving the response generated by the model. This makes it easier to develop chatbots, smart assistants, text-generating apps, and more.

Through the OpenAI API, there are two types of interactions with the model:

  1. Completion: You can provide a prompt, and the model will generate a completion text based on the prompt. This is useful for tasks like question answering, article authoring, code generation, and more.
  2. Chat: You can simulate a dialogue system to interact with the model. You can provide a history of the dialog along with the current user input and continue the dialog based on the responses generated by the model.

Using the OpenAI API requires access to OpenAI's model service, and you need to have a valid API key to access. You can use the Python library officially provided by OpenAI to easily interact with the API and handle input and output.

2. How to achieve

First import the openai library, and then configure openai_api_key. Then specify the model and the question to be asked in the method, the code is as follows:

import openai

openai.api_base = "如果有代理服务器,就配置服务器地址"
openai_api_key = '你的openai key'
openai.api_key = openai_api_key


def get_completion(prompt, model=None):
    if model is None:
        model = "gpt-3.5-turbo-0301"
    messages = [{
    
    "role": "user", "content": prompt}]

    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0,
    )
    return response.choices[0].message["content"]


if __name__ == '__main__':
    get_completion("1+1=?")

Realize the effect:
insert image description here

3. API documentation

Official: openai-api
Chinese document: openai-api-Chinese version

Guess you like

Origin blog.csdn.net/qq_60735796/article/details/131495440
Recommended