from openai import OpenAI import streamlit as st import os # Fetch the API key from an environment variable openai_api_key = os.getenv("OPENAI_API_KEY") # Select model using a dropdown model_choice = "gpt-3.5-turbo" # Read system message from a text file try: with open("system_message.txt", "r") as file: system_message = file.read().strip() except FileNotFoundError: st.error("The system message file was not found. Please make sure 'system_message.txt' exists.") st.stop() # Initialize session state for storing messages if it doesn't already exist if "messages" not in st.session_state: st.session_state["messages"] = [{"role": "system", "content": system_message}, {"role": "assistant", "content": "Je suis Logis-Experts Bot à votre service, posez moi votre question !"}] # Display all previous messages only when needed for msg in st.session_state.messages: if msg["role"] != "system": # Skip system messages st.chat_message(msg["role"]).write(msg["content"]) # Input for new prompts prompt = st.chat_input("Enter your question:") if prompt: if not openai_api_key: st.error("No OpenAI API key found. Please set the OPENAI_API_KEY environment variable.") st.stop() # Append the new user message to session state st.session_state.messages.append({"role": "user", "content": prompt}) st.chat_message("user").write(prompt) # Use a spinner to indicate that the model is generating a response with st.spinner('Logis-Expert Bot is Thinking...'): client = OpenAI(api_key=openai_api_key) response = client.chat.completions.create(model=model_choice, messages=st.session_state.messages) msg = response.choices[0].message.content # Append and display the assistant's response st.session_state.messages.append({"role": "assistant", "content": msg}) st.chat_message("assistant").write(msg)