Dharma20 commited on
Commit
dd64543
·
verified ·
1 Parent(s): b125f32

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +166 -0
pipeline.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from itertools import chain
3
+ from typing import Any, List
4
+
5
+ from haystack.components.converters import PyPDFToDocument, MarkdownToDocument, TextFileToDocument, OutputAdapter
6
+ from haystack.components.routers import FileTypeRouter
7
+ from haystack.components.joiners import DocumentJoiner
8
+ from haystack.components.preprocessors import DocumentCleaner, DocumentSplitter
9
+ from haystack.components.embedders import SentenceTransformersDocumentEmbedder
10
+ from haystack.components.writers import DocumentWriter
11
+ from haystack.components.builders import ChatPromptBuilder, PromptBuilder
12
+ from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
13
+ from haystack.document_stores.in_memory import InMemoryDocumentStore
14
+ from haystack.core.component.types import Variadic
15
+
16
+ from haystack_experimental.chat_message_stores.in_memory import InMemoryChatMessageStore
17
+ from haystack_experimental.components.retrievers import ChatMessageRetriever
18
+ from haystack_experimental.components.writers import ChatMessageWriter
19
+ from haystack_integrations.components.generators.cohere import CohereChatGenerator, CohereGenerator
20
+ from haystack_experimental.components.retrievers import ChatMessageRetriever
21
+ from haystack_experimental.components.writers import ChatMessageWriter
22
+
23
+ from haystack.dataclasses import ChatMessage
24
+ from haystack import Pipeline
25
+ from haystack import component
26
+
27
+ import os
28
+ from dotenv import load_dotenv
29
+
30
+ # Load .env file
31
+ load_dotenv()
32
+
33
+ # Access the API key
34
+ os.environ["COHERE_API_KEY"] = os.getenv('COHERE_API_KEY')
35
+
36
+
37
+ document_store = InMemoryDocumentStore()
38
+ file_type_router = FileTypeRouter(mime_types=['text/plain','application/pdf','text/markdown'])
39
+ pdf_converter = PyPDFToDocument()
40
+ text_file_converter = TextFileToDocument()
41
+ markdown_converter = MarkdownToDocument()
42
+ document_joiner = DocumentJoiner()
43
+ document_cleaner = DocumentCleaner()
44
+ document_splitter = DocumentSplitter(split_by='word', split_overlap=50)
45
+ document_embedder = SentenceTransformersDocumentEmbedder(model="sentence-transformers/all-MiniLM-L12-v2")
46
+ document_writer = DocumentWriter(document_store)
47
+
48
+
49
+ preprocessing_pipeline = Pipeline()
50
+
51
+
52
+ # Adding Componenets
53
+ preprocessing_pipeline.add_component('file_type_router', file_type_router)
54
+ preprocessing_pipeline.add_component('text_file_converter', text_file_converter)
55
+ preprocessing_pipeline.add_component('markdown_converter', markdown_converter)
56
+ preprocessing_pipeline.add_component('pdf_converter', pdf_converter)
57
+ preprocessing_pipeline.add_component('document_joiner', document_joiner)
58
+ preprocessing_pipeline.add_component('document_cleaner', document_cleaner)
59
+ preprocessing_pipeline.add_component('document_splitter', document_splitter)
60
+ preprocessing_pipeline.add_component('document_embedder', document_embedder)
61
+ preprocessing_pipeline.add_component('document_writer', document_writer)
62
+
63
+
64
+ # Connections
65
+
66
+ preprocessing_pipeline.connect('file_type_router.text/plain', 'text_file_converter.sources')
67
+ preprocessing_pipeline.connect('file_type_router.application/pdf', 'pdf_converter.sources')
68
+ preprocessing_pipeline.connect('file_type_router.text/markdown', 'markdown_converter.sources')
69
+ preprocessing_pipeline.connect('text_file_converter', 'document_joiner')
70
+ preprocessing_pipeline.connect('markdown_converter', 'document_joiner')
71
+ preprocessing_pipeline.connect('pdf_converter', 'document_joiner')
72
+ preprocessing_pipeline.connect('document_joiner', 'document_cleaner')
73
+ preprocessing_pipeline.connect('document_cleaner', 'document_splitter')
74
+ preprocessing_pipeline.connect('document_splitter', 'document_embedder')
75
+ preprocessing_pipeline.connect('document_embedder', 'document_writer')
76
+
77
+
78
+ @component
79
+ class ListJoiner:
80
+ def __init__(self, _type: Any):
81
+ component.set_output_types(self, values=_type)
82
+
83
+ def run(self, values:Variadic[Any]):
84
+ result = list(chain(*values))
85
+ return {'values':result}
86
+
87
+
88
+ memory_store = InMemoryChatMessageStore()
89
+
90
+ query_rephrase_template="""
91
+ Rewrite the question for search while keeping its meaning and key terms intact.
92
+ If the conversation history is empty, DO NOT change the query.
93
+ Use conversation history only if necessary, and avoid extending the query with your own knowledge.
94
+ If no changes are needed, output the current question as is.
95
+
96
+ Conversation history:
97
+ {% for memory in memories %}
98
+ {{ memory.content }}
99
+ {% endfor %}
100
+
101
+ User Query: {{query}}
102
+ Rewritten Query:
103
+ """
104
+
105
+
106
+ conversational_rag = Pipeline()
107
+
108
+ #Query rephrasing components
109
+ conversational_rag.add_component("query_rephrase_prompt_builder",PromptBuilder(query_rephrase_template))
110
+ conversational_rag.add_component('query_rephrase_llm',CohereGenerator())
111
+ conversational_rag.add_component('list_to_str_adapter', OutputAdapter(template="{{ replies[0] }}", output_type=str))
112
+
113
+ #RAG components
114
+ conversational_rag.add_component('retriever', InMemoryBM25Retriever(document_store=document_store, top_k=3))
115
+ conversational_rag.add_component('prompt_builder', ChatPromptBuilder(variables=["query", "documents", "memories"],required_variables=['query', 'documents', 'memories']))
116
+ conversational_rag.add_component('llm', CohereChatGenerator())
117
+
118
+ #Memory components
119
+ conversational_rag.add_component('memory_retriever',ChatMessageRetriever(memory_store))
120
+ conversational_rag.add_component('memory_writer', ChatMessageWriter(memory_store))
121
+ conversational_rag.add_component('memory_joiner', ListJoiner(List[ChatMessage]))
122
+
123
+
124
+ #Query Rephrasing Connections
125
+ conversational_rag.connect('memory_retriever', 'query_rephrase_prompt_builder.memories')
126
+ conversational_rag.connect('query_rephrase_prompt_builder.prompt', 'query_rephrase_llm' )
127
+ conversational_rag.connect('query_rephrase_llm.replies', 'list_to_str_adapter')
128
+ conversational_rag.connect('list_to_str_adapter', 'retriever.query')
129
+
130
+ #RAG connections
131
+ conversational_rag.connect('retriever.documents', 'prompt_builder.documents')
132
+ conversational_rag.connect('prompt_builder.prompt', 'llm.messages')
133
+ conversational_rag.connect('llm.replies', 'memory_joiner')
134
+
135
+ #Memory Connections
136
+ conversational_rag.connect('memory_joiner','memory_writer')
137
+ conversational_rag.connect('memory_retriever','prompt_builder.memories')
138
+
139
+
140
+ system_message = ChatMessage.from_system("""You are an intelligent and cheerful AI assistant specialized in assisting humans with queries based on provided supporting documents and conversation history.
141
+ Always prioritize accurate and concise answers derived from the documents, and offer contextually relevant follow-up questions to maintain an engaging and helpful conversation.
142
+ If the answer is not present in the documents, politely inform the user while suggesting alternative ways to help""")
143
+
144
+ user_message_template ="""Based on the conversation history and the provided supporting documents, provide a brief and accurate answer to the question.
145
+ Make the conversation feel more natural and engaging
146
+
147
+ - Format your response for clarity and readability, using bullet points, paragraphs, or lists where necessary.
148
+ - Note: Supporting documents are not part of the conversation history.
149
+ - If the question cannot be answered using the supporting documents, respond with: "The answer is not available in the provided documents."
150
+
151
+ Conversation History:
152
+ {% for memory in memories %}
153
+ {{ memory.content }}
154
+ {% endfor %}
155
+
156
+ Supporting Documents:
157
+ {% for doc in documents %}
158
+ {{ doc.content }}
159
+ {% endfor %}
160
+
161
+ Question: {{ query }}
162
+ Answer:
163
+
164
+ """
165
+ user_message = ChatMessage.from_user(user_message_template)
166
+