|
| 1 | +import PySimpleGUI as sg |
| 2 | +import openai |
| 3 | + |
| 4 | +# Set up OpenAI API credentials |
| 5 | +openai.api_key = "YOUR_API_KEY" |
| 6 | + |
| 7 | +# Define the ChatGPT function that sends a prompt to OpenAI and returns the response |
| 8 | +def chat_gpt(prompt): |
| 9 | + response = openai.Completion.create( |
| 10 | + engine="davinci", |
| 11 | + prompt=prompt, |
| 12 | + max_tokens=1024, |
| 13 | + n=1, |
| 14 | + stop=None, |
| 15 | + temperature=0.7, |
| 16 | + ) |
| 17 | + message = response.choices[0].text |
| 18 | + return message.strip() |
| 19 | + |
| 20 | +# Define the PySimpleGUI layout |
| 21 | +sg.theme('LightGrey1') |
| 22 | +layout = [[sg.Text('ChatGPT', font=('Helvetica', 20), pad=(5, 5))], |
| 23 | + [sg.Multiline('', key='conversation', font=('Helvetica', 14), size=(60, 10), pad=(5, 5))], |
| 24 | + [sg.Input('', key='input_message', font=('Helvetica', 14), size=(50, 1), pad=(5, 5)), |
| 25 | + sg.Button('Send', font=('Helvetica', 14), pad=(5, 5))], |
| 26 | + [sg.Button('Toggle Theme', font=('Helvetica', 14), pad=(5, 5))]] |
| 27 | + |
| 28 | +# Create the PySimpleGUI window |
| 29 | +window = sg.Window('ChatGPT', layout) |
| 30 | + |
| 31 | +# Start the PySimpleGUI event loop |
| 32 | +while True: |
| 33 | + event, values = window.read() |
| 34 | + |
| 35 | + # Exit the event loop when the window is closed |
| 36 | + if event == sg.WINDOW_CLOSED: |
| 37 | + break |
| 38 | + |
| 39 | + # Toggle between light and dark theme |
| 40 | + if event == 'Toggle Theme': |
| 41 | + if sg.theme() == 'LightGrey1': |
| 42 | + sg.theme('DarkGrey1') |
| 43 | + else: |
| 44 | + sg.theme('LightGrey1') |
| 45 | + |
| 46 | + # Send the user's message and get a response from ChatGPT |
| 47 | + if event == 'Send': |
| 48 | + # Get the user's input message |
| 49 | + message = values['input_message'] |
| 50 | + |
| 51 | + # Clear the input field |
| 52 | + window['input_message'].update('') |
| 53 | + |
| 54 | + # Add the user's message to the conversation area |
| 55 | + window['conversation'].print('You: ' + message) |
| 56 | + |
| 57 | + # Call ChatGPT to get a response |
| 58 | + response = chat_gpt(message) |
| 59 | + |
| 60 | + # Add the response to the conversation area |
| 61 | + window['conversation'].print('ChatGPT: ' + response) |
| 62 | + |
| 63 | +# Close the PySimpleGUI window when the event loop is exited |
| 64 | +window.close() |
0 commit comments