import streamlit as st import requests import json st.title("OpenAI Chatbot") st.write("Interact with OpenAI's models in real-time using your OpenAI API. Choose from a selection of their best models, set the temperature and max tokens, and start a conversation. Delete the conversation at any time and start fresh.") if "history" not in st.session_state: st.session_state.history = [] st.sidebar.markdown("## Configuration") API_KEY = st.sidebar.text_input("Enter your OpenAI API key") models = ['text-davinci-003', 'text-curie-001', 'text-babbage-001', 'text-ada-001'] model = st.sidebar.selectbox("Select a model", models, index=0) temperature = st.sidebar.slider("Temperature", 0.0, 1.0, 0.7) max_tokens = st.sidebar.slider("Max Tokens", 0, 3024, 3024) if st.sidebar.button("Delete Conversation"): st.session_state.history = [] st.sidebar.markdown("---") st.sidebar.markdown("## GPT-3") st.sidebar.markdown("OpenAI's GPT-3 models can understand and generate natural language. They offer four main models with different levels of power suitable for different tasks. Davinci is the most capable model, and Ada is the fastest.") st.sidebar.markdown("text-davinci-003 | 4,000 max tokens") st.sidebar.markdown("text-curie-001 | 2,048 max tokens") st.sidebar.markdown("text-babbage-001 | 2,048 max tokens") st.sidebar.markdown("text-ada-001 | 2,048 max tokens") def generate_answer(prompt): API_KEY = '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' API_URL = "https://api.openai.com/v1/completions" headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + API_KEY } previous_messages = [chat['message'] for chat in st.session_state.history if not chat['is_user']] previous_messages_text = '\n'.join(previous_messages) full_prompt = previous_messages_text + '\n' + prompt if previous_messages_text else prompt data = { "model": "text-davinci-003", "prompt": full_prompt, "temperature": 0.7, "max_tokens": 3024 } response = requests.post(API_URL, headers=headers, data=json.dumps(data)) result = response.json() message_bot = result['choices'][0]['text'] st.session_state.history.append({"message": prompt, "is_user": True}) st.session_state.history.append({"message": message_bot, "is_user": False}) prompt = st.text_input("Prompt") if st.button("Submit"): generate_answer(prompt) with st.spinner("Waiting for the response from the bot..."): for chat in st.session_state.history: if chat['is_user']: st.markdown("", unsafe_allow_html=True) st.markdown(f"