# chatbot.py
import openai
import streamlit as st
import wandb
from set_env import set_env
import weave
_ = set_env("OPENAI_API_KEY")
_ = set_env("WANDB_API_KEY")
wandb.login()
weave_client = weave.init("feedback-example")
oai_client = openai.OpenAI()
def init_states():
"""session_state のキーがまだ存在しない場合に設定します。"""
if "messages" not in st.session_state:
st.session_state["messages"] = []
if "calls" not in st.session_state:
st.session_state["calls"] = []
if "session_id" not in st.session_state:
st.session_state["session_id"] = "123abc"
@weave.op
def chat_response(full_history):
"""
これまでの会話履歴全体を基に、ストリーミング モードで OpenAI API を呼び出します。
full_history は辞書のリストです: [{"role":"user"|"assistant","content":...}, ...]
"""
stream = oai_client.chat.completions.create(
model="gpt-4", messages=full_history, stream=True
)
response_text = st.write_stream(stream)
return {"response": response_text}
def render_feedback_buttons(call_idx):
"""Call に対するサムズアップ/ダウンおよびテキスト フィードバックをレンダリングします。"""
col1, col2, col3 = st.columns([1, 1, 4])
# サムズアップ ボタン
with col1:
if st.button("👍", key=f"thumbs_up_{call_idx}"):
st.session_state.calls[call_idx].feedback.add_reaction("👍")
st.success("Thanks for the feedback!")
# サムズダウン ボタン
with col2:
if st.button("👎", key=f"thumbs_down_{call_idx}"):
st.session_state.calls[call_idx].feedback.add_reaction("👎")
st.success("Thanks for the feedback!")
# テキスト フィードバック
with col3:
feedback_text = st.text_input("Feedback", key=f"feedback_input_{call_idx}")
if (
st.button("Submit Feedback", key=f"submit_feedback_{call_idx}")
and feedback_text
):
st.session_state.calls[call_idx].feedback.add_note(feedback_text)
st.success("Feedback submitted!")
def display_old_messages():
"""st.session_state.messages に保存された会話をフィードバック ボタンとともに表示します。"""
for idx, message in enumerate(st.session_state.messages):
with st.chat_message(message["role"]):
st.markdown(message["content"])
# アシスタント メッセージの場合はフィードバック フォームを表示する
if message["role"] == "assistant":
# st.session_state.calls 内でこのアシスタント メッセージのインデックスを特定する
assistant_idx = (
len(
[
m
for m in st.session_state.messages[: idx + 1]
if m["role"] == "assistant"
]
)
- 1
)
# サムズアップ/ダウンおよびテキスト フィードバックをレンダリングする
if assistant_idx < len(st.session_state.calls):
render_feedback_buttons(assistant_idx)
def display_chat_prompt():
"""チャット プロンプトの入力ボックスを表示します。"""
if prompt := st.chat_input("Ask me anything!"):
# 新しいユーザー メッセージを即座にレンダリングする
with st.chat_message("user"):
st.markdown(prompt)
# セッションにユーザー メッセージを保存する
st.session_state.messages.append({"role": "user", "content": prompt})
# API 用のチャット履歴を準備する
full_history = [
{"role": msg["role"], "content": msg["content"]}
for msg in st.session_state.messages
]
with st.chat_message("assistant"):
# 会話インスタンスのトラッキング用に Weave 属性を付与する
with weave.attributes(
{"session": st.session_state["session_id"], "env": "prod"}
):
# OpenAI API を呼び出す(ストリーム)
result, call = chat_response.call(full_history)
# アシスタント メッセージを保存する
st.session_state.messages.append(
{"role": "assistant", "content": result["response"]}
)
# フィードバックを特定の Response に紐付けるために Weave の Call オブジェクトを保存する
st.session_state.calls.append(call)
# 新しいメッセージ用のフィードバック ボタンをレンダリングする
new_assistant_idx = (
len(
[
m
for m in st.session_state.messages
if m["role"] == "assistant"
]
)
- 1
)
# フィードバック ボタンをレンダリングする
if new_assistant_idx < len(st.session_state.calls):
render_feedback_buttons(new_assistant_idx)
def main():
st.title("Chatbot with immediate feedback forms")
init_states()
display_old_messages()
display_chat_prompt()
if __name__ == "__main__":
main()