Spaces:
Sleeping
Sleeping
import streamlit as st | |
from openai import OpenAI | |
model = "gpt-3.5-turbo" | |
st.sidebar.title('OpenAI Simple Conversation') | |
st.sidebar.write('Please provide your OpenAI key to be used for this conversation.') | |
def onchange_openai_key(): | |
print(st.session_state.openai_key) | |
openai_key = st.sidebar.text_input('OpenAI key', on_change=onchange_openai_key, key='openai_key') | |
st.title('OpenAI Simple Conversation') | |
st.write(f'Ask any question that can be answer by the LLM {model}.') | |
def submit_openai_key(model=model): | |
if(openai_key == None or openai_key==''): | |
st.sidebar.write('Please provide the key before') | |
return | |
else: | |
client = OpenAI(api_key=openai_key) | |
model = model | |
completion = client.chat.completions.create( | |
model=model, | |
messages=[ | |
{"role": "system", "content": "You are an assistant giving simple and short answer for question of child"}, | |
{"role": "user", "content": "count from 0 to 10"} | |
] | |
) | |
st.sidebar.write(f'Simple count : {completion.choices[0].message.content}') | |
def askQuestion(model=model, question=''): | |
if(openai_key == None or openai_key==''): | |
print('Please provide the key before') | |
return 'LLM API is not defined. Please provide the key before' | |
else: | |
client = OpenAI(api_key=openai_key) | |
model = model | |
completion = client.chat.completions.create( | |
model=model, | |
messages=[ | |
{"role": "system", "content": "You are an assistant giving simple and short answer for question of child"}, | |
{"role": "user", "content": f'{question}'} | |
] | |
) | |
return completion.choices[0].message.content | |
# Initialize chat history | |
if "messages" not in st.session_state: | |
st.session_state.messages = [] | |
# Display chat messages from history on app rerun | |
for message in st.session_state.messages: | |
with st.chat_message(message["role"]): | |
st.markdown(message["content"]) | |
# React to user input | |
if prompt := st.chat_input("What is up?"): | |
with st.status('Running', expanded=True) as status: | |
# Display user message in chat message container | |
st.chat_message("user").markdown(prompt) | |
# Add user message to chat history | |
st.session_state.messages.append({"role": "user", "content": prompt}) | |
response = askQuestion(question=prompt) | |
# Display assistant response in chat message container | |
with st.chat_message("assistant"): | |
st.markdown(response) | |
# Add assistant response to chat history | |
st.session_state.messages.append({"role": "assistant", "content": response}) | |
status.update(label='Reponse of last question', state="complete", expanded=True) | |
submit_key = st.sidebar.button(label='Submit', on_click=submit_openai_key) | |