Ticker

6/recent/ticker-posts

How to access ChatGPT (openai) from Python

Hello Everyone,

I recently accessed openai (ChatGPT) within Python and thought of sharing my experience.



You would require two basic things

1. Python (pip ready environment)
2. Account on (https://platform.openai.com/)

Steps:

  1. Login to  https://platform.openai.com/ and download your API key (top-right side of the page)



  2. Make sure you save it somewhere.
  3. Now create a python file (chatgpt.py in this example)
  4. Copy the below lines of code and make the required changes accordingly.
import openai
api_key='<your API key downloaded from openai>'
openai.api_key=api_key
result=openai.Completion.create(
    model='text-davinci-002',
    prompt='<Any question (e.g. What is Tableau in 100 words)>',
    max_tokens=100,
    temperature=0
    echo=True
    )
print (result)
5. Run the code (python chatgpt.py). You need to be in the same directory where you have created this file.
6. Voila! Your output is there in the JSON format.


Code Explained:

1. Import the openai API

2. openai.Completion.create is a function that creates a completed response based on your prompt. The same is used by ChatGPT.

3. Model: This is mandatory argument. There are multiple openai models. I have used text-davinci-002. You can use others. It is relatively costly and it has request size of 4000 tokens. More on models is available at https://platform.openai.com/docs/models

4. Prompt is your question. Optional

5. Max Token is no of characters. (approximately 1 token has 4 characters or  100 tokens is about 750 words ) Tokens can be words or just chunks of characters. Models understand and process text by breaking it down into tokens. The price is associated with the tokens. https://openai.com/pricing Optional.

6. Temperature lets you control how confident the model should be when making these predictions. Lowering temperature means it will take fewer risks, and completions will be more accurate. Increasing temperature will result in more risks, and more diverse completions. The values lies between 0-1. 

7. Echo=True echo back the prompt in addition to the completion. Default is false. Optional

8. Finally print the output.


Resources:


Regards,
Piyush Narayan







 

Post a Comment

0 Comments