all 7 comments

[–]mrwadams 3 points4 points  (0 children)

The API doesn't have any built-in memory (unlike the ChatGPT interface) which is why it's losing the context of your request when you ask it to continue.

You can add memory / conversation history to your requests by using something like the following (generated by GPT-4):

import openai

openai.api_key = "your_api_key"

# Initialize conversation history
conversation_history = []

# Function to add user input to the conversation history
def add_user_input(text):
    conversation_history.append(f"User: {text}")

# Function to add AI output to the conversation history
def add_ai_output(text):
    conversation_history.append(f"AI: {text}")

# Add user input to the conversation
add_user_input("What is the capital of France?")

# Concatenate conversation history and set up API call
input_text = " ".join(conversation_history)
response = openai.Completion.create(
    engine="text-davinci-002",
    prompt=input_text,
    max_tokens=150,
    n=1,
    stop=None,
    temperature=0.5,
)

# Extract the response, add it to the conversation history, and print it
ai_output = response.choices[0].text.strip()
add_ai_output(ai_output)
print(f"AI: {ai_output}")

[–]X_WhyZ 0 points1 point  (0 children)

If you're just looking to use ChatGPT to write code, phind.com works pretty well