-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
69 lines (56 loc) · 2.11 KB
/
Copy pathmain.py
File metadata and controls
69 lines (56 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from typing import Any, Dict, List
import streamlit as st
from core import run_agent
def _format_sources(context_docs: List[Any]) -> List[str]:
return [
str((meta.get("source") or "Unknown"))
for doc in (context_docs or [])
if (meta := (getattr(doc, "metadata", None) or {})) is not None
]
st.set_page_config(
page_title="Documentation Helper",
layout="centered"
)
st.title("Documentation Helper")
with st.sidebar:
st.subheader("Session")
if st.button("Clear chat", use_container_width=True):
st.session_state.pop("messages", None)
st.rerun()
if "messages" not in st.session_state:
st.session_state.messages = [
{
"role": "assistant",
"content": "Ask me anything about LangChain docs. I’ll retrieve relevant context and cite sources.",
"sources": [],
}
]
for msg in st.session_state.messages:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
if msg.get("sources"):
with st.expander("Sources"):
for s in msg["sources"]:
st.markdown(f"- {s}")
prompt = st.chat_input("Ask a question about LangChain…")
if prompt:
st.session_state.messages.append({"role": "user", "content": prompt, "sources": []})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
try:
with st.spinner("Retrieving docs and generating answer..."):
result: Dict[str, Any] = run_agent(prompt)
answer = str(result.get("answer", "")).strip() or "(No answer returned.)"
sources = _format_sources(result.get("context", []))
st.markdown(answer)
if sources:
with st.expander("Sources"):
for s in sources:
st.markdown(f"- {s}")
st.session_state.messages.append(
{"role": "assistant", "content": answer, "sources": sources}
)
except Exception as e:
st.error("Failed to generate a response.")
st.exception(e)