How can i chat with chatgpt using python

Question:

I asked ChatGPT to show me how could I use OpenAi’s API to interact with it in my terminal window and it generated code which I modified a little bit in order to do what I wanted.

Here is the python code:

import requests

with open('../api-key.txt','r') as key:
    data = key.read().strip()

api_key = data
model="text-danvinci-003"

def chat_with_chatgpt(prompt):
    res = requests.post(f"https://api.openai.com/v1/engines/{model}/jobs", headers = {
            "Content-Type":"application/json",
            "Authorization":f"Bearer {api_key}"
            },
            json={
                "prompt":prompt,
                "max_tokens":100
                }).json()
    print(res)
    return res.choices[0].text

while True:
    prompt = input('Me: ')
    response = chat_with_chatgpt(prompt)
    print(f'ChatGPT: {response}')

But when I ran this code I got some messages that said:

Me: hello
{'error': {'message': 'That model does not exist', 'type': 'invalid_request_error', 'param': None, 'code': None}}
Traceback (most recent call last):
  File "/data/data/com.termux/files/home/python/main.py", line 23, in <module>
    response = chat_with_chatgpt(prompt)                                         ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/data/com.termux/files/home/python/main.py", line 19, in chat_with_chatgpt
    return res.choices[0].text
           ^^^^^^^^^^^                                            AttributeError: 'dict' object has no attribute 'choices'

The response I got is an error dict.

For some reason I am not able to install OpenAi via pip install openai on my system, so this is the only option I have.

Asked By: John Delvin

||

Answers:

I believe the engines API endpoints were deprecated in favour of models. For more info read here: https://help.openai.com/en/articles/6283125-what-happened-to-engines

You will want to look at the completions endpoint instead https://platform.openai.com/docs/api-reference/completions

Here’s an example of the URL structure and headers required, using cURL.

curl https://api.openai.com/v1/completions 
  -H 'Content-Type: application/json' 
  -H 'Authorization: Bearer YOUR_API_KEY' 
  -d '{
  "model": "text-davinci-003",
  "prompt": "Say this is a test",
  "max_tokens": 7,
  "temperature": 0
}'

The general structure of the code should be fine, you’ll just want to swap out the endpoint in use.

def chat_with_chatgpt(prompt):
    res = requests.post(f"https://api.openai.com/v1/completions",
          headers = {
              "Content-Type": "application/json",
              "Authorization": f"Bearer {api_key}"
          },
          json={
              "model": model
              "prompt": prompt,
              "max_tokens": 100
          }).json()
    return res.choices[0].text
Answered By: Benjamin Rowell

This is what worked for me

import requests
import time
import sys

with open('../ap.txt','r') as key:
    data = key.read().strip()

api_key = data
model="text-davinci-003"

def chat_with_chatgpt(prompt):
    res = requests.post(f"https://api.openai.com/v1/completions",
          headers = {
              "Content-Type": "application/json",
              "Authorization": f"Bearer {api_key}"
          },
          json={
              "model": model,
              "prompt": prompt,
              "max_tokens": 100
          }).json()
    return res['choices'][0]['text'][1:]#slice off the first newline line

while True:
    prompt = input('nnJohn: ')
    if prompt == "done":
        break
    response = chat_with_chatgpt(prompt)
    print("Chatgpt:::>",end='n')
    for i in response:
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.09)

I included sys to emulate typing of characters since it is easier to read some text as it is getting typed than reading all the text at once which is kinda boring

Answered By: John Delvin

I’m wondering, If I keep all the prompts and responses and when I make a new prompt and all those, it will follow the previous discussion for the next answer?

Answered By: Claudiu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.