|
| 1 | +import os |
| 2 | +import openai # pip install openai |
| 3 | +from dash import Dash,dcc, html, Input, Output, State # pip install dash |
| 4 | + |
| 5 | +# Set up OpenAI API credentials |
| 6 | +# Create .env file and insert your api key like so: |
| 7 | +# OPENAI_API_KEY="your-key-goes-here" |
| 8 | +openai.api_key = os.getenv("OPENAI_API_KEY") # pip install python-dotenv |
| 9 | + |
| 10 | +# Initialize the ChatGPT model |
| 11 | +model_engine = 'text-davinci-003' |
| 12 | + |
| 13 | +# Instantiate the Dash app |
| 14 | +app = Dash(__name__) |
| 15 | + |
| 16 | +app.layout = html.Div([ |
| 17 | + html.H1("Dash-ChatGPT Example"), |
| 18 | + dcc.Input(id='input-text', type='text', placeholder='Type your message here', style={'width':500}), |
| 19 | + html.Button('Send', id='submit-button', n_clicks=0), |
| 20 | + dcc.Loading( |
| 21 | + children=[ |
| 22 | + html.Div(id='output-text') |
| 23 | + ], |
| 24 | + type="circle", |
| 25 | + ) |
| 26 | +]) |
| 27 | + |
| 28 | +# Define the callback function |
| 29 | +@app.callback( |
| 30 | + Output('output-text', 'children'), |
| 31 | + Input('submit-button', 'n_clicks'), |
| 32 | + State('input-text', 'value') |
| 33 | +) |
| 34 | +def update_output(n_clicks, input_text): |
| 35 | + if n_clicks >0: |
| 36 | + # Get the response from ChatGPT |
| 37 | + response = openai.Completion.create( |
| 38 | + engine=model_engine, |
| 39 | + prompt=f"{input_text}\n", |
| 40 | + max_tokens=4000, |
| 41 | + n=1, |
| 42 | + stop=None, |
| 43 | + temperature=0.7, |
| 44 | + ) |
| 45 | + |
| 46 | + # Extract the generated text from the response |
| 47 | + generated_text = response.choices[0].text |
| 48 | + |
| 49 | + # Return the generated text as the output |
| 50 | + return generated_text |
| 51 | + |
| 52 | +if __name__ == '__main__': |
| 53 | + app.run_server(debug=True) |
0 commit comments