Spaces:
Sleeping
Sleeping
File size: 12,930 Bytes
a01d550 80275c5 385ebea 723ae91 80275c5 df92eb1 80275c5 d967c00 c6e2641 eae1702 3ead889 a3e054f 76cbdff a3e054f 23a84f2 42554ac 385ebea b25bfc6 385ebea 80275c5 2029299 723ae91 76cbdff 69c42d0 e8bab5c 69c42d0 e8bab5c 69c42d0 42554ac 69c42d0 3ead889 8a92b0a eae1702 3ead889 8a92b0a 23a84f2 80275c5 df92eb1 6bfad85 723ae91 6bfad85 df92eb1 6bfad85 723ae91 df92eb1 723ae91 df92eb1 723ae91 df92eb1 6bfad85 42554ac 69c42d0 42554ac 69c42d0 42554ac 69c42d0 42554ac 69c42d0 42554ac da0f003 42554ac 69c42d0 42554ac 69c42d0 42554ac 69c42d0 42554ac 69c42d0 42554ac 69c42d0 80275c5 42554ac 80275c5 42554ac 69c42d0 42554ac 69c42d0 42554ac 69c42d0 42554ac 69c42d0 42554ac 69c42d0 42554ac 69c42d0 42554ac 80275c5 69c42d0 42554ac 69c42d0 42554ac 69c42d0 42554ac da0f003 42554ac da0f003 42554ac 69c42d0 3ead889 b2c7bf9 42554ac 80275c5 42554ac 80275c5 42554ac 76cbdff b25bfc6 da0f003 b25bfc6 42554ac 76cbdff 42554ac 76cbdff 42554ac 76cbdff 42554ac 76cbdff 793d0f2 76cbdff 42554ac 76cbdff 42554ac 76cbdff 42554ac 76cbdff 42554ac 793d0f2 76cbdff 42554ac b2c7bf9 76cbdff 42554ac 729aada da0f003 42554ac 69c42d0 42554ac 80275c5 9a7687f 42554ac 9a7687f 42554ac 9a7687f 42554ac 723ae91 42554ac 76cbdff 42554ac 723ae91 b25bfc6 c902b64 42554ac 69c42d0 da0f003 42554ac da0f003 42554ac b25bfc6 9a7687f 42554ac 9a7687f 42554ac 9a7687f 42554ac 9a7687f 42554ac 9a7687f 42554ac da0f003 42554ac b25bfc6 da0f003 42554ac 76cbdff 42554ac 76cbdff 42554ac da0f003 42554ac 76cbdff 42554ac df92eb1 42554ac 76cbdff df92eb1 42554ac |
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
"""
"""
from collections import defaultdict
import json
import os
import re
from langchain_core.documents import Document
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableParallel
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_together import ChatTogether
from langchain_google_genai import ChatGoogleGenerativeAI
import streamlit as st
import utils_mod
import doc_format_mod
import guide_mod
import sidebar_mod
import usage_mod
import vectorstore_mod
st.set_page_config(layout="wide", page_title="LegisQA")
os.environ["LANGCHAIN_API_KEY"] = st.secrets["langchain_api_key"]
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_PROJECT"] = st.secrets["langchain_project"]
os.environ["TOKENIZERS_PARALLELISM"] = "false"
SS = st.session_state
SEED = 292764
CONGRESS_NUMBERS = [113, 114, 115, 116, 117, 118]
SPONSOR_PARTIES = ["D", "R", "L", "I"]
OPENAI_CHAT_MODELS = {
"gpt-4o-mini": {"cost": {"pmi": 0.15, "pmo": 0.60}},
"gpt-4o": {"cost": {"pmi": 5.00, "pmo": 15.0}},
}
ANTHROPIC_CHAT_MODELS = {
"claude-3-haiku-20240307": {"cost": {"pmi": 0.25, "pmo": 1.25}},
"claude-3-5-sonnet-20240620": {"cost": {"pmi": 3.00, "pmo": 15.0}},
"claude-3-opus-20240229": {"cost": {"pmi": 15.0, "pmo": 75.0}},
}
TOGETHER_CHAT_MODELS = {
"meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo": {"cost": {"pmi": 0.18, "pmo": 0.18}},
"meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo": {
"cost": {"pmi": 0.88, "pmo": 0.88}
},
"meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo": {
"cost": {"pmi": 5.00, "pmo": 5.00}
},
}
GOOGLE_CHAT_MODELS = {
"gemini-1.5-flash": {"cost": {"pmi": 0.0, "pmo": 0.0}},
"gemini-1.5-pro": {"cost": {"pmi": 0.0, "pmo": 0.0}},
"gemini-1.5-pro-exp-0801": {"cost": {"pmi": 0.0, "pmo": 0.0}},
}
PROVIDER_MODELS = {
"OpenAI": OPENAI_CHAT_MODELS,
"Anthropic": ANTHROPIC_CHAT_MODELS,
"Together": TOGETHER_CHAT_MODELS,
"Google": GOOGLE_CHAT_MODELS,
}
def render_example_queries():
with st.expander("Example Queries"):
st.write(
"""
```
What are the themes around artificial intelligence?
```
```
Write a well cited 3 paragraph essay on food insecurity.
```
```
Create a table summarizing major climate change ideas with columns legis_id, title, idea.
```
```
Write an action plan to keep social security solvent.
```
```
Suggest reforms that would benefit the Medicaid program.
```
"""
)
def get_generative_config(key_prefix: str) -> dict:
output = {}
key = "provider"
output[key] = st.selectbox(
label=key, options=PROVIDER_MODELS.keys(), key=f"{key_prefix}|{key}"
)
key = "model_name"
output[key] = st.selectbox(
label=key,
options=PROVIDER_MODELS[output["provider"]],
key=f"{key_prefix}|{key}",
)
key = "temperature"
output[key] = st.slider(
key,
min_value=0.0,
max_value=2.0,
value=0.0,
key=f"{key_prefix}|{key}",
)
key = "max_output_tokens"
output[key] = st.slider(
key,
min_value=1024,
max_value=2048,
key=f"{key_prefix}|{key}",
)
key = "top_p"
output[key] = st.slider(
key, min_value=0.0, max_value=1.0, value=0.9, key=f"{key_prefix}|{key}"
)
key = "should_escape_markdown"
output[key] = st.checkbox(
key,
value=False,
key=f"{key_prefix}|{key}",
)
key = "should_add_legis_urls"
output[key] = st.checkbox(
key,
value=True,
key=f"{key_prefix}|{key}",
)
return output
def get_retrieval_config(key_prefix: str) -> dict:
output = {}
key = "n_ret_docs"
output[key] = st.slider(
"Number of chunks to retrieve",
min_value=1,
max_value=32,
value=8,
key=f"{key_prefix}|{key}",
)
key = "filter_legis_id"
output[key] = st.text_input("Bill ID (e.g. 118-s-2293)", key=f"{key_prefix}|{key}")
key = "filter_bioguide_id"
output[key] = st.text_input("Bioguide ID (e.g. R000595)", key=f"{key_prefix}|{key}")
key = "filter_congress_nums"
output[key] = st.multiselect(
"Congress Numbers",
CONGRESS_NUMBERS,
default=CONGRESS_NUMBERS,
key=f"{key_prefix}|{key}",
)
key = "filter_sponsor_parties"
output[key] = st.multiselect(
"Sponsor Party",
SPONSOR_PARTIES,
default=SPONSOR_PARTIES,
key=f"{key_prefix}|{key}",
)
return output
def get_llm(gen_config: dict):
match gen_config["provider"]:
case "OpenAI":
llm = ChatOpenAI(
model=gen_config["model_name"],
temperature=gen_config["temperature"],
api_key=st.secrets["openai_api_key"],
top_p=gen_config["top_p"],
seed=SEED,
max_tokens=gen_config["max_output_tokens"],
)
case "Anthropic":
llm = ChatAnthropic(
model_name=gen_config["model_name"],
temperature=gen_config["temperature"],
api_key=st.secrets["anthropic_api_key"],
top_p=gen_config["top_p"],
max_tokens_to_sample=gen_config["max_output_tokens"],
)
case "Together":
llm = ChatTogether(
model=gen_config["model_name"],
temperature=gen_config["temperature"],
max_tokens=gen_config["max_output_tokens"],
top_p=gen_config["top_p"],
seed=SEED,
api_key=st.secrets["together_api_key"],
)
case "Google":
llm = ChatGoogleGenerativeAI(
model=gen_config["model_name"],
temperature=gen_config["temperature"],
api_key=st.secrets["google_api_key"],
max_output_tokens=gen_config["max_output_tokens"],
top_p=gen_config["top_p"],
)
case _:
raise ValueError()
return llm
def create_rag_chain(llm, retriever):
QUERY_RAG_TEMPLATE = """You are an expert legislative analyst. Use the following excerpts from US congressional legislation to respond to the user's query. The excerpts are formatted as a JSON list. Each JSON object has "legis_id", "title", "introduced_date", "sponsor", and "snippets" keys. If a snippet is useful in writing part of your response, then cite the "legis_id", "title", "introduced_date", and "sponsor" in the response. When citing legis_id, use the same format as the excerpts (e.g. "116-hr-125"). If you don't know how to respond, just tell the user.
---
Congressional Legislation Excerpts:
{context}
---
Query: {query}"""
prompt = ChatPromptTemplate.from_messages(
[
("human", QUERY_RAG_TEMPLATE),
]
)
rag_chain = (
RunnableParallel(
{
"docs": retriever,
"query": RunnablePassthrough(),
}
)
.assign(context=lambda x: doc_format_mod.format_docs(x["docs"]))
.assign(aimessage=prompt | llm)
)
return rag_chain
def process_query(gen_config: dict, ret_config: dict, query: str):
vectorstore = vectorstore_mod.load_pinecone_vectorstore()
llm = get_llm(gen_config)
vs_filter = vectorstore_mod.get_vectorstore_filter(ret_config)
retriever = vectorstore.as_retriever(
search_kwargs={"k": ret_config["n_ret_docs"], "filter": vs_filter},
)
rag_chain = create_rag_chain(llm, retriever)
response = rag_chain.invoke(query)
return response
def render_response(
response: dict,
model_info: dict,
provider: str,
should_escape_markdown: bool,
should_add_legis_urls: bool,
tag: str | None = None,
):
response_text = response["aimessage"].content
if should_escape_markdown:
response_text = utils_mod.escape_markdown(response_text)
if should_add_legis_urls:
response_text = utils_mod.replace_legis_ids_with_urls(response_text)
with st.container(border=True):
if tag is None:
st.write("Response")
else:
st.write(f"Response ({tag})")
st.info(response_text)
usage_mod.display_api_usage(response["aimessage"], model_info, provider, tag=tag)
doc_format_mod.render_retrieved_chunks(response["docs"], tag=tag)
def render_query_rag_tab():
key_prefix = "query_rag"
render_example_queries()
with st.form(f"{key_prefix}|query_form"):
query = st.text_area(
"Enter a query that can be answered with congressional legislation:"
)
cols = st.columns(2)
with cols[0]:
query_submitted = st.form_submit_button("Submit")
with cols[1]:
status_placeholder = st.empty()
col1, col2 = st.columns(2)
with col1:
with st.expander("Generative Config"):
gen_config = get_generative_config(key_prefix)
with col2:
with st.expander("Retrieval Config"):
ret_config = get_retrieval_config(key_prefix)
rkey = f"{key_prefix}|response"
if query_submitted:
with status_placeholder:
with st.spinner("generating response"):
SS[rkey] = process_query(gen_config, ret_config, query)
if response := SS.get(rkey):
model_info = PROVIDER_MODELS[gen_config["provider"]][gen_config["model_name"]]
render_response(
response,
model_info,
gen_config["provider"],
gen_config["should_escape_markdown"],
gen_config["should_add_legis_urls"],
)
with st.expander("Debug"):
st.write(response)
def render_query_rag_sbs_tab():
base_key_prefix = "query_rag_sbs"
with st.form(f"{base_key_prefix}|query_form"):
query = st.text_area(
"Enter a query that can be answered with congressional legislation:"
)
cols = st.columns(2)
with cols[0]:
query_submitted = st.form_submit_button("Submit")
with cols[1]:
status_placeholder = st.empty()
grp1a, grp2a = st.columns(2)
gen_configs = {}
ret_configs = {}
with grp1a:
st.header("Group 1")
key_prefix = f"{base_key_prefix}|grp1"
with st.expander("Generative Config"):
gen_configs["grp1"] = get_generative_config(key_prefix)
with st.expander("Retrieval Config"):
ret_configs["grp1"] = get_retrieval_config(key_prefix)
with grp2a:
st.header("Group 2")
key_prefix = f"{base_key_prefix}|grp2"
with st.expander("Generative Config"):
gen_configs["grp2"] = get_generative_config(key_prefix)
with st.expander("Retrieval Config"):
ret_configs["grp2"] = get_retrieval_config(key_prefix)
grp1b, grp2b = st.columns(2)
sbs_cols = {"grp1": grp1b, "grp2": grp2b}
grp_names = {"grp1": "Group 1", "grp2": "Group 2"}
for post_key_prefix in ["grp1", "grp2"]:
with sbs_cols[post_key_prefix]:
key_prefix = f"{base_key_prefix}|{post_key_prefix}"
rkey = f"{key_prefix}|response"
if query_submitted:
with status_placeholder:
with st.spinner(
"generating response for {}".format(grp_names[post_key_prefix])
):
SS[rkey] = process_query(
gen_configs[post_key_prefix],
ret_configs[post_key_prefix],
query,
)
if response := SS.get(rkey):
model_info = PROVIDER_MODELS[gen_configs[post_key_prefix]["provider"]][
gen_configs[post_key_prefix]["model_name"]
]
render_response(
response,
model_info,
gen_configs[post_key_prefix]["provider"],
gen_configs[post_key_prefix]["should_escape_markdown"],
gen_configs[post_key_prefix]["should_add_legis_urls"],
tag=grp_names[post_key_prefix],
)
def main():
st.title(":classical_building: LegisQA :classical_building:")
st.header("Query Congressional Bills")
with st.sidebar:
sidebar_mod.render_sidebar()
query_rag_tab, query_rag_sbs_tab, guide_tab = st.tabs(
[
"RAG",
"RAG (side-by-side)",
"Guide",
]
)
with query_rag_tab:
render_query_rag_tab()
with query_rag_sbs_tab:
render_query_rag_sbs_tab()
with guide_tab:
guide_mod.render_guide()
if __name__ == "__main__":
main()
|