|
11 | 11 |
|
12 | 12 | # Imports from the library
|
13 | 13 | from .base_node import BaseNode
|
| 14 | +from langchain.text_splitter import RecursiveCharacterTextSplitter |
14 | 15 |
|
15 | 16 |
|
16 | 17 | class GenerateAnswerNode(BaseNode):
|
@@ -114,24 +115,30 @@ def execute(self, state: dict) -> dict:
|
114 | 115 | "chunk_id": i + 1, "format_instructions": format_instructions},
|
115 | 116 | )
|
116 | 117 | # Dynamically name the chains based on their index
|
117 |
| - chain_name = f"chunk{i+1}" |
118 |
| - chains_dict[chain_name] = prompt | self.llm | output_parser |
| 118 | + chains_dict[f"chunk{i+1}"] = prompt | self.llm | output_parser |
119 | 119 |
|
120 |
| - # Use dictionary unpacking to pass the dynamically named chains to RunnableParallel |
121 |
| - map_chain = RunnableParallel(**chains_dict) |
122 |
| - # Chain |
123 |
| - answer_map = map_chain.invoke({"question": user_input}) |
| 120 | + text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder( |
| 121 | + chunk_size=4000, |
| 122 | + chunk_overlap=0, |
| 123 | + ) |
| 124 | + |
| 125 | + chunks = text_splitter.split_text(str(chains_dict)) |
124 | 126 |
|
125 |
| - # Merge the answers from the chunks |
126 | 127 | merge_prompt = PromptTemplate(
|
127 | 128 | template=template_merge,
|
128 | 129 | input_variables=["context", "question"],
|
129 | 130 | partial_variables={"format_instructions": format_instructions},
|
130 | 131 | )
|
131 | 132 | merge_chain = merge_prompt | self.llm | output_parser
|
132 |
| - answer = merge_chain.invoke( |
133 |
| - {"context": answer_map, "question": user_input}) |
134 | 133 |
|
135 |
| - # Update the state with the generated answer |
| 134 | + answer_lines = [] |
| 135 | + for chunk in chunks: |
| 136 | + answer_temp = merge_chain.invoke( |
| 137 | + {"context": chunk, "question": user_input}) |
| 138 | + answer_lines.append(answer_temp) |
| 139 | + |
| 140 | + unique_answer_lines = list(set(answer_lines)) |
| 141 | + answer = '\n'.join(unique_answer_lines) |
| 142 | + |
136 | 143 | state.update({"answer": answer})
|
137 | 144 | return state
|
0 commit comments