-
Notifications
You must be signed in to change notification settings - Fork 101
/
question_answering.py
821 lines (694 loc) · 29.8 KB
/
question_answering.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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
# Copyright © 2024 Pathway
import json
from enum import Enum
import requests
import pathway as pw
from pathway.internals import ColumnReference, Table
from pathway.stdlib.indexing import DataIndex
from pathway.xpacks.llm import Doc, llms, prompts
from pathway.xpacks.llm.llms import prompt_chat_single_qa
from pathway.xpacks.llm.prompts import prompt_qa_geometric_rag
from pathway.xpacks.llm.vector_store import VectorStoreClient, VectorStoreServer
@pw.udf
def _limit_documents(documents: list[str], k: int) -> list[str]:
return documents[:k]
_answer_not_known = "I could not find an answer."
_answer_not_known_open_source = "No information available."
def _query_chat_strict_json(chat: pw.UDF, t: Table) -> pw.Table:
t += t.select(
prompt=prompt_qa_geometric_rag(
t.query, t.documents, _answer_not_known_open_source, strict_prompt=True
)
)
answer = t.select(answer=chat(prompt_chat_single_qa(t.prompt)))
@pw.udf
def extract_answer(response: str) -> str:
response = response.strip() # mistral-7b occasionally puts empty spaces
json_start, json_finish = response.find("{"), response.find(
"}"
) # remove unparsable part, mistral sometimes puts `[sources]` after the json
unparsed_json = response[json_start : json_finish + 1]
answer_dict = json.loads(unparsed_json)
return " ".join(answer_dict.values())
answer = answer.select(answer=extract_answer(pw.this.answer))
@pw.udf
def check_no_information(pred: str) -> bool:
return "No information" in pred
answer = answer.select(
answer=pw.if_else(check_no_information(pw.this.answer), None, pw.this.answer)
)
return answer
def _query_chat_gpt(chat: pw.UDF, t: Table) -> pw.Table:
t += t.select(
prompt=prompt_qa_geometric_rag(t.query, t.documents, _answer_not_known)
)
answer = t.select(answer=chat(prompt_chat_single_qa(t.prompt)))
answer = answer.select(
answer=pw.if_else(pw.this.answer == _answer_not_known, None, pw.this.answer)
)
return answer
def _query_chat(chat: pw.UDF, t: Table, strict_prompt: bool) -> pw.Table:
if strict_prompt:
return _query_chat_strict_json(chat, t)
else:
return _query_chat_gpt(chat, t)
def _query_chat_with_k_documents(
chat: pw.UDF, k: int, t: pw.Table, strict_prompt: bool
) -> pw.Table:
limited_documents = t.select(
pw.this.query, documents=_limit_documents(t.documents, k)
)
result = _query_chat(chat, limited_documents, strict_prompt)
return result
def answer_with_geometric_rag_strategy(
questions: ColumnReference,
documents: ColumnReference,
llm_chat_model: pw.UDF,
n_starting_documents: int,
factor: int,
max_iterations: int,
strict_prompt: bool = False,
) -> ColumnReference:
"""
Function for querying LLM chat while providing increasing number of documents until an answer
is found. Documents are taken from `documents` argument. Initially first `n_starting_documents` documents
are embedded in the query. If the LLM chat fails to find an answer, the number of documents
is multiplied by `factor` and the question is asked again.
Args:
questions (ColumnReference[str]): Column with questions to be asked to the LLM chat.
documents (ColumnReference[list[str]]): Column with documents to be provided along
with a question to the LLM chat.
llm_chat_model: Chat model which will be queried for answers
n_starting_documents: Number of documents embedded in the first query.
factor: Factor by which a number of documents increases in each next query, if
an answer is not found.
max_iterations: Number of times to ask a question, with the increasing number of documents.
strict_prompt: If LLM should be instructed strictly to return json.
Increases performance in small open source models, not needed in OpenAI GPT models.
Returns:
A column with answers to the question. If answer is not found, then None is returned.
Example:
>>> import pandas as pd
>>> import pathway as pw
>>> from pathway.xpacks.llm.llms import OpenAIChat
>>> from pathway.xpacks.llm.question_answering import answer_with_geometric_rag_strategy
>>> chat = OpenAIChat()
>>> df = pd.DataFrame(
... {
... "question": ["How do you connect to Kafka from Pathway?"],
... "documents": [
... [
... "`pw.io.csv.read reads a table from one or several files with delimiter-separated values.",
... "`pw.io.kafka.read` is a seneralized method to read the data from the given topic in Kafka.",
... ]
... ],
... }
... )
>>> t = pw.debug.table_from_pandas(df)
>>> answers = answer_with_geometric_rag_strategy(t.question, t.documents, chat, 1, 2, 2)
"""
n_documents = n_starting_documents
t = Table.from_columns(query=questions, documents=documents)
t = t.with_columns(answer=None)
for _ in range(max_iterations):
rows_without_answer = t.filter(pw.this.answer.is_none())
results = _query_chat_with_k_documents(
llm_chat_model, n_documents, rows_without_answer, strict_prompt
)
new_answers = rows_without_answer.with_columns(answer=results.answer)
t = t.update_rows(new_answers)
n_documents *= factor
return t.answer
def answer_with_geometric_rag_strategy_from_index(
questions: ColumnReference,
index: DataIndex,
documents_column: str | ColumnReference,
llm_chat_model: pw.UDF,
n_starting_documents: int,
factor: int,
max_iterations: int,
metadata_filter: pw.ColumnExpression | None = None,
strict_prompt: bool = False,
) -> ColumnReference:
"""
Function for querying LLM chat while providing increasing number of documents until an answer
is found. Documents are taken from `index`. Initially first `n_starting_documents` documents
are embedded in the query. If the LLM chat fails to find an answer, the number of documents
is multiplied by `factor` and the question is asked again.
Args:
questions (ColumnReference[str]): Column with questions to be asked to the LLM chat.
index: Index from which closest documents are obtained.
documents_column: name of the column in table passed to index, which contains documents.
llm_chat_model: Chat model which will be queried for answers
n_starting_documents: Number of documents embedded in the first query.
factor: Factor by which a number of documents increases in each next query, if
an answer is not found.
max_iterations: Number of times to ask a question, with the increasing number of documents.
strict_prompt: If LLM should be instructed strictly to return json.
Increases performance in small open source models, not needed in OpenAI GPT models.
Returns:
A column with answers to the question. If answer is not found, then None is returned.
"""
max_documents = n_starting_documents * (factor ** (max_iterations - 1))
if isinstance(documents_column, ColumnReference):
documents_column_name = documents_column.name
else:
documents_column_name = documents_column
query_context = questions.table + index.query_as_of_now(
questions,
number_of_matches=max_documents,
collapse_rows=True,
metadata_filter=metadata_filter,
).select(
documents_list=pw.this[documents_column_name],
)
return answer_with_geometric_rag_strategy(
questions,
query_context.documents_list,
llm_chat_model,
n_starting_documents,
factor,
max_iterations,
strict_prompt=strict_prompt,
)
class AIResponseType(Enum):
SHORT = "short"
LONG = "long"
@pw.udf
def _filter_document_metadata(
docs: pw.Json | list[pw.Json] | list[Doc], metadata_keys: list[str] = ["path"]
) -> list[Doc]:
"""Filter context document metadata to keep the keys in the
provided `metadata_keys` list.
Works on both ColumnReference and list of pw.Json."""
if isinstance(docs, pw.Json):
doc_ls: list[Doc] = docs.as_list()
elif isinstance(docs, list) and all([isinstance(dc, dict) for dc in docs]):
doc_ls = docs # type: ignore
elif all([isinstance(dc, pw.Json) for dc in docs]):
doc_ls = [dc.as_dict() for dc in docs] # type: ignore
else:
raise ValueError(
"""`docs` argument is not instance of (pw.Json | list[pw.Json] | list[Doc]).
Please check your pipeline. Using `pw.reducers.tuple` may help."""
)
if len(doc_ls) == 1 and isinstance(doc_ls[0], list | tuple): # unpack if needed
doc_ls = doc_ls[0]
filtered_docs = []
for doc in doc_ls:
filtered_doc = {"text": doc["text"]}
for key in metadata_keys:
if key in doc.get("metadata", {}):
assert isinstance(doc["metadata"], dict)
metadata_dict: dict = doc["metadata"]
filtered_doc[key] = metadata_dict[key]
filtered_docs.append(filtered_doc)
return filtered_docs
class BaseRAGQuestionAnswerer:
"""
Builds the logic and the API for basic RAG application.
Base class to build RAG app with Pathway vector store and Pathway components.
Gives the freedom to choose between two question answering strategies,
short (concise), and long (detailed) response, that can be set during the post request.
Allows for LLM agnosticity with freedom to choose from proprietary or open-source LLMs.
Args:
llm: LLM instance for question answering. See https://pathway.com/developers/api-docs/pathway-xpacks-llm/llms for available models.
indexer: Indexing object for search & retrieval to be used for context augmentation.
default_llm_name: Default LLM model to be used in queries, only used if ``model`` parameter in post request is not specified.
Omitting or setting this to ``None`` will default to the model name set during LLM's initialization.
short_prompt_template: Template for document question answering with short response.
A pw.udf function is expected. Defaults to ``pathway.xpacks.llm.prompts.prompt_short_qa``.
long_prompt_template: Template for document question answering with long response.
A pw.udf function is expected. Defaults to ``pathway.xpacks.llm.prompts.prompt_qa``.
summarize_template: Template for text summarization. Defaults to ``pathway.xpacks.llm.prompts.prompt_summarize``.
search_topk: Top k parameter for the retrieval. Adjusts number of chunks in the context.
Example:
>>> import pathway as pw # doctest: +SKIP
>>> from pathway.xpacks.llm import embedders, splitters, llms, parsers # doctest: +SKIP
>>> from pathway.xpacks.llm.vector_store import VectorStoreServer # doctest: +SKIP
>>> from pathway.udfs import DiskCache, ExponentialBackoffRetryStrategy # doctest: +SKIP
>>> from pathway.xpacks.llm.question_answering import BaseRAGQuestionAnswerer # doctest: +SKIP
>>> my_folder = pw.io.fs.read(
... path="/PATH/TO/MY/DATA/*", # replace with your folder
... format="binary",
... with_metadata=True) # doctest: +SKIP
>>> sources = [my_folder] # doctest: +SKIP
>>> app_host = "0.0.0.0" # doctest: +SKIP
>>> app_port = 8000 # doctest: +SKIP
>>> parser = parsers.ParseUnstructured() # doctest: +SKIP
>>> text_splitter = splitters.TokenCountSplitter(max_tokens=400) # doctest: +SKIP
>>> embedder = embedders.OpenAIEmbedder(cache_strategy=DiskCache()) # doctest: +SKIP
>>> vector_server = VectorStoreServer( # doctest: +SKIP
... *sources,
... embedder=embedder,
... splitter=text_splitter,
... parser=parser,
... )
>>> chat = llms.OpenAIChat( # doctest: +SKIP
... model=DEFAULT_GPT_MODEL,
... retry_strategy=ExponentialBackoffRetryStrategy(max_retries=6),
... cache_strategy=DiskCache(),
... temperature=0.05,
... )
>>> app = BaseRAGQuestionAnswerer( # doctest: +SKIP
... llm=chat,
... indexer=vector_server,
... )
>>> app.build_server(host=app_host, port=app_port) # doctest: +SKIP
>>> app.run_server() # doctest: +SKIP
""" # noqa: E501
def __init__(
self,
llm: pw.UDF,
indexer: VectorStoreServer,
*,
default_llm_name: str | None = None,
short_prompt_template: pw.UDF = prompts.prompt_short_qa,
long_prompt_template: pw.UDF = prompts.prompt_qa,
summarize_template: pw.UDF = prompts.prompt_summarize,
search_topk: int = 6,
) -> None:
self.llm = llm
self.indexer = indexer
if default_llm_name is None:
# user implemented udfs do not have to have kwargs attribute
if hasattr(llm, "kwargs"):
default_llm_name = llm.kwargs.get("model", None)
self._init_schemas(default_llm_name)
self.short_prompt_template = short_prompt_template
self.long_prompt_template = long_prompt_template
self.summarize_template = summarize_template
self.search_topk = search_topk
def _init_schemas(self, default_llm_name: str | None = None) -> None:
"""Initialize API schemas with optional and non-optional arguments."""
class PWAIQuerySchema(pw.Schema):
prompt: str
filters: str | None = pw.column_definition(default_value=None)
model: str | None = pw.column_definition(default_value=default_llm_name)
response_type: str = pw.column_definition(
default_value=AIResponseType.SHORT.value
)
class SummarizeQuerySchema(pw.Schema):
text_list: list[str]
model: str | None = pw.column_definition(default_value=default_llm_name)
self.PWAIQuerySchema = PWAIQuerySchema
self.SummarizeQuerySchema = SummarizeQuerySchema
@pw.table_transformer
def pw_ai_query(self, pw_ai_queries: pw.Table) -> pw.Table:
"""Main function for RAG applications that answer questions
based on available information."""
pw_ai_results = pw_ai_queries + self.indexer.retrieve_query(
pw_ai_queries.select(
metadata_filter=pw.this.filters,
filepath_globpattern=pw.cast(str | None, None),
query=pw.this.prompt,
k=self.search_topk,
)
).select(
docs=pw.this.result,
)
pw_ai_results = pw_ai_results.select(
*pw.this, filtered_docs=_filter_document_metadata(pw.this.docs)
)
pw_ai_results += pw_ai_results.select(
rag_prompt=pw.if_else(
pw.this.response_type == AIResponseType.SHORT.value,
self.short_prompt_template(pw.this.prompt, pw.this.filtered_docs),
self.long_prompt_template(pw.this.prompt, pw.this.filtered_docs),
)
)
pw_ai_results += pw_ai_results.select(
result=self.llm(
llms.prompt_chat_single_qa(pw.this.rag_prompt),
model=pw.this.model,
)
)
return pw_ai_results
@pw.table_transformer
def summarize_query(self, summarize_queries: pw.Table) -> pw.Table:
"""Function for summarizing given texts."""
summarize_results = summarize_queries.select(
pw.this.model,
prompt=self.summarize_template(pw.this.text_list),
)
summarize_results += summarize_results.select(
result=self.llm(
llms.prompt_chat_single_qa(pw.this.prompt),
model=pw.this.model,
)
)
return summarize_results
# connect http endpoint to output writer
def serve(self, route, schema, handler, webserver, **additional_endpoint_kwargs):
queries, writer = pw.io.http.rest_connector(
webserver=webserver,
route=route,
schema=schema,
autocommit_duration_ms=50,
delete_completed_queries=False,
**additional_endpoint_kwargs,
)
writer(handler(queries))
def build_server(
self,
host: str,
port: int,
**rest_kwargs,
) -> None:
"""Adds HTTP connectors to input tables, connects them with table transformers."""
webserver = pw.io.http.PathwayWebserver(host=host, port=port)
self.serve(
"/v1/retrieve",
self.indexer.RetrieveQuerySchema,
self.indexer.retrieve_query,
webserver,
**rest_kwargs,
)
self.serve(
"/v1/statistics",
self.indexer.StatisticsQuerySchema,
self.indexer.statistics_query,
webserver,
**rest_kwargs,
)
self.serve(
"/v1/pw_list_documents",
self.indexer.InputsQuerySchema,
self.indexer.inputs_query,
webserver,
**rest_kwargs,
)
self.serve(
"/v1/pw_ai_answer",
self.PWAIQuerySchema,
self.pw_ai_query,
webserver,
**rest_kwargs,
)
self.serve(
"/v1/pw_ai_summary",
self.SummarizeQuerySchema,
self.summarize_query,
webserver,
**rest_kwargs,
)
def run_server(
self,
with_cache: bool = True,
cache_backend: (
pw.persistence.Backend | None
) = pw.persistence.Backend.filesystem("./Cache"),
*args,
**kwargs,
):
"""Start the app with cache configs. Enabling persistence will cache the embedding,
and LLM requests between the runs."""
if with_cache:
if cache_backend is None:
raise ValueError(
"Cache usage was requested but the backend is unspecified"
)
persistence_config = pw.persistence.Config.simple_config(
cache_backend,
persistence_mode=pw.PersistenceMode.UDF_CACHING,
)
else:
persistence_config = None
pw.run(
monitoring_level=pw.MonitoringLevel.NONE,
persistence_config=persistence_config,
*args,
**kwargs,
)
class AdaptiveRAGQuestionAnswerer(BaseRAGQuestionAnswerer):
"""
Builds the logic and the API for adaptive RAG application.
It allows to build a RAG app with Pathway vector store and Pathway components.
Gives the freedom to choose between two question answering strategies,
short (concise), and long (detailed) response, that can be set during the post request.
Allows for LLM agnosticity with freedom to choose from proprietary or open-source LLMs.
It differs from :py:class:`~pathway.xpacks.llm.question_answering.BaseRAGQuestionAnswerer`
in adaptive choosing the number of chunks used as a context of a question.
First, only ``n_starting_documents`` chunks are used,
and then the number is increased until an answer is found.
Args:
llm: LLM instance for question answering. See https://pathway.com/developers/api-docs/pathway-xpacks-llm/llms for available models.
indexer: Indexing object for search & retrieval to be used for context augmentation.
default_llm_name: Default LLM model to be used in queries, only used if ``model`` parameter in post request is not specified.
Omitting or setting this to ``None`` will default to the model name set during LLM's initialization.
short_prompt_template: Template for document question answering with short response.
A pw.udf function is expected. Defaults to ``pathway.xpacks.llm.prompts.prompt_short_qa``.
long_prompt_template: Template for document question answering with long response.
A pw.udf function is expected. Defaults to ``pathway.xpacks.llm.prompts.prompt_qa``.
summarize_template: Template for text summarization. Defaults to ``pathway.xpacks.llm.prompts.prompt_summarize``.
n_starting_documents: Number of documents embedded in the first query.
factor: Factor by which a number of documents increases in each next query, if
an answer is not found.
max_iterations: Number of times to ask a question, with the increasing number of documents.
strict_prompt: If LLM should be instructed strictly to return json.
Increases performance in small open source models, not needed in OpenAI GPT models.
Example:
>>> import pathway as pw # doctest: +SKIP
>>> from pathway.xpacks.llm import embedders, splitters, llms, parsers # doctest: +SKIP
>>> from pathway.xpacks.llm.vector_store import VectorStoreServer # doctest: +SKIP
>>> from pathway.udfs import DiskCache, ExponentialBackoffRetryStrategy # doctest: +SKIP
>>> from pathway.xpacks.llm.question_answering import AdaptiveRAGQuestionAnswerer # doctest: +SKIP
>>> my_folder = pw.io.fs.read(
... path="/PATH/TO/MY/DATA/*", # replace with your folder
... format="binary",
... with_metadata=True) # doctest: +SKIP
>>> sources = [my_folder] # doctest: +SKIP
>>> app_host = "0.0.0.0" # doctest: +SKIP
>>> app_port = 8000 # doctest: +SKIP
>>> parser = parsers.ParseUnstructured() # doctest: +SKIP
>>> text_splitter = splitters.TokenCountSplitter(max_tokens=400) # doctest: +SKIP
>>> embedder = embedders.OpenAIEmbedder(cache_strategy=DiskCache()) # doctest: +SKIP
>>> vector_server = VectorStoreServer( # doctest: +SKIP
... *sources,
... embedder=embedder,
... splitter=text_splitter,
... parser=parser,
... )
>>> chat = llms.OpenAIChat( # doctest: +SKIP
... model=DEFAULT_GPT_MODEL,
... retry_strategy=ExponentialBackoffRetryStrategy(max_retries=6),
... cache_strategy=DiskCache(),
... temperature=0.05,
... )
>>> app = AdaptiveRAGQuestionAnswerer( # doctest: +SKIP
... llm=chat,
... indexer=vector_server,
... )
>>> app.build_server(host=app_host, port=app_port) # doctest: +SKIP
>>> app.run_server() # doctest: +SKIP
""" # noqa: E501
def __init__(
self,
llm: pw.UDF,
indexer: VectorStoreServer,
*,
default_llm_name: str | None = None,
short_prompt_template: pw.UDF = prompts.prompt_short_qa,
long_prompt_template: pw.UDF = prompts.prompt_qa,
summarize_template: pw.UDF = prompts.prompt_summarize,
n_starting_documents: int = 2,
factor: int = 2,
max_iterations: int = 4,
strict_prompt: bool = False,
) -> None:
super().__init__(
llm,
indexer,
default_llm_name=default_llm_name,
short_prompt_template=short_prompt_template,
long_prompt_template=long_prompt_template,
summarize_template=summarize_template,
)
self.n_starting_documents = n_starting_documents
self.factor = factor
self.max_iterations = max_iterations
self.strict_prompt = strict_prompt
@pw.table_transformer
def pw_ai_query(self, pw_ai_queries: pw.Table) -> pw.Table:
"""Create RAG response with adaptive retrieval."""
index = self.indexer.index
result = pw_ai_queries.select(
*pw.this,
result=answer_with_geometric_rag_strategy_from_index(
pw_ai_queries.prompt,
index,
"data", # knn index returns result in this column
self.llm,
n_starting_documents=self.n_starting_documents,
factor=self.factor,
max_iterations=self.max_iterations,
strict_prompt=self.strict_prompt,
metadata_filter=pw_ai_queries.filters,
),
)
return result
class DeckRetriever(BaseRAGQuestionAnswerer):
"""Class for slides search."""
excluded_response_metadata = ["b64_image"]
@pw.table_transformer
def pw_ai_query(self, pw_ai_queries: pw.Table) -> pw.Table:
"""Return similar docs from the index."""
pw_ai_results = pw_ai_queries + self.indexer.retrieve_query(
pw_ai_queries.select(
metadata_filter=pw.this.filters,
filepath_globpattern=None,
query=pw.this.prompt,
k=self.search_topk,
)
).select(
docs=pw.this.result,
)
@pw.udf
def _format_results(docs: pw.Json) -> pw.Json:
docs_ls = docs.as_list()
for docs_dc in docs_ls:
metadata: dict = docs_dc["metadata"]
for metadata_key in self.excluded_response_metadata:
metadata.pop(metadata_key, None)
docs_dc["metadata"] = metadata
return pw.Json(docs_ls)
pw_ai_results += pw_ai_results.select(result=_format_results(pw.this.docs))
return pw_ai_results
def send_post_request(
url: str, data: dict, headers: dict = {}, timeout: int | None = None
):
response = requests.post(url, json=data, headers=headers, timeout=timeout)
response.raise_for_status()
return response.json()
class RAGClient:
"""
Connector for interacting with the Pathway RAG applications.
Either (`host` and `port`) or `url` must be set.
Args:
- host: The host of the RAG service.
- port: The port of the RAG service.
- url: The URL of the RAG service.
- timeout: Timeout for requests in seconds. Defaults to 90.
- additional_headers: Additional headers for the requests.
"""
def __init__(
self,
host: str | None = None,
port: int | None = None,
url: str | None = None,
timeout: int | None = 90,
additional_headers: dict | None = None,
):
err = "Either (`host` and `port`) or `url` must be provided, but not both."
if url is not None:
if host is not None or port is not None:
raise ValueError(err)
self.url = url
else:
if host is None:
raise ValueError(err)
port = port or 80
protocol = "https" if port == 443 else "http"
self.url = f"{protocol}://{host}:{port}"
self.timeout = timeout
self.additional_headers = additional_headers or {}
self.index_client = VectorStoreClient(
url=self.url,
timeout=self.timeout,
additional_headers=self.additional_headers,
)
def retrieve(
self,
query: str,
k: int = 3,
metadata_filter: str | None = None,
filepath_globpattern: str | None = None,
):
"""
Retrieve closest documents from the vector store based on a query.
Args:
- query: The query string.
- k: The number of results to retrieve.
- metadata_filter: Optional metadata filter for the documents. Defaults to `None`, which
means there will be no filter.
- filepath_globpattern: Glob pattern for file paths.
"""
return self.index_client.query(
query=query,
k=k,
metadata_filter=metadata_filter,
filepath_globpattern=filepath_globpattern,
)
def statistics(
self,
):
"""
Retrieve stats from the vector store.
"""
return self.index_client.get_vectorstore_statistics()
def pw_ai_answer(
self,
prompt: str,
filters: str | None = None,
model: str | None = None,
):
"""
Return RAG answer based on a given prompt and optional filter.
Args:
- prompt: Question to be asked.
- filters: Optional metadata filter for the documents. Defaults to ``None``, which
means there will be no filter.
- model: Optional LLM model. If ``None``, app default will be used by the server.
"""
api_url = f"{self.url}/v1/pw_ai_answer"
payload = {
"prompt": prompt,
}
if filters:
payload["filters"] = filters
if model:
payload["model"] = model
response = send_post_request(api_url, payload, self.additional_headers)
return response
def pw_ai_summary(
self,
text_list: list[str],
model: str | None = None,
):
"""
Summarize a list of texts.
Args:
- text_list: List of texts to summarize.
- model: Optional LLM model. If ``None``, app default will be used by the server.
"""
api_url = f"{self.url}/v1/pw_ai_summary"
payload: dict = {
"text_list": text_list,
}
if model:
payload["model"] = model
response = send_post_request(api_url, payload, self.additional_headers)
return response
def pw_list_documents(self, filters: str | None = None, keys: list[str] = ["path"]):
"""
List indexed documents from the vector store with optional filtering.
Args:
- filters: Optional metadata filter for the documents.
- keys: List of metadata keys to be included in the response.
Defaults to ``["path"]``. Setting to ``None`` will retrieve all available metadata.
"""
api_url = f"{self.url}/v1/pw_list_documents"
payload = {}
if filters:
payload["metadata_filter"] = filters
response: list[dict] = send_post_request(
api_url, payload, self.additional_headers
)
if response:
if keys:
result = [{k: v for k, v in dc.items() if k in keys} for dc in response]
else:
result = response
else:
result = []
return result