doc_chat_agent
langroid/agent/special/doc_chat_agent.py
Agent that supports asking queries about a set of documents, using retrieval-augmented generation (RAG).
Functionality includes:
- summarizing a document, with a custom instruction; see summarize_docs
- asking a question about a document; see answer_from_docs
Note: to use the sentence-transformer embeddings, you must install langroid with the [hf-embeddings] extra, e.g.:
pip install "langroid[hf-embeddings]"
DocChatAgent(config)
¶
Bases: ChatAgent
Agent for chatting with a collection of documents.
Source code in langroid/agent/special/doc_chat_agent.py
clear()
¶
Clear the document collection and the specific collection in vecdb
Source code in langroid/agent/special/doc_chat_agent.py
ingest()
¶
Chunk + embed + store docs specified by self.config.doc_paths
Source code in langroid/agent/special/doc_chat_agent.py
ingest_doc_paths(paths, metadata=[], doc_type=None)
¶
Split, ingest docs from specified paths, do not add these to config.doc_paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
str | bytes | List[str | bytes]
|
document paths, urls or byte-content of docs. The bytes option is intended to support cases where a document has already been read in as bytes (e.g. from an API or a database), and we want to avoid having to write it to a temporary file just to read it back in. |
required |
metadata
|
List[Dict[str, Any]] | Dict[str, Any] | DocMetaData | List[DocMetaData]
|
List of metadata dicts, one for each path. If a single dict is passed in, it is used for all paths. |
[]
|
doc_type
|
str | DocumentType | None
|
DocumentType to use for parsing, if known.
MUST apply to all docs if specified.
This is especially useful when the |
None
|
Returns: List of Document objects
Source code in langroid/agent/special/doc_chat_agent.py
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 | |
ingest_docs(docs, split=True, metadata=[])
¶
Chunk docs into pieces, map each chunk to vec-embedding, store in vec-db
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[Document]
|
List of Document objects |
required |
split
|
bool
|
Whether to split docs into chunks. Default is True. If False, docs are treated as "chunks" and are not split. |
True
|
metadata
|
List[Dict[str, Any]] | Dict[str, Any] | DocMetaData | List[DocMetaData]
|
List of metadata dicts, one for each doc, to augment whatever metadata is already in the doc. [ASSUME no conflicting keys between the two metadata dicts.] If a single dict is passed in, it is used for all docs. |
[]
|
Source code in langroid/agent/special/doc_chat_agent.py
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 | |
retrieval_tool(msg)
¶
Handle the RetrievalTool message
Source code in langroid/agent/special/doc_chat_agent.py
document_compatible_dataframe(df, content='content', metadata=[])
staticmethod
¶
Convert dataframe so it is compatible with Document class: - has "content" column - has an "id" column to be used as Document.metadata.id
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
dataframe to convert |
required |
content
|
str
|
name of content column |
'content'
|
metadata
|
List[str]
|
list of metadata column names |
[]
|
Returns:
| Type | Description |
|---|---|
Tuple[DataFrame, List[str]]
|
Tuple[pd.DataFrame, List[str]]: dataframe, metadata - dataframe: dataframe with "content" column and "id" column - metadata: list of metadata column names, including "id" |
Source code in langroid/agent/special/doc_chat_agent.py
ingest_dataframe(df, content='content', metadata=[])
¶
Ingest a dataframe into vecdb.
Source code in langroid/agent/special/doc_chat_agent.py
setup_documents(docs=[], filter=None)
¶
Setup self.chunked_docs and self.chunked_docs_clean
based on possible filter.
These will be used in various non-vector-based search functions,
e.g. self.get_similar_chunks_bm25(), self.get_fuzzy_matches(), etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[Document]
|
List of Document objects. This is empty when we are calling this method after initial doc ingestion. |
[]
|
filter
|
str | None
|
Filter condition for various lexical/semantic search fns. |
None
|
Source code in langroid/agent/special/doc_chat_agent.py
get_field_values(fields)
¶
Get string-listing of possible values of each field, e.g. { "genre": "crime, drama, mystery, ... (10 more)", "certificate": "R, PG-13, PG, R", } The field names may have "metadata." prefix, e.g. "metadata.genre".
Source code in langroid/agent/special/doc_chat_agent.py
doc_length(docs)
¶
Calc token-length of a list of docs Args: docs: list of Document objects Returns: int: number of tokens
Source code in langroid/agent/special/doc_chat_agent.py
user_docs_ingest_dialog()
¶
Ask user to select doc-collection, enter filenames/urls, and ingest into vecdb.
Source code in langroid/agent/special/doc_chat_agent.py
doc_string(docs)
staticmethod
¶
Generate a string representation of a list of docs. Args: docs: list of Document objects Returns: str: string representation
Source code in langroid/agent/special/doc_chat_agent.py
get_summary_answer(question, passages)
¶
Given a question and a list of (possibly) doc snippets,
generate an answer if possible
Args:
question: question to answer
passages: list of Document objects each containing a possibly relevant
snippet, and metadata
Returns:
a Document object containing the answer,
and metadata containing source citations
Source code in langroid/agent/special/doc_chat_agent.py
enrich_chunks(docs)
¶
Enrich chunks using Agent configured with self.config.chunk_enrichment_config.
We assume that the system message of the agent is set in such a way that when we run
prompt = self.config.chunk_enrichment_config.enrichment_prompt_fn(text)
result = await agent.llm_response_forget_async(prompt)
then result.content will contain the augmentation to the text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[Document]
|
List of document chunks to enrich |
required |
Returns:
| Type | Description |
|---|---|
List[Document]
|
List[Document]: Documents (chunks) enriched with additional text, separated by a delimiter. |
Source code in langroid/agent/special/doc_chat_agent.py
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 | |
rerank_with_diversity(passages)
¶
Rerank a list of items in such a way that each successive item is least similar (on average) to the earlier items.
Args: query (str): The query for which the passages are relevant. passages (List[Document]): A list of Documents to be reranked.
Returns: List[Documents]: A reranked list of Documents.
Source code in langroid/agent/special/doc_chat_agent.py
rerank_to_periphery(passages)
¶
Rerank to avoid Lost In the Middle (LIM) problem, where LLMs pay more attention to items at the ends of a list, rather than the middle. So we re-rank to make the best passages appear at the periphery of the list. https://arxiv.org/abs/2307.03172
Example reranking: 1 2 3 4 5 6 7 8 9 ==> 1 3 5 7 9 8 6 4 2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
passages
|
List[Document]
|
A list of Documents to be reranked. |
required |
Returns:
| Type | Description |
|---|---|
List[Document]
|
List[Documents]: A reranked list of Documents. |
Source code in langroid/agent/special/doc_chat_agent.py
add_context_window(docs_scores)
¶
In each doc's metadata, there may be a window_ids field indicating the ids of the chunks around the current chunk. We use these stored window_ids to retrieve the desired number (self.config.n_neighbor_chunks) of neighbors on either side of the current chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs_scores
|
List[Tuple[Document, float]]
|
List of pairs of documents to add context windows to together with their match scores. |
required |
Returns:
| Type | Description |
|---|---|
List[Tuple[Document, float]]
|
List[Tuple[Document, float]]: List of (Document, score) tuples. |
Source code in langroid/agent/special/doc_chat_agent.py
get_semantic_search_results(query, k=10)
¶
Get semantic search results from vecdb. Args: query (str): query to search for k (int): number of results to return Returns: List[Tuple[Document, float]]: List of (Document, score) tuples.
Source code in langroid/agent/special/doc_chat_agent.py
get_relevant_chunks(query, query_proxies=[])
¶
The retrieval stage in RAG: get doc-chunks that are most "relevant" to the query (and possibly any proxy queries), from the document-store, which currently is the vector store, but in theory could be any document store, or even web-search. This stage does NOT involve an LLM, and the retrieved chunks could either be pre-chunked text (from the initial pre-processing stage where chunks were stored in the vector store), or they could be dynamically retrieved based on a window around a lexical match.
These are the steps (some optional based on config): - semantic search based on vector-embedding distance, from vecdb - lexical search using bm25-ranking (keyword similarity) - fuzzy matching (keyword similarity) - re-ranking of doc-chunks by relevance to query, using cross-encoder, and pick top k
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
original query (assumed to be in stand-alone form) |
required |
query_proxies
|
List[str]
|
possible rephrases, or hypothetical answer to query (e.g. for HyDE-type retrieval) |
[]
|
Returns:
Source code in langroid/agent/special/doc_chat_agent.py
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 | |
get_relevant_extracts(query)
¶
Get list of (verbatim) extracts from doc-chunks relevant to answering a query.
These are the stages (some optional based on config): - use LLM to convert query to stand-alone query - optionally use LLM to rephrase query to use below - optionally use LLM to generate hypothetical answer (HyDE) to use below. - get_relevant_chunks(): get doc-chunks relevant to query and proxies - use LLM to get relevant extracts from doc-chunks
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
query to search for |
required |
Returns:
| Name | Type | Description |
|---|---|---|
query |
str
|
stand-alone version of input query |
List[Document]
|
List[Document]: list of relevant extracts |
Source code in langroid/agent/special/doc_chat_agent.py
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 | |
remove_chunk_enrichments(passages)
¶
Remove any enrichments (like hypothetical questions, or keywords) from documents. Only cleans if enrichment was enabled in config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
passages
|
List[Document]
|
List of documents to clean |
required |
Returns:
| Type | Description |
|---|---|
List[Document]
|
List of documents with only original content |
Source code in langroid/agent/special/doc_chat_agent.py
get_verbatim_extracts(query, passages)
¶
Run RelevanceExtractorAgent in async/concurrent mode on passages, to extract portions relevant to answering query, from each passage. Args: query (str): query to answer passages (List[Documents]): list of passages to extract from
Returns:
| Type | Description |
|---|---|
List[Document]
|
List[Document]: list of Documents containing extracts and metadata. |
Source code in langroid/agent/special/doc_chat_agent.py
answer_from_docs(query)
¶
Answer query based on relevant docs from the VecDB
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
query to answer |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Document |
ChatDocument
|
answer |
Source code in langroid/agent/special/doc_chat_agent.py
summarize_docs(instruction='Give a concise summary of the following text:')
¶
Summarize all docs
Source code in langroid/agent/special/doc_chat_agent.py
justify_response()
¶
Show evidence for last response