Repository navigation
Expand file tree
/
Copy pathdocument_client.py
More file actions
320 lines (280 loc) · 10.2 KB
/
Copy pathdocument_client.py
File metadata and controls
320 lines (280 loc) · 10.2 KB
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
"""Document Client for RoboSystems API
Upload, search, list, and delete text documents indexed in OpenSearch.
Documents are sectioned on markdown headings, embedded for semantic search,
and searchable alongside structured graph data.
"""
from http import HTTPStatus
from pathlib import Path
from typing import Any, Dict, List, Optional
from ..api.documents.delete_document import sync_detailed as delete_document
from ..api.documents.list_documents import sync_detailed as list_documents
from ..api.documents.upload_document import sync_detailed as upload_document
from ..api.documents.upload_documents_bulk import sync_detailed as upload_documents_bulk
from ..api.search.get_document_section import sync_detailed as get_document_section
from ..api.search.search_documents import sync_detailed as search_documents
from ..client import AuthenticatedClient
from ..models.document_list_response import DocumentListResponse
from ..models.document_section import DocumentSection
from ..models.bulk_document_upload_request import BulkDocumentUploadRequest
from ..models.bulk_document_upload_response import BulkDocumentUploadResponse
from ..models.document_upload_request import DocumentUploadRequest
from ..models.document_upload_response import DocumentUploadResponse
from ..models.search_request import SearchRequest
from ..models.search_response import SearchResponse
from ..types import UNSET
class DocumentClient:
"""Client for document upload, search, and management."""
def __init__(self, config: Dict[str, Any]):
self.config = config
self.base_url = config["base_url"]
self.headers = config.get("headers", {})
self.token = config.get("token")
self.timeout = config.get("timeout", 60)
def _get_client(self) -> AuthenticatedClient:
if not self.token:
raise Exception("No API key provided. Set X-API-Key in headers.")
return AuthenticatedClient(
base_url=self.base_url,
token=self.token,
prefix="",
auth_header_name="X-API-Key",
headers=self.headers,
)
def upload(
self,
graph_id: str,
title: str,
content: str,
tags: Optional[List[str]] = None,
folder: Optional[str] = None,
external_id: Optional[str] = None,
) -> DocumentUploadResponse:
"""Upload a markdown document for text indexing.
The document is sectioned on headings, embedded, and indexed
into OpenSearch for full-text and semantic search.
Args:
graph_id: Target graph ID.
title: Document title.
content: Markdown content (may include YAML frontmatter).
tags: Optional tags for filtering.
folder: Optional folder/category.
external_id: Optional external ID for upsert behavior.
Returns:
DocumentUploadResponse with section IDs and counts.
"""
body = DocumentUploadRequest(
title=title,
content=content,
tags=tags if tags is not None else UNSET,
folder=folder if folder is not None else UNSET,
external_id=external_id if external_id is not None else UNSET,
)
client = self._get_client()
response = upload_document(graph_id=graph_id, client=client, body=body)
if response.status_code != HTTPStatus.OK:
raise Exception(
f"Document upload failed ({response.status_code}): {response.content.decode()}"
)
return response.parsed
def upload_file(
self,
graph_id: str,
file_path: str | Path,
title: Optional[str] = None,
tags: Optional[List[str]] = None,
folder: Optional[str] = None,
external_id: Optional[str] = None,
) -> DocumentUploadResponse:
"""Upload a markdown file by path.
Reads the file, optionally extracts title from filename,
and uploads via the document API.
Args:
graph_id: Target graph ID.
file_path: Path to markdown file.
title: Document title (defaults to filename).
tags: Optional tags.
folder: Optional folder.
external_id: Optional external ID.
"""
path = Path(file_path)
content = path.read_text()
if title is None:
title = path.stem.replace("-", " ").replace("_", " ").title()
return self.upload(
graph_id=graph_id,
title=title,
content=content,
tags=tags,
folder=folder,
external_id=external_id,
)
def upload_directory(
self,
graph_id: str,
directory: str | Path,
pattern: str = "*.md",
folder: Optional[str] = None,
) -> List[DocumentUploadResponse]:
"""Upload all markdown files from a directory.
Args:
graph_id: Target graph ID.
directory: Path to directory containing markdown files.
pattern: Glob pattern for file matching (default: *.md).
folder: Optional folder to apply to all documents.
Returns:
List of upload results, one per file.
"""
dir_path = Path(directory)
results = []
for md_file in sorted(dir_path.glob(pattern)):
result = self.upload_file(
graph_id=graph_id,
file_path=md_file,
folder=folder,
)
results.append(result)
return results
def upload_bulk(
self,
graph_id: str,
documents: List[Dict[str, Any]],
) -> BulkDocumentUploadResponse:
"""Upload multiple markdown documents (max 50 per request).
Args:
graph_id: Target graph ID.
documents: List of dicts with keys: title, content, and
optionally tags, folder, external_id.
Returns:
BulkDocumentUploadResponse with per-document results.
"""
items = []
for doc in documents:
items.append(
DocumentUploadRequest(
title=doc["title"],
content=doc["content"],
tags=doc.get("tags", UNSET),
folder=doc.get("folder", UNSET),
external_id=doc.get("external_id", UNSET),
)
)
body = BulkDocumentUploadRequest(documents=items)
client = self._get_client()
response = upload_documents_bulk(graph_id=graph_id, client=client, body=body)
if response.status_code != HTTPStatus.OK:
raise Exception(
f"Bulk upload failed ({response.status_code}): {response.content.decode()}"
)
return response.parsed
def search(
self,
graph_id: str,
query: str,
source_type: Optional[str] = None,
entity: Optional[str] = None,
form_type: Optional[str] = None,
section: Optional[str] = None,
element: Optional[str] = None,
fiscal_year: Optional[int] = None,
date_from: Optional[str] = None,
date_to: Optional[str] = None,
size: int = 10,
) -> SearchResponse:
"""Search documents with hybrid (BM25 + KNN) search.
Args:
graph_id: Target graph ID.
query: Search query string.
source_type: Filter by source type (xbrl_textblock, narrative_section,
ixbrl_disclosure, uploaded_doc, memory).
entity: Filter by entity ticker/CIK/name.
form_type: Filter by SEC form type (10-K, 10-Q).
section: Filter by section ID (item_1, item_1a, item_7, etc.).
element: Filter by XBRL element qname (e.g., us-gaap:Goodwill).
fiscal_year: Filter by fiscal year.
date_from: Filter filings on or after date (YYYY-MM-DD).
date_to: Filter filings on or before date (YYYY-MM-DD).
size: Max results to return.
Returns:
SearchResponse with ranked hits.
"""
body = SearchRequest(
query=query,
source_type=source_type if source_type is not None else UNSET,
entity=entity if entity is not None else UNSET,
form_type=form_type if form_type is not None else UNSET,
section=section if section is not None else UNSET,
element=element if element is not None else UNSET,
fiscal_year=fiscal_year if fiscal_year is not None else UNSET,
date_from=date_from if date_from is not None else UNSET,
date_to=date_to if date_to is not None else UNSET,
size=size,
)
client = self._get_client()
response = search_documents(graph_id=graph_id, client=client, body=body)
if response.status_code != HTTPStatus.OK:
raise Exception(
f"Document search failed ({response.status_code}): {response.content.decode()}"
)
return response.parsed
def get_section(self, graph_id: str, document_id: str) -> Optional[DocumentSection]:
"""Retrieve the full text of a document section by ID.
Args:
graph_id: Target graph ID.
document_id: Document section ID.
Returns:
DocumentSection with full content and metadata, or None if not found.
"""
client = self._get_client()
response = get_document_section(
graph_id=graph_id, document_id=document_id, client=client
)
if response.status_code == HTTPStatus.NOT_FOUND:
return None
if response.status_code != HTTPStatus.OK:
raise Exception(
f"Get section failed ({response.status_code}): {response.content.decode()}"
)
return response.parsed
def list(
self, graph_id: str, source_type: Optional[str] = None
) -> DocumentListResponse:
"""List indexed documents for a graph.
Args:
graph_id: Target graph ID.
source_type: Optional filter by source type.
Returns:
DocumentListResponse with document inventory.
"""
client = self._get_client()
response = list_documents(
graph_id=graph_id,
client=client,
source_type=source_type if source_type is not None else UNSET,
)
if response.status_code != HTTPStatus.OK:
raise Exception(
f"List documents failed ({response.status_code}): {response.content.decode()}"
)
return response.parsed
def delete(self, graph_id: str, document_id: str) -> bool:
"""Delete a document and all its sections.
Args:
graph_id: Target graph ID.
document_id: Document ID to delete.
Returns:
True if deleted, False if not found.
"""
client = self._get_client()
response = delete_document(
graph_id=graph_id, document_id=document_id, client=client
)
if response.status_code == HTTPStatus.NO_CONTENT:
return True
if response.status_code == HTTPStatus.NOT_FOUND:
return False
raise Exception(
f"Delete document failed ({response.status_code}): {response.content.decode()}"
)
def close(self):
"""Close the client (no-op, AuthenticatedClient is created per-call)."""
pass