File size: 1,267 Bytes
727516c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import streamlit as st
from openai import OpenAI

# Streamlit app
st.title("Chat with OpenAI")

# Get OpenAI API key from user
api_key = st.text_input("Enter your OpenAI API key:", type="password")
client = OpenAI(api_key=api_key)

if api_key:
    # Configure OpenAI API key
    try:
        # Get user input
        user_input = st.text_input("Ask a question")

        if st.button("Submit"):
            if user_input:
                # Call OpenAI API
                response = client.chat.completions.create(
                    model="gpt-3.5-turbo",
                    # response_format={ "type": "json_object" },
                    messages=[
                        {"role": "system", "content": "You are an AI that takes instructions from a human and produces an answer. Be concise in your output."},
                        {"role": "user", "content": f"{user_input}"}
                    ]
                )
                answer = response.choices[0].message.content
                st.write("AI Response:")
                st.write(answer)
            else:
                st.write("Please enter a question.")
    except Exception as e:
        st.error(f"Error: {e}")
else:
    if not api_key:
        st.write("Please enter your OpenAI API key.")