import os
import streamlit as st
from qaip import Qaip
st.set_page_config(page_title="QAIP Chatbot", page_icon="🤖", layout="wide")
st.title("🤖 QAIP Chatbot")
st.markdown("Chat with an AI assistant powered by QAIP")
if "messages" not in st.session_state:
st.session_state.messages = []
if "qaip_client" not in st.session_state:
api_key = os.getenv("QAIP_API_KEY", "your-api-key-here")
st.session_state.qaip_client = Qaip(
api_key=api_key,
base_url="https://developer.qaip.com/api/v1",
)
with st.sidebar:
st.header("Settings")
api_key_input = st.text_input(
"API Key",
type="password",
value=os.getenv("QAIP_API_KEY", ""),
help="Enter your QAIP API key",
)
if api_key_input:
st.session_state.qaip_client = Qaip(
api_key=api_key_input,
base_url="https://developer.qaip.com/api/v1",
)
if st.button("Clear Chat History", type="secondary"):
st.session_state.messages = []
st.rerun()
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if prompt := st.chat_input("What would you like to know?"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
message_placeholder = st.empty()
full_response = ""
try:
with st.spinner("Thinking..."):
response = st.session_state.qaip_client.completion(
messages=st.session_state.messages,
citation=True,
tags=["documentation"],
)
if hasattr(response, "choices") and response.choices:
full_response = response.choices[0].message.content
elif hasattr(response, "content"):
full_response = response.content
elif hasattr(response, "text"):
full_response = response.text
else:
full_response = str(response)
message_placeholder.markdown(full_response)
except Exception as e:
error_msg = f"Error: {str(e)}"
message_placeholder.error(error_msg)
full_response = error_msg
st.session_state.messages.append(
{"role": "assistant", "content": full_response}
)
if not st.session_state.messages:
st.info("👋 Welcome! Start a conversation by typing a message below.")