docmesh-kbms 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kyundae-kim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: docmesh-kbms
3
+ Version: 0.1.0
4
+ Summary: Document knowledge management system that extracts, chunks, and embeds documents for semantic search with dms-core, Ollama, and Milvus
5
+ Requires-Python: >=3.11
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: aiosqlite>=0.22.1
9
+ Requires-Dist: dms-core>=0.11.0
10
+ Requires-Dist: ollama>=0.6.2
11
+ Requires-Dist: psycopg[binary]>=3.2.3
12
+ Requires-Dist: pymilvus[milvus-lite]>=3.0.1
13
+ Requires-Dist: sqlalchemy>=2.0.52
14
+ Dynamic: license-file
15
+
16
+ # docmesh-kbms
17
+
18
+ 문서 원본과 메타데이터는 `dms-core`가 관리하고, 이 프로젝트는 문서 내용을
19
+ 추출·chunking·embedding하여 Milvus에 저장하는 지식 저장 관리 시스템이다.
20
+
21
+ 외부 공개 진입점은 `kbms.KnowledgeManagement` 하나다.
22
+
23
+ ## 계층
24
+
25
+ - Domain: Python
26
+ - Document management: dms-core
27
+ - ORM/RDB: SQLAlchemy with SQLite or PostgreSQL
28
+ - Vector store: Milvus
29
+ - Embedding provider: Ollama
30
+
31
+ `KnowledgeManagement`의 문서 작업은 모두 async API이며 `await`로 호출한다.
32
+ `upload_document()`은 dms-core에 원본 문서와 메타데이터를 저장한 뒤,
33
+ 텍스트 문서만 추출·chunking하여 Ollama/Milvus로 지식화한다. SQLAlchemy engine과
34
+ dms-core, Ollama, Milvus client의 생성·종료 및 commit/rollback은 host가 맡는다.
35
+ 비동기 경로를 사용하려면 `AsyncEngine`(`sqlite+aiosqlite` 또는 async PostgreSQL),
36
+ Ollama `AsyncClient`, pymilvus `AsyncMilvusClient`를 주입한다. 이 경우
37
+ dms-core의 `AsyncDocumentManagementSDK`와 async SQLAlchemy/Milvus 호출을 사용하며,
38
+ 동기 클라이언트를 주입하면 기존 호환 경로를 사용한다.
39
+ host 권한 정책은 생성자에 `access_policy`로 주입하고, 각 문서 작업에는 dms-core의
40
+ `AccessContext`를 전달해 사용자·그룹 권한을 적용한다.
41
+
42
+ ## 검증
43
+
44
+ ```bash
45
+ uv run pytest -q
46
+ uv run ruff check kbms test_kbms
47
+ ```
48
+
49
+ SQLite memory/disk와 Milvus local 검사는 항상 실행된다. PostgreSQL, Milvus server,
50
+ Ollama 연결 검사는
51
+ 다음 환경변수가 설정된 경우 실행된다.
52
+
53
+ ```bash
54
+ export KBMS_POSTGRES_URL='postgresql+psycopg://docmesh:postgres@postgres:5432/kbms'
55
+ export KBMS_MILVUS_URI='http://milvus:19530'
56
+ export KBMS_OLLAMA_HOST='http://192.168.219.106:11434'
57
+ export KBMS_OLLAMA_EMBEDDING_MODEL='bge-m3'
58
+ export KBMS_OLLAMA_GENERATION_MODEL='llama3.2'
59
+ uv run pytest -q -m integration
60
+ ```
61
+
62
+ 실환경 전체 흐름(DMS + MinIO + PostgreSQL + Ollama + Milvus)은 다음 테스트가
63
+ 검증한다. MinIO 설정을 생략하면 devcontainer 기본값을 사용한다.
64
+
65
+ ```bash
66
+ export KBMS_MINIO_ENDPOINT='milvus-minio:9000'
67
+ export KBMS_MINIO_ACCESS_KEY='minioadmin'
68
+ export KBMS_MINIO_SECRET_KEY='minioadmin'
69
+ export KBMS_MINIO_BUCKET='kbms-e2e'
70
+ uv run pytest -q -m real_integration test_kbms/test_real_integration.py
71
+ ```
@@ -0,0 +1,56 @@
1
+ # docmesh-kbms
2
+
3
+ 문서 원본과 메타데이터는 `dms-core`가 관리하고, 이 프로젝트는 문서 내용을
4
+ 추출·chunking·embedding하여 Milvus에 저장하는 지식 저장 관리 시스템이다.
5
+
6
+ 외부 공개 진입점은 `kbms.KnowledgeManagement` 하나다.
7
+
8
+ ## 계층
9
+
10
+ - Domain: Python
11
+ - Document management: dms-core
12
+ - ORM/RDB: SQLAlchemy with SQLite or PostgreSQL
13
+ - Vector store: Milvus
14
+ - Embedding provider: Ollama
15
+
16
+ `KnowledgeManagement`의 문서 작업은 모두 async API이며 `await`로 호출한다.
17
+ `upload_document()`은 dms-core에 원본 문서와 메타데이터를 저장한 뒤,
18
+ 텍스트 문서만 추출·chunking하여 Ollama/Milvus로 지식화한다. SQLAlchemy engine과
19
+ dms-core, Ollama, Milvus client의 생성·종료 및 commit/rollback은 host가 맡는다.
20
+ 비동기 경로를 사용하려면 `AsyncEngine`(`sqlite+aiosqlite` 또는 async PostgreSQL),
21
+ Ollama `AsyncClient`, pymilvus `AsyncMilvusClient`를 주입한다. 이 경우
22
+ dms-core의 `AsyncDocumentManagementSDK`와 async SQLAlchemy/Milvus 호출을 사용하며,
23
+ 동기 클라이언트를 주입하면 기존 호환 경로를 사용한다.
24
+ host 권한 정책은 생성자에 `access_policy`로 주입하고, 각 문서 작업에는 dms-core의
25
+ `AccessContext`를 전달해 사용자·그룹 권한을 적용한다.
26
+
27
+ ## 검증
28
+
29
+ ```bash
30
+ uv run pytest -q
31
+ uv run ruff check kbms test_kbms
32
+ ```
33
+
34
+ SQLite memory/disk와 Milvus local 검사는 항상 실행된다. PostgreSQL, Milvus server,
35
+ Ollama 연결 검사는
36
+ 다음 환경변수가 설정된 경우 실행된다.
37
+
38
+ ```bash
39
+ export KBMS_POSTGRES_URL='postgresql+psycopg://docmesh:postgres@postgres:5432/kbms'
40
+ export KBMS_MILVUS_URI='http://milvus:19530'
41
+ export KBMS_OLLAMA_HOST='http://192.168.219.106:11434'
42
+ export KBMS_OLLAMA_EMBEDDING_MODEL='bge-m3'
43
+ export KBMS_OLLAMA_GENERATION_MODEL='llama3.2'
44
+ uv run pytest -q -m integration
45
+ ```
46
+
47
+ 실환경 전체 흐름(DMS + MinIO + PostgreSQL + Ollama + Milvus)은 다음 테스트가
48
+ 검증한다. MinIO 설정을 생략하면 devcontainer 기본값을 사용한다.
49
+
50
+ ```bash
51
+ export KBMS_MINIO_ENDPOINT='milvus-minio:9000'
52
+ export KBMS_MINIO_ACCESS_KEY='minioadmin'
53
+ export KBMS_MINIO_SECRET_KEY='minioadmin'
54
+ export KBMS_MINIO_BUCKET='kbms-e2e'
55
+ uv run pytest -q -m real_integration test_kbms/test_real_integration.py
56
+ ```
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: docmesh-kbms
3
+ Version: 0.1.0
4
+ Summary: Document knowledge management system that extracts, chunks, and embeds documents for semantic search with dms-core, Ollama, and Milvus
5
+ Requires-Python: >=3.11
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: aiosqlite>=0.22.1
9
+ Requires-Dist: dms-core>=0.11.0
10
+ Requires-Dist: ollama>=0.6.2
11
+ Requires-Dist: psycopg[binary]>=3.2.3
12
+ Requires-Dist: pymilvus[milvus-lite]>=3.0.1
13
+ Requires-Dist: sqlalchemy>=2.0.52
14
+ Dynamic: license-file
15
+
16
+ # docmesh-kbms
17
+
18
+ 문서 원본과 메타데이터는 `dms-core`가 관리하고, 이 프로젝트는 문서 내용을
19
+ 추출·chunking·embedding하여 Milvus에 저장하는 지식 저장 관리 시스템이다.
20
+
21
+ 외부 공개 진입점은 `kbms.KnowledgeManagement` 하나다.
22
+
23
+ ## 계층
24
+
25
+ - Domain: Python
26
+ - Document management: dms-core
27
+ - ORM/RDB: SQLAlchemy with SQLite or PostgreSQL
28
+ - Vector store: Milvus
29
+ - Embedding provider: Ollama
30
+
31
+ `KnowledgeManagement`의 문서 작업은 모두 async API이며 `await`로 호출한다.
32
+ `upload_document()`은 dms-core에 원본 문서와 메타데이터를 저장한 뒤,
33
+ 텍스트 문서만 추출·chunking하여 Ollama/Milvus로 지식화한다. SQLAlchemy engine과
34
+ dms-core, Ollama, Milvus client의 생성·종료 및 commit/rollback은 host가 맡는다.
35
+ 비동기 경로를 사용하려면 `AsyncEngine`(`sqlite+aiosqlite` 또는 async PostgreSQL),
36
+ Ollama `AsyncClient`, pymilvus `AsyncMilvusClient`를 주입한다. 이 경우
37
+ dms-core의 `AsyncDocumentManagementSDK`와 async SQLAlchemy/Milvus 호출을 사용하며,
38
+ 동기 클라이언트를 주입하면 기존 호환 경로를 사용한다.
39
+ host 권한 정책은 생성자에 `access_policy`로 주입하고, 각 문서 작업에는 dms-core의
40
+ `AccessContext`를 전달해 사용자·그룹 권한을 적용한다.
41
+
42
+ ## 검증
43
+
44
+ ```bash
45
+ uv run pytest -q
46
+ uv run ruff check kbms test_kbms
47
+ ```
48
+
49
+ SQLite memory/disk와 Milvus local 검사는 항상 실행된다. PostgreSQL, Milvus server,
50
+ Ollama 연결 검사는
51
+ 다음 환경변수가 설정된 경우 실행된다.
52
+
53
+ ```bash
54
+ export KBMS_POSTGRES_URL='postgresql+psycopg://docmesh:postgres@postgres:5432/kbms'
55
+ export KBMS_MILVUS_URI='http://milvus:19530'
56
+ export KBMS_OLLAMA_HOST='http://192.168.219.106:11434'
57
+ export KBMS_OLLAMA_EMBEDDING_MODEL='bge-m3'
58
+ export KBMS_OLLAMA_GENERATION_MODEL='llama3.2'
59
+ uv run pytest -q -m integration
60
+ ```
61
+
62
+ 실환경 전체 흐름(DMS + MinIO + PostgreSQL + Ollama + Milvus)은 다음 테스트가
63
+ 검증한다. MinIO 설정을 생략하면 devcontainer 기본값을 사용한다.
64
+
65
+ ```bash
66
+ export KBMS_MINIO_ENDPOINT='milvus-minio:9000'
67
+ export KBMS_MINIO_ACCESS_KEY='minioadmin'
68
+ export KBMS_MINIO_SECRET_KEY='minioadmin'
69
+ export KBMS_MINIO_BUCKET='kbms-e2e'
70
+ uv run pytest -q -m real_integration test_kbms/test_real_integration.py
71
+ ```
@@ -0,0 +1,19 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ docmesh_kbms.egg-info/PKG-INFO
5
+ docmesh_kbms.egg-info/SOURCES.txt
6
+ docmesh_kbms.egg-info/dependency_links.txt
7
+ docmesh_kbms.egg-info/requires.txt
8
+ docmesh_kbms.egg-info/top_level.txt
9
+ kbms/__init__.py
10
+ kbms/facade.py
11
+ kbms/dms/__init__.py
12
+ kbms/dms/dms_core.py
13
+ kbms/dms/dto.py
14
+ kbms/dms/embedding.py
15
+ kbms/dms/ingestion.py
16
+ kbms/dms/knowledge.py
17
+ kbms/dms/pipeline.py
18
+ kbms/dms/retrieval.py
19
+ kbms/dms/vectors.py
@@ -0,0 +1,6 @@
1
+ aiosqlite>=0.22.1
2
+ dms-core>=0.11.0
3
+ ollama>=0.6.2
4
+ psycopg[binary]>=3.2.3
5
+ pymilvus[milvus-lite]>=3.0.1
6
+ sqlalchemy>=2.0.52
@@ -0,0 +1,4 @@
1
+
2
+ from .facade import KnowledgeManagement
3
+
4
+ __all__ = ["KnowledgeManagement"]
@@ -0,0 +1,40 @@
1
+ """Document management and knowledgeization primitives."""
2
+
3
+ from .dms_core import DmsCoreClient, DmsCoreDocumentManager
4
+ from .dto import KnowledgeDocument, KnowledgeDocumentPage
5
+ from .embedding import OllamaEmbeddingProvider
6
+ from .ingestion import DocumentIndexer, DocumentIngestionService
7
+ from .knowledge import (
8
+ EmbeddingProvider,
9
+ KnowledgeIndexer,
10
+ TextChunk,
11
+ TextChunker,
12
+ VectorStore,
13
+ )
14
+ from .pipeline import PipelineBase, PipelineState, PipelineStateRepository
15
+ from .retrieval import KnowledgeSearchService, SearchHit
16
+ from .vectors import MilvusVectorStore
17
+
18
+ __all__ = [
19
+
20
+ "DmsCoreClient",
21
+ "DmsCoreDocumentManager",
22
+
23
+ "DocumentIndexer",
24
+ "DocumentIngestionService",
25
+
26
+ "EmbeddingProvider",
27
+ "KnowledgeDocument",
28
+ "KnowledgeDocumentPage",
29
+ "KnowledgeIndexer",
30
+ "KnowledgeSearchService",
31
+ "MilvusVectorStore",
32
+ "OllamaEmbeddingProvider",
33
+ "PipelineBase",
34
+ "PipelineState",
35
+ "PipelineStateRepository",
36
+ "SearchHit",
37
+ "TextChunk",
38
+ "TextChunker",
39
+ "VectorStore",
40
+ ]
@@ -0,0 +1,225 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ from typing import Protocol
5
+
6
+ from dms import (
7
+ AccessContext,
8
+ DocumentContent,
9
+ DocumentManagementClient,
10
+ DocumentPage,
11
+ DocumentPartition,
12
+ PublicDocumentMetadata,
13
+ UploadDocumentRequest,
14
+ UploadDocumentResult,
15
+ )
16
+
17
+
18
+ class DmsCoreClient(Protocol):
19
+ def list_documents(
20
+ self,
21
+ *,
22
+ partition: DocumentPartition,
23
+ cursor: str | None = None,
24
+ limit: int = 100,
25
+ status: object | None = None,
26
+ access_context: AccessContext | None = None,
27
+ ) -> DocumentPage: ...
28
+
29
+ def get_document_metadata(
30
+ self,
31
+ document_id: str,
32
+ *,
33
+ partition: DocumentPartition,
34
+ access_context: AccessContext | None = None,
35
+ ) -> PublicDocumentMetadata: ...
36
+
37
+ def upload_document(
38
+ self,
39
+ request: UploadDocumentRequest,
40
+ *,
41
+ partition: DocumentPartition,
42
+ access_context: AccessContext | None = None,
43
+ ) -> UploadDocumentResult: ...
44
+
45
+ def get_document_content(
46
+ self,
47
+ document_id: str,
48
+ *,
49
+ partition: DocumentPartition,
50
+ access_context: AccessContext | None = None,
51
+ ) -> DocumentContent: ...
52
+
53
+ def delete_document(
54
+ self,
55
+ document_id: str,
56
+ *,
57
+ partition: DocumentPartition,
58
+ hard_delete: bool = False,
59
+ access_context: AccessContext | None = None,
60
+ ) -> object: ...
61
+
62
+
63
+ class DmsCoreDocumentManager:
64
+ """Document-management boundary backed by the dms-core SDK."""
65
+
66
+ def __init__(self, client: DmsCoreClient | DocumentManagementClient) -> None:
67
+ self.client = client
68
+
69
+ def upload(
70
+ self,
71
+ *,
72
+ content: bytes,
73
+ filename: str,
74
+ content_type: str,
75
+ partition: DocumentPartition,
76
+ document_id: str | None = None,
77
+ created_by: str | None = None,
78
+ metadata: dict[str, object] | None = None,
79
+ access_context: AccessContext | None = None,
80
+ ) -> UploadDocumentResult:
81
+ if not content:
82
+ raise ValueError("content must not be empty")
83
+ if not filename.strip():
84
+ raise ValueError("filename must not be blank")
85
+ if not content_type.strip():
86
+ raise ValueError("content_type must not be blank")
87
+
88
+ request = UploadDocumentRequest(
89
+ content=content,
90
+ filename=filename,
91
+ content_type=content_type,
92
+ document_id=document_id,
93
+ created_by=created_by,
94
+ metadata=metadata,
95
+ checksum=hashlib.sha256(content).hexdigest(),
96
+ )
97
+ return self.client.upload_document(
98
+ request, partition=partition, access_context=access_context
99
+ )
100
+
101
+ def list(
102
+ self,
103
+ *,
104
+ partition: DocumentPartition,
105
+ cursor: str | None = None,
106
+ limit: int = 100,
107
+ access_context: AccessContext | None = None,
108
+ ) -> DocumentPage:
109
+ if limit <= 0:
110
+ raise ValueError("limit must be positive")
111
+ return self.client.list_documents(
112
+ partition=partition,
113
+ cursor=cursor,
114
+ limit=limit,
115
+ access_context=access_context,
116
+ )
117
+
118
+ def metadata(
119
+ self,
120
+ document_id: str,
121
+ *,
122
+ partition: DocumentPartition,
123
+ access_context: AccessContext | None = None,
124
+ ) -> PublicDocumentMetadata:
125
+ if not document_id.strip():
126
+ raise ValueError("document_id must not be blank")
127
+ return self.client.get_document_metadata(
128
+ document_id, partition=partition, access_context=access_context
129
+ )
130
+
131
+ def read(
132
+ self,
133
+ document_id: str,
134
+ *,
135
+ partition: DocumentPartition,
136
+ access_context: AccessContext | None = None,
137
+ ) -> DocumentContent:
138
+ if not document_id.strip():
139
+ raise ValueError("document_id must not be blank")
140
+ return self.client.get_document_content(
141
+ document_id, partition=partition, access_context=access_context
142
+ )
143
+
144
+ def delete(
145
+ self,
146
+ document_id: str,
147
+ *,
148
+ partition: DocumentPartition,
149
+ hard_delete: bool = False,
150
+ access_context: AccessContext | None = None,
151
+ ) -> object:
152
+ if not document_id.strip():
153
+ raise ValueError("document_id must not be blank")
154
+ return self.client.delete_document(
155
+ document_id,
156
+ partition=partition,
157
+ hard_delete=hard_delete,
158
+ access_context=access_context,
159
+ )
160
+
161
+ async def aupload(self, **kwargs: object) -> UploadDocumentResult:
162
+ self._validate_upload_kwargs(kwargs)
163
+ request = UploadDocumentRequest(
164
+ content=kwargs["content"],
165
+ filename=kwargs["filename"],
166
+ content_type=kwargs["content_type"],
167
+ document_id=kwargs.get("document_id"),
168
+ created_by=kwargs.get("created_by"),
169
+ metadata=kwargs.get("metadata"),
170
+ checksum=hashlib.sha256(kwargs["content"]).hexdigest(),
171
+ )
172
+ return await self.client.upload_document(
173
+ request,
174
+ partition=kwargs["partition"],
175
+ access_context=kwargs.get("access_context"),
176
+ )
177
+
178
+ async def alist(self, **kwargs: object) -> DocumentPage:
179
+ limit = kwargs.get("limit", 100)
180
+ if limit <= 0:
181
+ raise ValueError("limit must be positive")
182
+ return await self.client.list_documents(
183
+ partition=kwargs["partition"],
184
+ cursor=kwargs.get("cursor"),
185
+ limit=limit,
186
+ access_context=kwargs.get("access_context"),
187
+ )
188
+
189
+ async def ametadata(self, document_id: str, **kwargs: object) -> PublicDocumentMetadata:
190
+ if not document_id.strip():
191
+ raise ValueError("document_id must not be blank")
192
+ return await self.client.get_document_metadata(
193
+ document_id,
194
+ partition=kwargs["partition"],
195
+ access_context=kwargs.get("access_context"),
196
+ )
197
+
198
+ async def aread(self, document_id: str, **kwargs: object) -> DocumentContent:
199
+ if not document_id.strip():
200
+ raise ValueError("document_id must not be blank")
201
+ return await self.client.get_document_content(
202
+ document_id,
203
+ partition=kwargs["partition"],
204
+ access_context=kwargs.get("access_context"),
205
+ )
206
+
207
+ async def adelete(self, document_id: str, **kwargs: object) -> object:
208
+ if not document_id.strip():
209
+ raise ValueError("document_id must not be blank")
210
+ return await self.client.delete_document(
211
+ document_id,
212
+ partition=kwargs["partition"],
213
+ hard_delete=kwargs.get("hard_delete", False),
214
+ access_context=kwargs.get("access_context"),
215
+ )
216
+
217
+ @staticmethod
218
+ def _validate_upload_kwargs(kwargs: dict[str, object]) -> None:
219
+ content = kwargs["content"]
220
+ if not content:
221
+ raise ValueError("content must not be empty")
222
+ if not kwargs["filename"].strip():
223
+ raise ValueError("filename must not be blank")
224
+ if not kwargs["content_type"].strip():
225
+ raise ValueError("content_type must not be blank")
@@ -0,0 +1,30 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from datetime import datetime
5
+ from typing import Any
6
+
7
+
8
+ @dataclass(frozen=True, slots=True)
9
+ class KnowledgeDocument:
10
+ """KMS document projection that hides dms-core-specific types."""
11
+
12
+ document_id: str
13
+ filename: str
14
+ content_type: str
15
+ file_size: int
16
+ status: str
17
+ created_at: datetime
18
+ updated_at: datetime
19
+ partition_kind: str
20
+ partition_id: str
21
+ checksum: str | None
22
+ created_by: str | None
23
+ metadata: dict[str, Any]
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class KnowledgeDocumentPage:
28
+ items: list[KnowledgeDocument]
29
+ next_cursor: str | None
30
+ has_more: bool
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Any
5
+
6
+
7
+ class OllamaEmbeddingProvider:
8
+ """Small adapter around Ollama's synchronous ``embed`` API."""
9
+
10
+ def __init__(self, client: Any, model: str) -> None:
11
+ if not isinstance(model, str) or not model.strip():
12
+ raise ValueError("model must not be blank")
13
+ self.client = client
14
+ self.model = model
15
+
16
+ def embed(self, text: str) -> Sequence[float]:
17
+ if not isinstance(text, str) or not text.strip():
18
+ raise ValueError("text must not be blank")
19
+ response = self.client.embed(model=self.model, input=text)
20
+ embeddings = response.get("embeddings") if isinstance(response, dict) else getattr(response, "embeddings", None)
21
+ if not embeddings or not isinstance(embeddings, (list, tuple)):
22
+ raise ValueError("invalid embedding response")
23
+ vector = embeddings[0] if embeddings and isinstance(embeddings[0], (list, tuple)) else embeddings
24
+ if not vector:
25
+ raise ValueError("invalid embedding response")
26
+ return vector
27
+
28
+ async def aembed(self, text: str) -> Sequence[float]:
29
+ if not isinstance(text, str) or not text.strip():
30
+ raise ValueError("text must not be blank")
31
+ response = await self.client.embed(model=self.model, input=text)
32
+ return self._parse_response(response)
33
+
34
+ @staticmethod
35
+ def _parse_response(response: Any) -> Sequence[float]:
36
+ embeddings = response.get("embeddings") if isinstance(response, dict) else getattr(response, "embeddings", None)
37
+ if not embeddings or not isinstance(embeddings, (list, tuple)):
38
+ raise ValueError("invalid embedding response")
39
+ vector = embeddings[0] if isinstance(embeddings[0], (list, tuple)) else embeddings
40
+ if not vector:
41
+ raise ValueError("invalid embedding response")
42
+ return vector