Repository navigation
Expand file tree
/
Copy pathapp_react_cmdline.py
More file actions
116 lines (100 loc) · 3.53 KB
/
Copy pathapp_react_cmdline.py
File metadata and controls
116 lines (100 loc) · 3.53 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
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
import csv
from langchain_core.prompts import PromptTemplate
from langchain.tools.retriever import create_retriever_tool
from langchain.agents import AgentExecutor
from src import CFG
from src.agents import create_react_agent, DEFAULT_REACT_TEMPLATE
from src.prompt_templates import prompts
from src.retrieval_qa import build_rerank_retriever, condense_question_chain
from src.tools import tavily_tool, wikipedia_tool
from src.vectordb import load_faiss
from streamlit_app.utils import load_base_embeddings, load_llm, load_reranker
CHAT_FORMAT = prompts.chat_format
LLM = load_llm()
BASE_EMBEDDINGS = load_base_embeddings()
RERANKER = load_reranker()
CONDENSE_QUESTION_CHAIN = condense_question_chain(LLM)
def load_faiss_cached(index_path):
return load_faiss(BASE_EMBEDDINGS, index_path)
def build_chain(reranker, llm):
tools = [wikipedia_tool, tavily_tool]
for vectordb in CFG.VECTORDB:
db = load_faiss_cached(vectordb.PATH)
retriever = build_rerank_retriever(db, reranker)
tool = create_retriever_tool(
retriever=retriever,
name=vectordb.NAME,
description=vectordb.DESCRIPTION,
)
tools.append(tool)
prompt = PromptTemplate.from_template(
CHAT_FORMAT.format(system=DEFAULT_REACT_TEMPLATE, user="")
)
agent = create_react_agent(
llm=llm,
tools=tools,
prompt=prompt,
)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
return_intermediate_steps=True,
handle_parsing_errors=True,
verbose=True,
)
return agent_executor
def print_docs(source_documents):
for row in source_documents:
print(f"Document: {row}")
def save_to_csv(file_path, data):
with open(file_path, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
# Write header
writer.writerow(["User Query", "Assistant Answer", "Sources"])
# Write data
for row in data:
writer.writerow(row)
def main():
try:
print("Loading agent...")
chain = build_chain(RERANKER, LLM)
print("Loading complete!")
print("Reading from existing VectorDB")
except Exception as e:
print(f"Error: {e}")
return
chat_history = list()
display_history = [("", "Hello! How can I help you?", None)]
while True:
# Display chat history
for question, answer, source_documents in display_history:
if question:
print(f"User: {question}")
print(f"Assistant: {answer}")
if source_documents:
print("Sources:")
print_docs(source_documents)
user_query = input("Your query: ")
if user_query.strip().lower() == "exit":
break
query = CONDENSE_QUESTION_CHAIN.invoke(
{
"question": user_query,
"chat_history": chat_history,
}
)
response = chain.invoke(
{"input": query}
)
answer = response["output"].replace("$", r"\$")
source_documents = [
r[1].replace("$", r"\$") if isinstance(r[1], str) else r[1] for r in response["intermediate_steps"]
]
print(f"Assistant: {answer}")
print("Sources:")
print_docs(source_documents)
chat_history.append((user_query, answer))
display_history.append((user_query, answer, source_documents))
save_to_csv("app_react_responses.csv", display_history)
if __name__ == "__main__":
main()