lorebo-sdk 0.1.0__py3-none-any.whl

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.
lorebo_sdk/__init__.py ADDED
File without changes
lorebo_sdk/client.py ADDED
@@ -0,0 +1,119 @@
1
+ from typing import Any, Self
2
+
3
+ from fastmcp import Client
4
+ from fastmcp.exceptions import ToolError
5
+ from pydantic import BaseModel, ValidationError
6
+ from pydantic_ai.models import Model, infer_model
7
+
8
+ from lorebo_sdk.errors import LockedBaseError, LoreboToolError
9
+ from lorebo_sdk.records import Base, CaptureResult, ExploreResult
10
+ from lorebo_sdk.runs import CaptureReport, ExploreReport, SkillRunner
11
+ from lorebo_sdk.skills import PublishedSkills, Skill, SkillSource
12
+
13
+
14
+ class ListedBase(BaseModel):
15
+ base_ref: str
16
+ label: str
17
+ kind: str
18
+ entry_id: str
19
+
20
+
21
+ class BaseList(BaseModel):
22
+ items: list[ListedBase]
23
+
24
+
25
+ class CreatedBase(BaseModel):
26
+ entry_id: str
27
+
28
+
29
+ class Lorebo:
30
+ def __init__(
31
+ self,
32
+ mcp_client: Client[Any],
33
+ model: Model,
34
+ skills: SkillSource,
35
+ base_ref: str | None,
36
+ ) -> None:
37
+ self._mcp_client = mcp_client
38
+ self._base_ref = base_ref
39
+ self._runner = SkillRunner(model, skills, mcp_client, base_ref)
40
+
41
+ @classmethod
42
+ def from_url(
43
+ cls,
44
+ *,
45
+ url: str,
46
+ token: str | None,
47
+ model: Model | str,
48
+ base_ref: str | None,
49
+ ) -> Self:
50
+ return cls(
51
+ mcp_client=Client(url, auth=token),
52
+ model=infer_model(model),
53
+ skills=PublishedSkills(),
54
+ base_ref=base_ref,
55
+ )
56
+
57
+ async def capture(self, prompt: str) -> CaptureResult:
58
+ run = await self._runner.run(Skill.CAPTURE, prompt, CaptureReport)
59
+
60
+ return CaptureResult(
61
+ summary=run.report.summary,
62
+ created=run.pages.created,
63
+ updated=run.pages.updated,
64
+ )
65
+
66
+ async def explore(self, prompt: str) -> ExploreResult:
67
+ run = await self._runner.run(Skill.EXPLORE, prompt, ExploreReport)
68
+
69
+ return ExploreResult(
70
+ answer=run.report.answer,
71
+ sources=run.pages.cited(run.report.source_page_ids),
72
+ )
73
+
74
+ async def list_bases(self) -> list[Base]:
75
+ listed_bases = await self._list_bases()
76
+
77
+ return [
78
+ Base(base_ref=listed.base_ref, label=listed.label, kind=listed.kind)
79
+ for listed in listed_bases
80
+ ]
81
+
82
+ async def create_base(self, label: str, path: str, activate: bool) -> Base:
83
+ if self._base_ref is not None:
84
+ raise LockedBaseError("base_create_base", self._base_ref)
85
+
86
+ created = await self._call_tool(
87
+ "base_create_base",
88
+ {"display_name": label, "path": path, "activate": activate},
89
+ CreatedBase,
90
+ )
91
+ listed_bases = await self._list_bases()
92
+
93
+ for listed in listed_bases:
94
+ if listed.entry_id == created.entry_id:
95
+ return Base(base_ref=listed.base_ref, label=listed.label, kind=listed.kind)
96
+
97
+ raise LoreboToolError("base_create_base", f"base {created.entry_id} is not listed")
98
+
99
+ async def _list_bases(self) -> list[ListedBase]:
100
+ base_list = await self._call_tool("working_base_list_bases", {}, BaseList)
101
+
102
+ return base_list.items
103
+
104
+ async def _call_tool[ResponseT: BaseModel](
105
+ self,
106
+ tool_name: str,
107
+ arguments: dict[str, Any],
108
+ response_type: type[ResponseT],
109
+ ) -> ResponseT:
110
+ try:
111
+ async with self._mcp_client:
112
+ result = await self._mcp_client.call_tool(tool_name, arguments)
113
+ except ToolError as error:
114
+ raise LoreboToolError(tool_name, str(error)) from error
115
+
116
+ try:
117
+ return response_type.model_validate(result.structured_content)
118
+ except ValidationError as error:
119
+ raise LoreboToolError(tool_name, "the response has an unexpected shape") from error
lorebo_sdk/errors.py ADDED
@@ -0,0 +1,29 @@
1
+ class LoreboError(Exception):
2
+ pass
3
+
4
+
5
+ class LockedBaseError(LoreboError):
6
+ def __init__(self, tool_name: str, base_ref: str) -> None:
7
+ self.tool_name = tool_name
8
+ self.base_ref = base_ref
9
+
10
+ super().__init__(f"{tool_name} tried to leave the locked base {base_ref}")
11
+
12
+
13
+ class LoreboToolError(LoreboError):
14
+ def __init__(self, tool_name: str, detail: str) -> None:
15
+ self.tool_name = tool_name
16
+ self.detail = detail
17
+
18
+ super().__init__(f"{tool_name} failed: {detail}")
19
+
20
+
21
+ class SkillPackageError(LoreboError):
22
+ pass
23
+
24
+
25
+ class RunLimitError(LoreboError):
26
+ def __init__(self, request_limit: int) -> None:
27
+ self.request_limit = request_limit
28
+
29
+ super().__init__(f"the run did not finish within {request_limit} model requests")
lorebo_sdk/pages.py ADDED
@@ -0,0 +1,92 @@
1
+ from pydantic import BaseModel, ValidationError
2
+
3
+ from lorebo_sdk.errors import LoreboToolError
4
+ from lorebo_sdk.records import Page
5
+
6
+
7
+ class PageReference(BaseModel):
8
+ id: str
9
+ title: str
10
+
11
+
12
+ class PageItems(BaseModel):
13
+ items: list[PageReference]
14
+
15
+
16
+ class HybridSearchResults(BaseModel):
17
+ results: list[PageReference]
18
+
19
+
20
+ class RelevantSubgraph(BaseModel):
21
+ nodes: list[PageReference]
22
+
23
+
24
+ class RunPages:
25
+ CREATING_TOOLS = frozenset({"create_page"})
26
+ UPDATING_TOOLS = frozenset({"update_page", "replace_in_page"})
27
+ SINGLE_PAGE_TOOLS = frozenset({"get_page"})
28
+ PAGE_ITEMS_TOOLS = frozenset({"get_pages", "list_pages", "search", "find_similar_notes"})
29
+
30
+ def __init__(self) -> None:
31
+ self._created: dict[str, Page] = {}
32
+ self._updated: dict[str, Page] = {}
33
+ self._seen: dict[str, Page] = {}
34
+
35
+ @property
36
+ def created(self) -> list[Page]:
37
+ return list(self._created.values())
38
+
39
+ @property
40
+ def updated(self) -> list[Page]:
41
+ return list(self._updated.values())
42
+
43
+ def cited(self, page_ids: list[str]) -> list[Page]:
44
+ pages: dict[str, Page] = {}
45
+
46
+ for page_id in page_ids:
47
+ page = self._seen.get(page_id)
48
+
49
+ if page is not None:
50
+ pages[page.id] = page
51
+
52
+ return list(pages.values())
53
+
54
+ def record(self, tool_name: str, base_ref: str, payload: object) -> None:
55
+ references = RunPages.page_references(tool_name, payload)
56
+ pages = [
57
+ Page(id=reference.id, title=reference.title, base_ref=base_ref)
58
+ for reference in references
59
+ ]
60
+
61
+ for page in pages:
62
+ self._seen[page.id] = page
63
+
64
+ if tool_name in RunPages.CREATING_TOOLS:
65
+ self._created[page.id] = page
66
+
67
+ if tool_name in RunPages.UPDATING_TOOLS:
68
+ changed_pages = self._created if page.id in self._created else self._updated
69
+ changed_pages[page.id] = page
70
+
71
+ @staticmethod
72
+ def page_references(tool_name: str, payload: object) -> list[PageReference]:
73
+ try:
74
+ if (
75
+ tool_name in RunPages.CREATING_TOOLS
76
+ or tool_name in RunPages.UPDATING_TOOLS
77
+ or tool_name in RunPages.SINGLE_PAGE_TOOLS
78
+ ):
79
+ return [PageReference.model_validate(payload)]
80
+
81
+ if tool_name in RunPages.PAGE_ITEMS_TOOLS:
82
+ return PageItems.model_validate(payload).items
83
+
84
+ if tool_name == "hybrid_search":
85
+ return HybridSearchResults.model_validate(payload).results
86
+
87
+ if tool_name == "get_relevant_subgraph":
88
+ return RelevantSubgraph.model_validate(payload).nodes
89
+ except ValidationError as error:
90
+ raise LoreboToolError(tool_name, "the response does not describe pages") from error
91
+
92
+ return []
lorebo_sdk/py.typed ADDED
File without changes
lorebo_sdk/records.py ADDED
@@ -0,0 +1,32 @@
1
+ from pydantic import BaseModel, ConfigDict
2
+
3
+
4
+ class Page(BaseModel):
5
+ model_config = ConfigDict(frozen=True)
6
+
7
+ id: str
8
+ title: str
9
+ base_ref: str
10
+
11
+
12
+ class Base(BaseModel):
13
+ model_config = ConfigDict(frozen=True)
14
+
15
+ base_ref: str
16
+ label: str
17
+ kind: str
18
+
19
+
20
+ class CaptureResult(BaseModel):
21
+ model_config = ConfigDict(frozen=True)
22
+
23
+ summary: str
24
+ created: list[Page]
25
+ updated: list[Page]
26
+
27
+
28
+ class ExploreResult(BaseModel):
29
+ model_config = ConfigDict(frozen=True)
30
+
31
+ answer: str
32
+ sources: list[Page]
lorebo_sdk/runs.py ADDED
@@ -0,0 +1,164 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any
3
+
4
+ import pydantic_ai
5
+ from fastmcp import Client
6
+ from pydantic import BaseModel, Field
7
+ from pydantic_ai import Agent, RunContext
8
+ from pydantic_ai.exceptions import UsageLimitExceeded
9
+ from pydantic_ai.mcp import CallToolFunc, MCPToolset, ToolResult
10
+ from pydantic_ai.models import Model
11
+ from pydantic_ai.tools import ToolDefinition
12
+ from pydantic_ai.usage import UsageLimits
13
+
14
+ from lorebo_sdk.errors import RunLimitError
15
+ from lorebo_sdk.pages import RunPages
16
+ from lorebo_sdk.skills import Skill, SkillSource
17
+ from lorebo_sdk.tools import SkillToolPolicy
18
+
19
+
20
+ class CaptureReport(BaseModel):
21
+ summary: str = Field(
22
+ description=(
23
+ "One or two plain sentences for the application's user: "
24
+ "what was saved, or why nothing was saved."
25
+ )
26
+ )
27
+
28
+
29
+ class ExploreReport(BaseModel):
30
+ answer: str = Field(
31
+ description="The answer to the prompt in plain text, based on the Lorebo pages read."
32
+ )
33
+ source_page_ids: list[str] = Field(description="IDs of the Lorebo pages the answer relies on.")
34
+
35
+
36
+ class BaseScopedArguments(BaseModel):
37
+ base_ref: str
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class SkillRun[ReportT: BaseModel]:
42
+ report: ReportT
43
+ pages: RunPages
44
+
45
+
46
+ class SkillRunner:
47
+ REQUEST_LIMIT = 24
48
+
49
+ def __init__(
50
+ self,
51
+ model: Model,
52
+ skills: SkillSource,
53
+ mcp_client: Client[Any],
54
+ base_ref: str | None,
55
+ ) -> None:
56
+ self._model = model
57
+ self._skills = skills
58
+ self._mcp_client = mcp_client
59
+ self._base_ref = base_ref
60
+
61
+ pydantic_ai.BANNER_ENABLED = False
62
+
63
+ async def run[ReportT: BaseModel](
64
+ self,
65
+ skill: Skill,
66
+ prompt: str,
67
+ report_type: type[ReportT],
68
+ ) -> SkillRun[ReportT]:
69
+ skill_instructions = await self._skills.instructions(skill)
70
+ policy = SkillToolPolicy(skill, self._base_ref)
71
+ pages = RunPages()
72
+
73
+ async def call_lorebo_tool(
74
+ context: RunContext[None],
75
+ call_tool: CallToolFunc,
76
+ tool_name: str,
77
+ arguments: dict[str, Any],
78
+ ) -> ToolResult:
79
+ prepared_arguments = policy.prepare_arguments(tool_name, arguments)
80
+ result = await call_tool(tool_name, prepared_arguments)
81
+
82
+ if SkillToolPolicy.is_base_scoped(tool_name):
83
+ base_ref = BaseScopedArguments.model_validate(prepared_arguments).base_ref
84
+ pages.record(tool_name, base_ref, result)
85
+
86
+ return result
87
+
88
+ def is_available(context: RunContext[None], tool: ToolDefinition) -> bool:
89
+ return policy.allows(tool.name)
90
+
91
+ toolset: MCPToolset[None] = MCPToolset(
92
+ self._mcp_client,
93
+ process_tool_call=call_lorebo_tool,
94
+ )
95
+ agent = Agent(
96
+ self._model,
97
+ instructions=SkillRunner.instructions(skill, skill_instructions, self._base_ref),
98
+ output_type=report_type,
99
+ deps_type=type(None),
100
+ toolsets=[toolset.filtered(is_available)],
101
+ )
102
+
103
+ try:
104
+ result = await agent.run(
105
+ prompt,
106
+ usage_limits=UsageLimits(request_limit=SkillRunner.REQUEST_LIMIT),
107
+ )
108
+ except UsageLimitExceeded as error:
109
+ raise RunLimitError(SkillRunner.REQUEST_LIMIT) from error
110
+
111
+ return SkillRun(report=result.output, pages=pages)
112
+
113
+ @staticmethod
114
+ def instructions(skill: Skill, skill_instructions: str, base_ref: str | None) -> str:
115
+ if base_ref is not None:
116
+ base_rule = (
117
+ f"This run is locked to the base {base_ref}. "
118
+ "Pass that base_ref on every call that takes one. Other bases are not available."
119
+ )
120
+ elif skill is Skill.CAPTURE:
121
+ base_rule = (
122
+ "No base is preselected. List the bases and choose the one this knowledge "
123
+ "belongs to, or create one when none fits. Pass its base_ref on every call "
124
+ "that takes one."
125
+ )
126
+ else:
127
+ base_rule = (
128
+ "No base is preselected. List the bases and choose the one that holds this "
129
+ "knowledge. Pass its base_ref on every call that takes one."
130
+ )
131
+
132
+ if skill is Skill.CAPTURE:
133
+ final_report_rule = (
134
+ "Its summary is shown to the application's user. State what was saved, or why "
135
+ "nothing was saved."
136
+ )
137
+ else:
138
+ final_report_rule = (
139
+ "Its answer is shown to the application's user. Answer the prompt directly from "
140
+ "the pages you read, and put the IDs of the pages it relies on in "
141
+ "source_page_ids instead of listing sources in the answer."
142
+ )
143
+
144
+ return "\n\n".join(
145
+ [
146
+ skill_instructions,
147
+ "# Lorebo SDK run",
148
+ (
149
+ f"You are running the {skill} skill for an application through the Lorebo "
150
+ "SDK. The run is unattended: nobody can answer questions or confirm steps. "
151
+ "The application's prompt is the whole task and its only source material."
152
+ ),
153
+ base_rule,
154
+ (
155
+ "Governance tools read Lorebo's managed governance base. "
156
+ "They do not change the target base."
157
+ ),
158
+ (
159
+ f"When the work is done, return the final report. {final_report_rule} "
160
+ "Write that text plainly, without Markdown, page IDs, tool names, or a "
161
+ "description of your reasoning and steps."
162
+ ),
163
+ ]
164
+ )
lorebo_sdk/skills.py ADDED
@@ -0,0 +1,101 @@
1
+ import hashlib
2
+ import io
3
+ import zipfile
4
+ from enum import StrEnum
5
+ from typing import Protocol
6
+
7
+ import httpx
8
+
9
+ from lorebo_sdk.errors import SkillPackageError
10
+
11
+
12
+ class Skill(StrEnum):
13
+ CAPTURE = "lorebo-capture"
14
+ EXPLORE = "lorebo-explore"
15
+
16
+
17
+ class SkillSource(Protocol):
18
+ async def instructions(self, skill: Skill) -> str: ...
19
+
20
+
21
+ class PublishedSkills:
22
+ VERSION = "0.4.3"
23
+ DOWNLOAD_URL = "https://downloads.lorebo.com/lorebo/skills/stable"
24
+ DOWNLOAD_TIMEOUT_SECONDS = 30
25
+ DIGESTS = {
26
+ Skill.CAPTURE: "6b3d47ca5ba8f0511fc6b6ce33a22ed34757cd54fec54e06d7f34d3452d5572d",
27
+ Skill.EXPLORE: "2310e6ef43d68e79641c0b32a0f2cefab141e07cdf322d8ded5c52b7d71c215b",
28
+ }
29
+
30
+ def __init__(self) -> None:
31
+ self._instructions: dict[Skill, str] = {}
32
+
33
+ async def instructions(self, skill: Skill) -> str:
34
+ cached = self._instructions.get(skill)
35
+
36
+ if cached is not None:
37
+ return cached
38
+
39
+ package = await self._download(skill)
40
+ digest = hashlib.sha256(package).hexdigest()
41
+
42
+ if digest != PublishedSkills.DIGESTS[skill]:
43
+ raise SkillPackageError(f"{skill} {PublishedSkills.VERSION} does not match its digest")
44
+
45
+ instructions = SkillPackage.read_instructions(package, skill)
46
+ self._instructions[skill] = instructions
47
+
48
+ return instructions
49
+
50
+ async def _download(self, skill: Skill) -> bytes:
51
+ version = PublishedSkills.VERSION
52
+ url = f"{PublishedSkills.DOWNLOAD_URL}/{version}/{skill}-{version}.zip"
53
+
54
+ try:
55
+ async with httpx.AsyncClient(
56
+ follow_redirects=True,
57
+ timeout=PublishedSkills.DOWNLOAD_TIMEOUT_SECONDS,
58
+ ) as client:
59
+ response = await client.get(url)
60
+ response.raise_for_status()
61
+ except httpx.HTTPError as error:
62
+ raise SkillPackageError(f"could not download {url}") from error
63
+
64
+ return response.content
65
+
66
+
67
+ class SkillPackage:
68
+ INSTRUCTIONS_FILE = "SKILL.md"
69
+
70
+ @staticmethod
71
+ def read_instructions(package: bytes, skill: Skill) -> str:
72
+ prefix = f"{skill}/"
73
+
74
+ try:
75
+ archive = zipfile.ZipFile(io.BytesIO(package))
76
+ except zipfile.BadZipFile as error:
77
+ raise SkillPackageError(f"{skill} package is not a zip archive") from error
78
+
79
+ documents: dict[str, str] = {}
80
+
81
+ with archive:
82
+ for entry in archive.infolist():
83
+ if entry.is_dir():
84
+ continue
85
+
86
+ path = entry.filename
87
+
88
+ if not path.startswith(prefix) or ".." in path.split("/") or "\\" in path:
89
+ raise SkillPackageError(f"{skill} package contains an unexpected path: {path}")
90
+
91
+ if path.endswith(".md"):
92
+ documents[path.removeprefix(prefix)] = archive.read(entry).decode("utf-8")
93
+
94
+ skill_document = documents.pop(SkillPackage.INSTRUCTIONS_FILE, None)
95
+
96
+ if skill_document is None:
97
+ raise SkillPackageError(f"{skill} package has no {SkillPackage.INSTRUCTIONS_FILE}")
98
+
99
+ references = [f"# {path}\n\n{text}" for path, text in sorted(documents.items())]
100
+
101
+ return "\n\n".join([skill_document, *references])
lorebo_sdk/tools.py ADDED
@@ -0,0 +1,87 @@
1
+ from typing import Any
2
+
3
+ from lorebo_sdk.errors import LockedBaseError
4
+ from lorebo_sdk.skills import Skill
5
+
6
+
7
+ class SkillToolPolicy:
8
+ GOVERNANCE_TOOLS = frozenset(
9
+ {
10
+ "get_governance_scenario",
11
+ "get_governance_scenarios_for_tool",
12
+ }
13
+ )
14
+ BASE_DISCOVERY_TOOLS = frozenset(
15
+ {
16
+ "working_base_list_bases",
17
+ "working_base_get_current_base",
18
+ }
19
+ )
20
+ BASE_CREATION_TOOLS = frozenset(
21
+ {
22
+ "base_create_base",
23
+ }
24
+ )
25
+ READ_TOOLS = frozenset(
26
+ {
27
+ "get_page",
28
+ "get_pages",
29
+ "list_pages",
30
+ "search",
31
+ "hybrid_search",
32
+ "get_relevant_subgraph",
33
+ "find_similar_notes",
34
+ "get_page_ancestry",
35
+ "get_inline_link",
36
+ "get_graph_counts",
37
+ "search_capability_status",
38
+ "get_note_authoring_preferences",
39
+ }
40
+ )
41
+ WRITE_TOOLS = frozenset(
42
+ {
43
+ "create_page",
44
+ "update_page",
45
+ "replace_in_page",
46
+ "link_pages",
47
+ "batch_link",
48
+ "set_parent",
49
+ }
50
+ )
51
+
52
+ def __init__(self, skill: Skill, base_ref: str | None) -> None:
53
+ self._base_ref = base_ref
54
+ self._available_tools = SkillToolPolicy.available_tools(skill, base_ref)
55
+
56
+ def allows(self, tool_name: str) -> bool:
57
+ return tool_name in self._available_tools
58
+
59
+ def prepare_arguments(self, tool_name: str, arguments: dict[str, Any]) -> dict[str, Any]:
60
+ if self._base_ref is None or not SkillToolPolicy.is_base_scoped(tool_name):
61
+ return arguments
62
+
63
+ requested_base_ref = arguments.get("base_ref")
64
+
65
+ if requested_base_ref is not None and requested_base_ref != self._base_ref:
66
+ raise LockedBaseError(tool_name, self._base_ref)
67
+
68
+ return {**arguments, "base_ref": self._base_ref}
69
+
70
+ @staticmethod
71
+ def is_base_scoped(tool_name: str) -> bool:
72
+ return tool_name in SkillToolPolicy.READ_TOOLS or tool_name in SkillToolPolicy.WRITE_TOOLS
73
+
74
+ @staticmethod
75
+ def available_tools(skill: Skill, base_ref: str | None) -> frozenset[str]:
76
+ tools = SkillToolPolicy.GOVERNANCE_TOOLS | SkillToolPolicy.READ_TOOLS
77
+
78
+ if skill is Skill.CAPTURE:
79
+ tools |= SkillToolPolicy.WRITE_TOOLS
80
+
81
+ if base_ref is None:
82
+ tools |= SkillToolPolicy.BASE_DISCOVERY_TOOLS
83
+
84
+ if base_ref is None and skill is Skill.CAPTURE:
85
+ tools |= SkillToolPolicy.BASE_CREATION_TOOLS
86
+
87
+ return tools
@@ -0,0 +1,297 @@
1
+ Metadata-Version: 2.5
2
+ Name: lorebo-sdk
3
+ Version: 0.1.0
4
+ Summary: Save and retrieve Lorebo knowledge from your application with any LLM
5
+ Project-URL: Homepage, https://github.com/lexrag/lorebo-sdk
6
+ Project-URL: Documentation, https://github.com/lexrag/lorebo-sdk#quick-start
7
+ Project-URL: Repository, https://github.com/lexrag/lorebo-sdk
8
+ Project-URL: Issues, https://github.com/lexrag/lorebo-sdk/issues
9
+ Author: LexRAG
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,knowledge-base,llm,lorebo,mcp,pydantic-ai
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Framework :: Pydantic
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: fastmcp-slim[client]>=4.1
23
+ Requires-Dist: httpx>=0.28
24
+ Requires-Dist: pydantic-ai-slim[mcp]>=2.59
25
+ Requires-Dist: pydantic>=2.11
26
+ Provides-Extra: anthropic
27
+ Requires-Dist: pydantic-ai-slim[anthropic]>=2.59; extra == 'anthropic'
28
+ Provides-Extra: bedrock
29
+ Requires-Dist: pydantic-ai-slim[bedrock]>=2.59; extra == 'bedrock'
30
+ Provides-Extra: google
31
+ Requires-Dist: pydantic-ai-slim[google]>=2.59; extra == 'google'
32
+ Provides-Extra: groq
33
+ Requires-Dist: pydantic-ai-slim[groq]>=2.59; extra == 'groq'
34
+ Provides-Extra: mistral
35
+ Requires-Dist: pydantic-ai-slim[mistral]>=2.59; extra == 'mistral'
36
+ Provides-Extra: openai
37
+ Requires-Dist: pydantic-ai-slim[openai]>=2.59; extra == 'openai'
38
+ Description-Content-Type: text/markdown
39
+
40
+ <p align="center">
41
+ <a href="https://github.com/lexrag/lorebo-sdk">
42
+ <picture>
43
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/lexrag/lorebo-sdk/main/assets/lorebo-logo-on-dark.svg">
44
+ <img src="https://raw.githubusercontent.com/lexrag/lorebo-sdk/main/assets/lorebo-logo-primary.svg" width="264" alt="Lorebo">
45
+ </picture>
46
+ </a>
47
+ </p>
48
+
49
+ <h1 align="center">Lorebo SDK</h1>
50
+
51
+ <p align="center"><strong>Give your application a knowledge base that people and AI share.</strong></p>
52
+
53
+ <p align="center">
54
+ <a href="https://github.com/lexrag/lorebo-sdk/actions/workflows/check.yml"><img src="https://github.com/lexrag/lorebo-sdk/actions/workflows/check.yml/badge.svg" alt="Checks"></a>
55
+ <a href="https://github.com/lexrag/lorebo-sdk/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-593EDC" alt="MIT license"></a>
56
+ <a href="https://pypi.org/project/lorebo-sdk/"><img src="https://img.shields.io/badge/Python-3.12+-3776AB" alt="Python 3.12+"></a>
57
+ <a href="https://www.npmjs.com/package/lorebo-sdk"><img src="https://img.shields.io/badge/TypeScript-Node_22+-3178C6" alt="TypeScript, Node 22+"></a>
58
+ </p>
59
+
60
+ <p align="center">
61
+ <a href="#quick-start">Quick start</a> ·
62
+ <a href="#results">Results</a> ·
63
+ <a href="#choosing-a-base">Choosing a base</a> ·
64
+ <a href="#errors">Errors</a> ·
65
+ <a href="#connecting-to-lorebo">Connecting to Lorebo</a>
66
+ </p>
67
+
68
+ Lorebo turns useful AI work into knowledge you own:
69
+ readable, connected pages that people and AI agents can find, correct and reuse.
70
+
71
+ The Lorebo SDK lets your application use that knowledge with two calls:
72
+
73
+ - **`capture`** saves the durable part of a text as Lorebo pages. It searches
74
+ first, updates pages that already cover the topic and creates the rest.
75
+ - **`explore`** answers a question from the pages in Lorebo and returns the
76
+ pages the answer relies on.
77
+
78
+ Both calls run the official Lorebo skills with the language model you choose.
79
+ The SDK is available for Python and TypeScript with the same behavior.
80
+
81
+ ## Requirements
82
+
83
+ - A Lorebo MCP endpoint:
84
+ - Lorebo Desktop serves `http://127.0.0.1:8757/mcp` on your machine.
85
+ - [Lorebo Headless](https://github.com/orgs/lexrag/packages/container/package/lorebo-headless) serves `http://127.0.0.1:8758/mcp` when run locally with the example below.
86
+ - A language model that supports tool calls and structured output.
87
+ - Python 3.12+ or Node.js 22+.
88
+
89
+ ## Connecting to Lorebo
90
+
91
+ With Desktop already running, use its local MCP URL in the quick start.
92
+ To run Headless with Docker instead:
93
+
94
+ ```bash
95
+ docker run --detach --name lorebo \
96
+ --publish 127.0.0.1:8758:8758 \
97
+ --volume lorebo-data:/data \
98
+ ghcr.io/lexrag/lorebo-headless:stable
99
+ ```
100
+
101
+ Use `http://127.0.0.1:8758/mcp` as the SDK URL and `None` (`null` in
102
+ TypeScript) as the token. The volume preserves your bases when the container
103
+ is recreated. Back up the complete volume before upgrading and stop the old
104
+ container before starting another writer on it. The official image is Linux
105
+ amd64; ARM hosts need amd64 emulation.
106
+
107
+ For a remote deployment, use the HTTPS URL and authentication configured by
108
+ your deployment operator. The SDK's `token` argument sends an optional HTTP
109
+ Bearer token; it does not configure the server's authentication or perform
110
+ Lorebo broker OAuth sign-in. Keep the native server behind the authenticated
111
+ deployment perimeter. No provider API key or Lorebo credential belongs in source
112
+ code; configure model-provider credentials through the provider's environment
113
+ settings.
114
+
115
+ ## Quick start
116
+
117
+ ### Python
118
+
119
+ ```bash
120
+ pip install "lorebo-sdk[openai]"
121
+ ```
122
+
123
+ The extra installs the model provider. `anthropic`, `google`, `groq`,
124
+ `mistral` and `bedrock` are available too.
125
+
126
+ ```python
127
+ import asyncio
128
+
129
+ from lorebo_sdk.client import Lorebo
130
+
131
+
132
+ async def main() -> None:
133
+ lorebo = Lorebo.from_url(
134
+ url="http://127.0.0.1:8757/mcp",
135
+ token=None,
136
+ model="openai:gpt-5-mini",
137
+ base_ref="local:your-entry-id",
138
+ )
139
+
140
+ captured = await lorebo.capture("Our API listens on port 8757, on loopback only.")
141
+ print(captured.summary)
142
+
143
+ explored = await lorebo.explore("Which port does our API use?")
144
+ print(explored.answer)
145
+
146
+
147
+ asyncio.run(main())
148
+ ```
149
+
150
+ `model` accepts any [Pydantic AI](https://ai.pydantic.dev/models/) model or model name.
151
+
152
+ ### TypeScript
153
+
154
+ ```bash
155
+ npm install lorebo-sdk ai @ai-sdk/openai
156
+ ```
157
+
158
+ ```ts
159
+ import { openai } from "@ai-sdk/openai";
160
+ import { createLorebo } from "lorebo-sdk";
161
+
162
+ const lorebo = createLorebo({
163
+ url: "http://127.0.0.1:8757/mcp",
164
+ token: null,
165
+ model: openai("gpt-5-mini"),
166
+ baseRef: "local:your-entry-id",
167
+ });
168
+
169
+ const captured = await lorebo.capture("Our API listens on port 8757, on loopback only.");
170
+ console.log(captured.summary);
171
+
172
+ const explored = await lorebo.explore("Which port does our API use?");
173
+ console.log(explored.answer);
174
+ ```
175
+
176
+ `model` accepts any [AI SDK](https://ai-sdk.dev/providers) language model.
177
+
178
+ ## Results
179
+
180
+ `capture` returns what changed in Lorebo:
181
+
182
+ | Field | Meaning |
183
+ | --------- | ----------------------------------- |
184
+ | `summary` | One or two sentences for your user. |
185
+ | `created` | Pages this call created. |
186
+ | `updated` | Existing pages this call changed. |
187
+
188
+ `explore` returns the answer and its sources:
189
+
190
+ | Field | Meaning |
191
+ | --------- | --------------------------------------------------- |
192
+ | `answer` | Plain-text answer for your user. |
193
+ | `sources` | Pages the answer relies on, each read in this call. |
194
+
195
+ Each page has an `id`, a `title` and the `base_ref` (`baseRef` in TypeScript)
196
+ of the base that holds it. The SDK builds these lists from Lorebo's responses,
197
+ not from the model's text, so they only contain pages that exist.
198
+
199
+ Summaries and answers are plain text written for your user, without the model's
200
+ reasoning, tool names or page IDs. Nothing is printed to your console.
201
+
202
+ ## Choosing a base
203
+
204
+ A Lorebo installation can hold several knowledge bases. Pass `base_ref` to
205
+ lock every call to one of them:
206
+
207
+ ```python
208
+ lorebo = Lorebo.from_url(..., base_ref="local:your-entry-id")
209
+ ```
210
+
211
+ When the model tries to use another base, the call stops with
212
+ `LockedBaseError` before anything is written there.
213
+
214
+ With multi-base permissions, pass `None` (`null` in TypeScript) to let the skill choose. `capture` then
215
+ picks the base the knowledge belongs to, or creates one when none fits.
216
+ `explore` picks the base that holds the answer.
217
+
218
+ For a local Headless container, run `docker exec lorebo lorebo-headless --json
219
+ base list` and use `local:<entry_id>` for the active base. Desktop also displays
220
+ the base reference on Base Home. Use the registry entry ID, not the database's
221
+ logical base ID.
222
+
223
+ When the server exposes multi-base MCP tools, list bases with an unlocked client:
224
+
225
+ ```python
226
+ for base in await lorebo.list_bases():
227
+ print(base.base_ref, base.label)
228
+ ```
229
+
230
+ ```ts
231
+ for (const base of await lorebo.listBases()) {
232
+ console.log(base.baseRef, base.label);
233
+ }
234
+ ```
235
+
236
+ `create_base` (`createBase` in TypeScript) creates a base from your code.
237
+ Actions remain subject to the connected runtime's account entitlements and
238
+ agent permissions for each base.
239
+ On Free, lock the client to the active base; multi-base discovery and base
240
+ creation through MCP require the corresponding Pro permissions.
241
+
242
+ ## What the model can do
243
+
244
+ The model only sees the Lorebo tools its skill needs:
245
+
246
+ - `explore` can read and search pages.
247
+ - `capture` can also create, update and link pages.
248
+ - Without a locked base, both can list bases and `capture` can create one when
249
+ the connected runtime exposes and permits those tools.
250
+
251
+ Tools that delete pages, delete bases, restore backups or change sharing are
252
+ never offered.
253
+
254
+ ## Errors
255
+
256
+ Every SDK error extends `LoreboError`:
257
+
258
+ | Error | Raised when |
259
+ | ------------------- | -------------------------------------------------------------- |
260
+ | `LockedBaseError` | The model tried to use a base other than the locked one. |
261
+ | `LoreboToolError` | Lorebo rejected a call or returned an unexpected response. |
262
+ | `RunLimitError` | The skill did not finish within the step limit of 24. |
263
+ | `SkillPackageError` | A Lorebo skill could not be downloaded or failed verification. |
264
+
265
+ Python imports them from `lorebo_sdk.errors`, TypeScript from `lorebo-sdk/errors`.
266
+ Errors from the model provider are passed through unchanged.
267
+
268
+ ## Lorebo skills
269
+
270
+ Each SDK release is pinned to one version of the official `lorebo-capture`
271
+ and `lorebo-explore` skills. They are downloaded from `downloads.lorebo.com`
272
+ on first use, checked against a SHA-256 digest built into the SDK and kept in
273
+ memory for the life of the client.
274
+
275
+ ## Development
276
+
277
+ ```bash
278
+ uv sync
279
+ uv run mypy
280
+ uv run ruff check .
281
+ uv run pytest
282
+ ```
283
+
284
+ ```bash
285
+ cd typescript
286
+ npm ci
287
+ npm run check
288
+ npm run build
289
+ npm pack --dry-run
290
+ ```
291
+
292
+ Package publication is described in
293
+ [Releasing](https://github.com/lexrag/lorebo-sdk/blob/main/docs/releasing.md).
294
+
295
+ ## License
296
+
297
+ [MIT](https://github.com/lexrag/lorebo-sdk/blob/main/LICENSE)
@@ -0,0 +1,13 @@
1
+ lorebo_sdk/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ lorebo_sdk/client.py,sha256=G1Iw2H5iNw_3op652XW3QDEBoqDoGuWvNzRFh0g6nM8,3673
3
+ lorebo_sdk/errors.py,sha256=RiIauXYtRXSYaIRqfcAEPZxmpamIDtWIhcdrTvjasvk,785
4
+ lorebo_sdk/pages.py,sha256=7nYwrFM6d_1cfYjNzwFwWiBAlJTpnmvLtTkxqGk6kIg,2847
5
+ lorebo_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ lorebo_sdk/records.py,sha256=w_qYzqCLXrb4byyjxpIUZJvsiyp2N_S42iNgJ60rCJ4,534
7
+ lorebo_sdk/runs.py,sha256=D4bicJvXMiTJQ6_X4FdugwsNIOacYeK4jFF9jE7tJps,5767
8
+ lorebo_sdk/skills.py,sha256=h6tnZD_s3FXGsU4skbjsz0q1hWZ-uOzAqtcAdpEgnXw,3214
9
+ lorebo_sdk/tools.py,sha256=95HOL6KwNrCIWiYJmNb6lnkrLsA3TwcXMQ6QBQTjeWc,2573
10
+ lorebo_sdk-0.1.0.dist-info/METADATA,sha256=KSGCmFl7FKA8G8MMrrMtXMZyg6fc5J-ssAcKfNhM2VY,10693
11
+ lorebo_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ lorebo_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=g9c4PDxetLCEzy3TE3wP2ERFj1sNY9QOrCYvGlJsaRU,1063
13
+ lorebo_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LexRAG
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.