File size: 8,711 Bytes
7e4014b 60e8923 d2b4a56 7e4014b d2b4a56 dd7f91e 6ae5e8b 827774a 6ae5e8b 60e8923 2159374 60e8923 827774a 20c0b83 827774a 7e4014b 827774a 7e4014b 827774a dd7f91e e2b472e dd7f91e 6ae5e8b dd7f91e 6ae5e8b dd7f91e 7e4014b 6ae5e8b 7e4014b 5f9938a 7e4014b 6ae5e8b 7e4014b 20c0b83 7e4014b 5f9938a 7e4014b fefc5e6 7e4014b 20c0b83 00bc7cc 20c0b83 dd7f91e 7e4014b dd7f91e 60e8923 7e4014b 827774a 60e8923 7e4014b d2b4a56 827774a 20c0b83 7e4014b 20c0b83 827774a d2b4a56 827774a 7e4014b 2159374 7e4014b 827774a 2159374 6ae5e8b 7e4014b e2b472e d2b4a56 60e8923 dd7f91e 60e8923 d2b4a56 dd7f91e d2b4a56 7e4014b dd7f91e 7e4014b dd7f91e 7e4014b b05ff4a 7e4014b 00bc7cc dd7f91e 6ae5e8b 7e4014b 00bc7cc 7e4014b 5f9938a |
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 |
import streamlit as st
import os
import pandas as pd
from command_center import CommandCenter
from process_documents import process_documents
from embed_documents import create_retriever
import json
from langchain.callbacks import get_openai_callback
from langchain_openai import ChatOpenAI
import base64
from chat_chains import rag_chain, parse_model_response
from langchain_core.messages import AIMessage, HumanMessage
from autoqa_chains import auto_qa_chain, followup_qa_chain, auto_qa_output_parser
st.set_page_config(layout="wide")
os.environ["OPENAI_API_KEY"] = "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"
format_citations = lambda citations: "\n\n".join(
[f"{citation['quote']} ... [{citation['source_id']}]" for citation in citations]
)
def session_state_2_llm_chat_history(session_state):
chat_history = []
for ss in session_state:
if not ss[0].startswith("/"):
chat_history.append(HumanMessage(content=ss[0]))
chat_history.append(AIMessage(content=ss[1]))
return chat_history
ai_message_format = lambda message, references: (
f"{message}\n\n---\n\n{format_citations(references)}"
if references != ""
else message
)
welcome_message = """
Hi I'm Agent Zeta, your AI assistant, dedicated to making your journey through machine learning research papers as insightful and interactive as possible. Whether you're diving into the latest studies or brushing up on foundational papers, I'm here to help navigate, discuss, and analyze content with you.
Here's a quick guide to getting started with me:
| Command | Description |
|---------|-------------|
| `/upload` <list of urls> | Upload and process documents for our conversation. |
| `/index` | View an index of processed documents to easily navigate your research. |
| `/cost` | Calculate the cost of our conversation, ensuring transparency in resource usage. |
| `/download` | Download conversation data for your records or further analysis. |
| `/auto` <document id> | Automatically generate questions and answers for a document. |
<br>
Feel free to use these commands to enhance your research experience. Let's embark on this exciting journey of discovery together!
Use `/man` at any point of time to view this guide again.
"""
def process_documents_wrapper(inputs):
snippets, documents = process_documents(inputs)
st.session_state.retriever = create_retriever(snippets)
st.session_state.source_doc_urls = inputs
st.session_state.index = [
[snip.metadata["chunk_id"], snip.metadata["header"]] for snip in snippets
]
response = f"Uploaded and processed documents {inputs}"
st.session_state.messages.append((f"/upload {inputs}", response, ""))
st.session_state.documents = documents
return response
def index_documents_wrapper(inputs=None):
response = pd.DataFrame(
st.session_state.index, columns=["id", "reference"]
).to_markdown()
st.session_state.messages.append(("/index", response, ""))
return response
def calculate_cost_wrapper(inputs=None):
try:
stats_df = pd.DataFrame(st.session_state.costing)
stats_df.loc["total"] = stats_df.sum()
response = stats_df.to_markdown()
except ValueError:
response = "No cost incurred yet"
st.session_state.messages.append(("/cost", response, ""))
return response
def download_conversation_wrapper(inputs=None):
conversation_data = json.dumps(
{
"document_urls": (
st.session_state.source_doc_urls
if "source_doc_urls" in st.session_state
else []
),
"document_snippets": (
st.session_state.index if "index" in st.session_state else []
),
"conversation": [
{"human": message[0], "ai": message[1], "references": message[2]}
for message in st.session_state.messages
],
"costing": (
st.session_state.costing if "costing" in st.session_state else []
),
"total_cost": (
{
k: sum(d[k] for d in st.session_state.costing)
for k in st.session_state.costing[0]
}
if "costing" in st.session_state and len(st.session_state.costing) > 0
else {}
),
}
)
conversation_data = base64.b64encode(conversation_data.encode()).decode()
st.session_state.messages.append(("/download", "Conversation data downloaded", ""))
return f'<a href="data:text/csv;base64,{conversation_data}" download="conversation_data.json">Download Conversation</a>'
def query_llm_wrapper(inputs):
retriever = st.session_state.retriever
qa_chain = rag_chain(
retriever, ChatOpenAI(model="gpt-4-0125-preview", temperature=0)
)
relevant_docs = retriever.get_relevant_documents(inputs)
with get_openai_callback() as cb:
response = qa_chain.invoke(
{
"question": inputs,
"chat_history": session_state_2_llm_chat_history(
st.session_state.messages
),
}
).content
stats = cb
response = parse_model_response(response)
answer = response["answer"]
citations = response["citations"]
citations.append(
{
"source_id": " ".join(
[
f"[{ref}]"
for ref in sorted(
[ref.metadata["chunk_id"] for ref in relevant_docs],
key=lambda x: int(x.split("_")[1]),
)
]
),
"quote": "other sources",
}
)
st.session_state.messages.append((inputs, answer, citations))
st.session_state.costing.append(
{
"prompt tokens": stats.prompt_tokens,
"completion tokens": stats.completion_tokens,
"cost": stats.total_cost,
}
)
return answer, citations
def auto_qa_chain_wrapper(inputs):
document = st.session_state.documents[inputs]
llm = ChatOpenAI(model="gpt-4-turbo-preview", temperature=0)
auto_qa_conversation = []
with get_openai_callback() as cb:
auto_qa_response = auto_qa_chain(llm).invoke({"paper": document})
auto_qa_response_parsed = auto_qa_output_parser.invoke(auto_qa_response)[
"questions"
]
auto_qa_conversation = [
(f'/auto {qa["question"]}', qa["answer"], "")
for qa in auto_qa_response_parsed
]
stats = cb
st.session_state.messages.append(
(f"/auto {inputs}", "Auto Convervation Generated", "")
)
for qa in auto_qa_conversation:
st.session_state.messages.append((qa[0], qa[1], ""))
st.session_state.costing.append(
{
"prompt tokens": stats.prompt_tokens,
"completion tokens": stats.completion_tokens,
"cost": stats.total_cost,
}
)
return "\n\n".join(
f"Q: {qa['question']}\n\nA: {qa['answer']}" for qa in auto_qa_response_parsed
)
def boot(command_center):
st.write("# Agent Zeta")
if "costing" not in st.session_state:
st.session_state.costing = []
if "messages" not in st.session_state:
st.session_state.messages = []
st.chat_message("ai").write(welcome_message, unsafe_allow_html=True)
for message in st.session_state.messages:
st.chat_message("human").write(message[0])
st.chat_message("ai").write(
ai_message_format(message[1], message[2]), unsafe_allow_html=True
)
if query := st.chat_input():
st.chat_message("human").write(query)
response = command_center.execute_command(query)
if response is None:
pass
elif type(response) == tuple:
result, references = response
st.chat_message("ai").write(
ai_message_format(result, references), unsafe_allow_html=True
)
else:
st.chat_message("ai").write(response, unsafe_allow_html=True)
if __name__ == "__main__":
all_commands = [
("/upload", list, process_documents_wrapper),
("/index", None, index_documents_wrapper),
("/cost", None, calculate_cost_wrapper),
("/download", None, download_conversation_wrapper),
("/man", None, lambda x: welcome_message),
("/auto", int, auto_qa_chain_wrapper),
]
command_center = CommandCenter(
default_input_type=str,
default_function=query_llm_wrapper,
all_commands=all_commands,
)
boot(command_center)
|