while True:
user_input = input("You: ")
if user_input.lower() == "exit":
break
response = get_chatgpt_response(user_input)
print("ChatGPT: " + response)
Explanation
The get_chatgpt_response function handles the core interaction with the OpenAI API, using the gpt-3.5-turbo model. The message formatting is crucial for providing context to the model.
The while loop keeps the conversation going until the user types "exit".
Part 2: Enhancing the Conversation
System Instructions: Refine the initial message to the model (the system role) to shape its behavior. For example:Python{"role": "system", "content": "You are a friendly and creative assistant who can answer questions and help with tasks."}
Conversation History: Store and pass previous messages in the messages list to give the model context and improve response coherence.
Error Handling: Add try...except blocks to catch potential API errors (rate limits, invalid requests, etc.).
Part 3: Advanced Features (Optional)
Function Calling: Allow the model to trigger external functions to perform actions (e.g., search the web, calculate, etc.).
Fine-tuning: Customize the model on your own dataset to make it more specific to your needs.
Token Management: Keep track of token usage to stay within your API limits.
Graphical Interface: Create a more user-friendly interface with libraries like Tkinter, PyQt, etc.
Example Conversation
You: Tell me a joke about programmers. ChatGPT: Why did the programmer quit his job? Because he didn't get arrays!
You: That's funny! Can you write a Python function to sort a list of numbers?
ChatGPT: Absolutely! Here's a Python function to sort a list of numbers using the built-in `sorted()` function: