-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathchain.py
68 lines (59 loc) · 1.44 KB
/
chain.py
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
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
from langchain_core.runnables import (
RunnableLambda,
RunnableParallel,
RunnablePassthrough,
)
from langchain_exa import ExaSearchRetriever
from langchain_openai import ChatOpenAI
retriever = ExaSearchRetriever(k=3, highlights=True)
document_prompt = PromptTemplate.from_template(
"""
<source>
<url>{url}</url>
<highlights>{highlights}</highlights>
</source>
"""
)
document_chain = (
RunnableLambda(
lambda document: {
"highlights": document.metadata["highlights"],
"url": document.metadata["url"],
}
)
| document_prompt
)
retrieval_chain = (
retriever | document_chain.map() | (lambda docs: "\n".join([i.text for i in docs]))
)
generation_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are an expert research assistant. You use xml-formatted context to research people's questions.",
),
(
"human",
"""
Please answer the following query based on the provided context. Please cite your sources at the end of your response.:
Query: {query}
---
<context>
{context}
</context>
""",
),
]
)
llm = ChatOpenAI()
chain = (
RunnableParallel(
{
"query": RunnablePassthrough(),
"context": retrieval_chain,
}
)
| generation_prompt
| llm
).with_types(input_type=str)