|
3 | 3 | StreamlitCallbackHandler,
|
4 | 4 | )
|
5 | 5 |
|
6 |
| -from template_langgraph.agents.chat_with_tools_agent.agent import AgentState, graph |
| 6 | +from template_langgraph.agents.chat_with_tools_agent.agent import ( |
| 7 | + AgentState, |
| 8 | + ChatWithToolsAgent, |
| 9 | +) |
| 10 | +from template_langgraph.tools.common import get_default_tools |
7 | 11 |
|
8 | 12 | if "chat_history" not in st.session_state:
|
9 | 13 | st.session_state["chat_history"] = []
|
10 | 14 |
|
| 15 | +# Sidebar: ツール選択とエージェントの構築 |
| 16 | +with st.sidebar: |
| 17 | + st.subheader("使用するツール") |
| 18 | + |
| 19 | + # 利用可能なツール一覧を取得 |
| 20 | + available_tools = get_default_tools() |
| 21 | + tool_name_to_obj = {t.name: t for t in available_tools} |
| 22 | + tool_names = list(tool_name_to_obj.keys()) |
| 23 | + |
| 24 | + # 初期選択は全選択 |
| 25 | + if "selected_tool_names" not in st.session_state: |
| 26 | + st.session_state["selected_tool_names"] = tool_names |
| 27 | + |
| 28 | + selected_tool_names = st.multiselect( |
| 29 | + "有効化するツールを選択", |
| 30 | + options=tool_names, |
| 31 | + default=st.session_state["selected_tool_names"], |
| 32 | + ) |
| 33 | + st.session_state["selected_tool_names"] = selected_tool_names |
| 34 | + |
| 35 | + # 選択されたツールでグラフを再構築(選択が変わった時のみ) |
| 36 | + selected_tools = [tool_name_to_obj[name] for name in selected_tool_names] |
| 37 | + signature = tuple(selected_tool_names) |
| 38 | + if "graph" not in st.session_state or st.session_state.get("graph_tools_signature") != signature: |
| 39 | + st.session_state["graph"] = ChatWithToolsAgent(tools=selected_tools).create_graph() |
| 40 | + st.session_state["graph_tools_signature"] = signature |
| 41 | + # 選択中のツール表示(簡易) |
| 42 | + st.caption("選択中: " + (", ".join(selected_tool_names) if selected_tool_names else "なし")) |
| 43 | + |
11 | 44 | for msg in st.session_state["chat_history"]:
|
12 | 45 | if isinstance(msg, dict):
|
13 | 46 | st.chat_message(msg["role"]).write(msg["content"])
|
|
18 | 51 | st.session_state["chat_history"].append({"role": "user", "content": prompt})
|
19 | 52 | st.chat_message("user").write(prompt)
|
20 | 53 | with st.chat_message("assistant"):
|
21 |
| - response: AgentState = graph.invoke( |
| 54 | + response: AgentState = st.session_state["graph"].invoke( |
22 | 55 | {"messages": st.session_state["chat_history"]},
|
23 | 56 | {
|
24 | 57 | "callbacks": [
|
25 | 58 | StreamlitCallbackHandler(st.container()),
|
26 | 59 | ]
|
27 | 60 | },
|
28 | 61 | )
|
29 |
| - st.session_state["chat_history"].append(response["messages"][-1]) |
30 |
| - st.write(response["messages"][-1].content) |
| 62 | + last_message = response["messages"][-1] |
| 63 | + st.session_state["chat_history"].append(last_message) |
| 64 | + st.write(last_message.content) |
0 commit comments