forked from langchain-ai/chat-langchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
142 lines (113 loc) · 4.47 KB
/
utils.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
"""Shared utility functions used in the project.
Functions:
format_docs: Convert documents to an xml-formatted string.
load_chat_model: Load a chat model from a model name.
"""
import uuid
from typing import Any, Optional, Union
from langchain.chat_models import init_chat_model
from langchain_core.documents import Document
from langchain_core.language_models import BaseChatModel
def _format_doc(doc: Document) -> str:
"""Format a single document as XML.
Args:
doc (Document): The document to format.
Returns:
str: The formatted document as an XML string.
"""
metadata = doc.metadata or {}
meta = "".join(f" {k}={v!r}" for k, v in metadata.items())
if meta:
meta = f" {meta}"
return f"<document{meta}>\n{doc.page_content}\n</document>"
def format_docs(docs: Optional[list[Document]]) -> str:
"""Format a list of documents as XML.
This function takes a list of Document objects and formats them into a single XML string.
Args:
docs (Optional[list[Document]]): A list of Document objects to format, or None.
Returns:
str: A string containing the formatted documents in XML format.
Examples:
>>> docs = [Document(page_content="Hello"), Document(page_content="World")]
>>> print(format_docs(docs))
<documents>
<document>
Hello
</document>
<document>
World
</document>
</documents>
>>> print(format_docs(None))
<documents></documents>
"""
if not docs:
return "<documents></documents>"
formatted = "\n".join(_format_doc(doc) for doc in docs)
return f"""<documents>
{formatted}
</documents>"""
def load_chat_model(fully_specified_name: str) -> BaseChatModel:
"""Load a chat model from a fully specified name.
Args:
fully_specified_name (str): String in the format 'provider/model'.
"""
if "/" in fully_specified_name:
provider, model = fully_specified_name.split("/", maxsplit=1)
else:
provider = ""
model = fully_specified_name
model_kwargs = {"temperature": 0}
if provider == "google_genai":
model_kwargs["convert_system_message_to_human"] = True
return init_chat_model(model, model_provider=provider, **model_kwargs)
def reduce_docs(
existing: Optional[list[Document]],
new: Union[
list[Document],
list[dict[str, Any]],
list[str],
str,
],
) -> list[Document]:
"""Reduce and process documents based on the input type.
This function handles various input types and converts them into a sequence of Document objects.
It also combines existing documents with the new one based on the document ID.
Args:
existing (Optional[Sequence[Document]]): The existing docs in the state, if any.
new (Union[Sequence[Document], Sequence[dict[str, Any]], Sequence[str], str, Literal["delete"]]):
The new input to process. Can be a sequence of Documents, dictionaries, strings, or a single string.
"""
existing_list = list(existing) if existing else []
if isinstance(new, str):
return existing_list + [
Document(page_content=new, metadata={"uuid": str(uuid.uuid4())})
]
new_list = []
if isinstance(new, list):
existing_ids = set(doc.metadata.get("uuid") for doc in existing_list)
for item in new:
if isinstance(item, str):
item_id = str(uuid.uuid4())
new_list.append(Document(page_content=item, metadata={"uuid": item_id}))
existing_ids.add(item_id)
elif isinstance(item, dict):
metadata = item.get("metadata", {})
item_id = metadata.get("uuid", str(uuid.uuid4()))
if item_id not in existing_ids:
new_list.append(
Document(**item, metadata={**metadata, "uuid": item_id})
)
existing_ids.add(item_id)
elif isinstance(item, Document):
item_id = item.metadata.get("uuid")
if item_id is None:
item_id = str(uuid.uuid4())
new_item = item.copy(deep=True)
new_item.metadata["uuid"] = item_id
else:
new_item = item
if item_id not in existing_ids:
new_list.append(new_item)
existing_ids.add(item_id)
return existing_list + new_list