Spaces:
Sleeping
Sleeping
Create langchain_utils.py
Browse files- langchain_utils.py +48 -0
langchain_utils.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_openai import ChatOpenAI
|
| 2 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 3 |
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 4 |
+
from langchain.chains import create_history_aware_retriever, create_retrieval_chain
|
| 5 |
+
from langchain.chains.combine_documents import create_stuff_documents_chain
|
| 6 |
+
from typing import List
|
| 7 |
+
from langchain_core.documents import Document
|
| 8 |
+
import os
|
| 9 |
+
from chroma_utils import vectorstore
|
| 10 |
+
retriever = vectorstore.as_retriever(search_kwargs={"k": 2})
|
| 11 |
+
|
| 12 |
+
output_parser = StrOutputParser()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# Set up prompts and chains
|
| 18 |
+
contextualize_q_system_prompt = (
|
| 19 |
+
"Given a chat history and the latest user question "
|
| 20 |
+
"which might reference context in the chat history, "
|
| 21 |
+
"formulate a standalone question which can be understood "
|
| 22 |
+
"without the chat history. Do NOT answer the question, "
|
| 23 |
+
"just reformulate it if needed and otherwise return it as is."
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
contextualize_q_prompt = ChatPromptTemplate.from_messages([
|
| 27 |
+
("system", contextualize_q_system_prompt),
|
| 28 |
+
MessagesPlaceholder("chat_history"),
|
| 29 |
+
("human", "{input}"),
|
| 30 |
+
])
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
qa_prompt = ChatPromptTemplate.from_messages([
|
| 35 |
+
("system", "You are a helpful AI assistant. Use the following context to answer the user's question."),
|
| 36 |
+
("system", "Context: {context}"),
|
| 37 |
+
MessagesPlaceholder(variable_name="chat_history"),
|
| 38 |
+
("human", "{input}")
|
| 39 |
+
])
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def get_rag_chain(model="gpt-4o-mini"):
|
| 44 |
+
llm = ChatOpenAI(model=model)
|
| 45 |
+
history_aware_retriever = create_history_aware_retriever(llm, retriever, contextualize_q_prompt)
|
| 46 |
+
question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
|
| 47 |
+
rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
|
| 48 |
+
return rag_chain
|