Unlocking Conversations: Your First ChatGPT API Call

Unlocking Conversations: Your First ChatGPT API Call

Introduction:

Integrating OpenAI's ChatGPT into your applications opens up a world of interactive and engaging conversational experiences. In this article, we will guide you through your first ChatGPT API call. We'll cover the necessary setup, demonstrate how to make a simple API call, and explore the response it generates. Let's dive in!

f you are new to ChatGPT, start with the following article:

Preparing Your Environment

Install?Python

Visual Studio?Code

Follow the detailed instruction to install VS Code in this article (You can skip Node and Yarn installations, if you are not going to use Node)

Configure VSCode for Python:

Open VSCode and create a new file with extension?.py?

No alt text provided for this image


The moment you create the file and click enter, it will ask you to install Pythin Extension. Click install as shown above

No alt text provided for this image


Make sure you have the Python interpreter which will show at the bottom

No alt text provided for this image


Write a simple print statement

print('Hello ChatGPT')        

Run the command by pressing ctrl + F5

No alt text provided for this image

This will print “Hello ChaGPT” to the terminal

No alt text provided for this image

Steps to acquire API access and obtain necessary credentials:

  • Sign up for an OpenAI account and navigate to the OpenAI API dashboard.
  • Once access is granted, obtain your API key or credentials for authentication.

Making API?Requests

?1. Install openai?Library

For Python

pip3 install openai        
No alt text provided for this image

For Node.js

npm install openai        

2. Authentication

Now we will use the APIKey we obtained in the previous step to Authenticate. Let’s first add it to a variable

secret_key = 'copy and paste your key here'        

Here is the simplest code to call the API

secret_key = 'copy and paste your key here'


import openai

# Set up your OpenAI API credentials
openai.api_key = secret_key

# output = openai.Model.list()

output = openai.Completion.create(
    model="text-curie-001",
    prompt="tel me a joke",
)


print(output)        

In the above code, you need to replace secret_key with your actual OpenAI API key, which you can obtain from your OpenAI account. The call_chatgpt function takes a prompt parameter as input, sends an API request to the ChatGPT model using OpenAI's Python library, and returns the generated response.

Note that this example uses the "text-curie-001" model, but you can modify the model variable to use other models as needed. Also, remember to ensure you have the OpenAI Python library (openai) installed before running the code.

No alt text provided for this image


Run the program by pressing Run?

No alt text provided for this image


The response comes in a JSON Format

{
  "id": "cmpl-7ZstBpD71Py3TOF8CC4swmplqhFRT",
  "object": "text_completion",
  "created": 1688786829,
  "model": "text-curie-001",
  "choices": [
    {
      "text": "\n\nWould you like me to tell you a joke? \nNo,",
      "index": 0,
      "logprobs": null,
      "finish_reason": "length"
    }
  ],
  "usage": {
    "prompt_tokens": 4,
    "completion_tokens": 16,
    "total_tokens": 20
  }
}        
No alt text provided for this image

The joke is

Would you like me to tell you a joke?

No

Apparently, it is not that funny?:)

Understanding the Response:

Let's break down the response from ChatGPT:

  • "id": "cmpl-7ZstBpD71Py3TOF8CC4swmplqhFRT": This field represents the unique identifier for the API call. It can be useful for tracking or referencing the specific completion.
  • "object": "text_completion": Indicates that the API response is a text completion, which means it contains the generated text based on the given prompt.
  • "created": 1688786829: The timestamp indicates when the API response was generated. It represents the number of seconds since the Unix epoch (January 1, 1970).
  • "model": "text-curie-001": Specifies the model that was used for generating the response. In this case, it indicates the text-curie-001 model.
  • "choices": An array containing the generated completions or responses from the model. In this example, there is only one choice.
  • "text": "\n\nWould you like me to tell you a joke? \nNo,": The generated text as a response from ChatGPT. It suggests that the model generated the text "\n\nWould you like me to tell you a joke? \nNo," as the completion of the prompt.
  • "index": 0: Indicates the index of the choice in the choices array. Since there's only one choice in this example, the index is 0.
  • "logprobs": null: This field would typically contain log probabilities associated with the generated text, but in this case, it is null or empty.
  • "finish_reason": "length": Specifies the reason for completion termination. In this example, the completion ended due to reaching the specified length limit.
  • "usage": Provides information about the token count used for the completion.
  • "prompt_tokens": 4: Indicates the number of tokens in the provided prompt.
  • "completion_tokens": 16: Represents the number of tokens in the generated completion.
  • "total_tokens": 20: The total number of tokens used, which includes both the prompt and completion tokens.

Understanding the response object allows you to extract and utilize the generated text as well as analyze the token usage for billing or other purposes.

This response is a JSON Object. Inside this object, there is a list of objects named "choices"

No alt text provided for this image

Let's print out just this list


output_text = output["choices"]
print(output_text)        

It will print out the following:


[<OpenAIObject at 0x1055bf810> JSON: {
? "text": "\n\nWhat do you call a shih tzu with a master's degree",
? "index": 0,
? "logprobs": null,
? "finish_reason": "length"
}]        

We want to print the text that is in the first object in the list as follows:


output_text = output["choices"][0]        

This will print out the following:


{
? "text": "\n\nWhy did the chicken cross the road?\n\nTo get to the",
? "index": 0,
? "logprobs": null,
? "finish_reason": "length"
}        
No alt text provided for this image

Now let's just print the text response, which we usually get on the ChatGPT:


output_text = output["choices"][0]["text"]        

The output will look like this:


What do you call a giraffe with a necktie? A gentleman        
No alt text provided for this image

Here is the full code


secret_key = "sk-..."
import openai

# Set up your OpenAI API credentials
openai.api_key = secret_key

output = openai.Completion.create(
    model="text-curie-001",
    prompt="tel me a joke",
)
output_text = output["choices"][0]["text"]
print(output_text)

        

To get the list of models:


output = openai.Model.list()        


Conclusion:

Congratulations on completing your first ChatGPT API call! You have taken the first step towards creating dynamic and interactive conversational experiences powered by OpenAI's language models. By leveraging the ChatGPT API, you can unlock the potential for engaging chatbots, virtual assistants, and more. Remember to experiment, iterate, and explore the possibilities as you integrate ChatGPT into your applications. Enjoy the power of conversation!

要查看或添加评论,请登录

社区洞察

其他会员也浏览了