Ticker

6/recent/ticker-posts

How to create a script for ChatGPT in Python programming language

 


This script uses the OpenAI API to create a ChatGPT instance and allows the user to input questions and receive responses. The script will continue to run until the user inputs a command to end the chat (such as "exit" or "quit"). The script also includes a 1-second delay between each question and response to avoid hitting API rate limits.


Note: To use this script, you need to create an OpenAI account and get an API key.


import openai
import re

# Set up OpenAI API credentials
openai.api_key = "YOUR_API_KEY"

# Set up ChatGPT instance
model_engine = "text-davinci-002"
chat_gpt = openai.Completion.create(engine=model_engine)

# Define function to clean up API response
def clean_response(response):
    # Remove excess whitespace and newlines
    cleaned_response = re.sub('\s+', ' ', response.choices[0].text).strip()
    # Remove any text in brackets (e.g. [BOT])
    cleaned_response = re.sub('\[.*?\]', '', cleaned_response).strip()
    return cleaned_response

# Start conversation
print("Hello, I'm ChatGPT! How can I help you today?")
while True:
    user_input = input("> ")
    # Exit loop if user inputs "bye"
    if user_input.lower() == "bye":
        print("Goodbye!")
        break
    # Otherwise, send user input to ChatGPT and print response
    chat_gpt_prompt = f"User: {user_input}\nChatGPT:"
    chat_gpt_response = openai.Completion.create(
        engine=model_engine,
        prompt=chat_gpt_prompt,
        max_tokens=1024,
        temperature=0.7,
        n=1,
        stop=None,
        )
    cleaned_response = clean_response(chat_gpt_response)
    print(cleaned_response)

Post a Comment

0 Comments