Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 145 additions & 0 deletions docs/providers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# Providers and self-hosted gateways

Pass a `Provider` to the `SelfGraph` constructor to use one object for
structured generation, embedding, and reranking. Both SDKs export the protocol
and its retrieval output types.

| Method | Result |
|--------|--------|
| `generate(system=, user=, output=)` in Python, `generate({ system, user, output })` in TypeScript | A result matching the Pydantic model or Zod schema supplied as `output`. Use the supplied model or schema to validate the gateway's reply. |
| `embed(texts)` | `EmbeddingVectors`, one numeric vector per text, in input order and with a common dimension. |
| `rerank(query, texts)` | `RerankScores`, one finite number per text, in input order. SelfGraph ranks higher scores first. |

All three methods are async. `provider` supplies the LLM for extraction and
any LLM tiers you select. Choose `seeds="embeddings"` or `level="max"` to
use embedding seeds. Retrieval uses the provider's scorer by default when
`max_tier` is `"max"`. An explicit `rerank` tier takes precedence. Passing
`llm`, `embedder`, or `reranker` overrides the corresponding capability.

## Configure the chat endpoint

If the gateway implements the chat API of an existing route, set
`GATEWAY_CHAT_ROUTE` to a provider identifier supported by the SDK whose API
the gateway implements, and `GATEWAY_TOKEN` to the gateway credential. Use the
gateway's chat API base URL and the model alias the gateway exposes. The route
must support structured replies.

Install the `llm` extra for Python.

```python
import os

from selfgraph import LLMConfig, SelfGraph

chat = LLMConfig(
provider=os.environ["GATEWAY_CHAT_ROUTE"],
base_url="https://gateway.example.test/v1",
model="chat-default",
api_key=os.environ["GATEWAY_TOKEN"],
)
graph = SelfGraph(store, llm=chat)
```

Install the optional generation dependencies for the chosen route in TypeScript.

```typescript
import { type LLMConfig, SelfGraph } from "@hydradb/selfgraph";

const chat: LLMConfig = {
provider: process.env.GATEWAY_CHAT_ROUTE!,
base_url: "https://gateway.example.test/v1",
model: "chat-default",
api_key: process.env.GATEWAY_TOKEN!,
};
const graph = new SelfGraph(store, { llm: chat });
```

## Use a custom gateway for all three capabilities

This example reuses configured chat generation and adds custom gateway
endpoints for retrieval. It assumes the same gateway implements these routes.

- `POST /v1/embed` with `{"texts": ["..."]}` and returns `{"vectors": [[0.1, 0.2]]}`.
- `POST /v1/rerank` with `{"query": "...", "texts": ["..."]}` and returns `{"scores": [0.9]}`.

The adapter turns the existing scorer's `score` method into `Provider.rerank`.
Use your gateway's request and response shapes in the adapter methods.

Reuse `chat` from the Python example.

```python
import asyncio
import json
from urllib.request import Request, urlopen

from pydantic import TypeAdapter

from selfgraph import EmbeddingVectors, RerankScores, SelfGraph, build_provider

def post(path, payload):
request = Request(
f"{chat.base_url}/{path}",
data=json.dumps(payload).encode(),
headers={
"Authorization": f"Bearer {chat.api_key}",
"Content-Type": "application/json",
},
)
with urlopen(request, timeout=30) as response:
return json.load(response)

class GatewayRetrieval:
async def embed(self, texts: list[str]) -> EmbeddingVectors:
reply = await asyncio.to_thread(post, "embed", {"texts": texts})
return TypeAdapter(EmbeddingVectors).validate_python(reply["vectors"])

async def score(self, query: str, texts: list[str]) -> RerankScores:
reply = await asyncio.to_thread(post, "rerank", {"query": query, "texts": texts})
return TypeAdapter(RerankScores).validate_python(reply["scores"])

retrieval = GatewayRetrieval()
provider = build_provider(chat, retrieval, retrieval)
graph = SelfGraph(store, provider=provider, seeds="embeddings")
```

Reuse `chat` from the TypeScript example.

```typescript
import {
buildProvider,
type EmbeddingVectors,
type RerankScores,
SelfGraph,
} from "@hydradb/selfgraph";
import { z } from "zod";

async function post(path: string, payload: object): Promise<unknown> {
const response = await fetch(`${chat.base_url}/${path}`, {
method: "POST",
headers: {
Authorization: `Bearer ${chat.api_key}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(30_000),
});
if (!response.ok) throw new Error(`Gateway request failed (${response.status})`);
return response.json();
}

const retrieval = {
async embed(texts: string[]): Promise<EmbeddingVectors> {
const reply = await post("embed", { texts });
return z.object({ vectors: z.array(z.array(z.number())) }).parse(reply).vectors;
},
async score(query: string, texts: string[]): Promise<RerankScores> {
const reply = await post("rerank", { query, texts });
return z.object({ scores: z.array(z.number()) }).parse(reply).scores;
},
};
const provider = buildProvider(chat, retrieval, retrieval);
const graph = new SelfGraph(store, { provider, seeds: "embeddings" });
```

For a gateway with its own generation API, implement `generate`, `embed`,
and `rerank` on your provider and pass it directly as `provider`.
1 change: 1 addition & 0 deletions docs/reference/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ both SDKs. See [TypeScript](../typescript.md) for differences in names and setup
|------|--------|
| [Install](../install.md) | The package and its optional extras. |
| [Inserting](../inserting.md) | Extracting from text, and writing ready facts. |
| [Providers](../providers.md) | One client for generation, embeddings, and reranking through a gateway. |
| [Tiers](../tiers.md) | The `level` preset, what each level picks, and the cost cap. |
| [Schema](../schema.md) | Optional types that guide extraction and check writes. |
| [Ontology](../ontology.md) | Terms, synonyms, definitions, grounding a question, and drafts from table metadata. |
Expand Down
8 changes: 6 additions & 2 deletions src/selfgraph/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
StepOut,
)
from .ids import decision_id, entity_id, normalize_rel_type, preference_id, profile_id, relation_id
from .llm import build_llm_client
from .llm import build_llm_client, build_provider
from .models import (
AnswerabilityReport,
Certification,
Expand Down Expand Up @@ -104,7 +104,7 @@
UnmergeResult,
UnsupportedSentence,
)
from .protocols import Embedder, Extractor, GraphStore, LLMClient, Reranker
from .protocols import Embedder, EmbeddingVectors, Extractor, GraphStore, LLMClient, Provider, Reranker, RerankScores
from .resolution import DefaultResolver, EntityResolver, LLMResolver, ResolutionDecision, ResolverMode, SameEntity
from .schema import Definition, EntityType, PropertySpec, RelationEndpoint, RelationType, Schema, TermMapping
from .sync import SyncSelfGraph
Expand Down Expand Up @@ -157,6 +157,10 @@ def __dir__() -> list[str]:
"Extractor",
"Embedder",
"Reranker",
"Provider",
"EmbeddingVectors",
"RerankScores",
"build_provider",
"Level",
"Entity",
"Certification",
Expand Down
17 changes: 14 additions & 3 deletions src/selfgraph/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
as_input,
check_options,
)
from .protocols import Embedder, Extractor, GraphStore, LLMClient, Reranker
from .protocols import Embedder, Extractor, GraphStore, LLMClient, Provider, Reranker
from .provenance import record_source
from .resolution import (
EntityResolver,
Expand Down Expand Up @@ -152,6 +152,7 @@ def __init__(
embedder: Embedder | None = None,
rerank: tiers.RerankTier | None = None,
reranker: Reranker | None = None,
provider: Provider | None = None,
**options: Any,
) -> None:
check_options(
Expand All @@ -174,6 +175,7 @@ def __init__(
"embedder",
"rerank",
"reranker",
"provider",
],
)
_require_namespace(namespace)
Expand All @@ -182,6 +184,13 @@ def __init__(
tiers.require_level("max_tier", max_tier)
self.store = store
self.namespace = namespace
if provider is not None:
if not all(callable(getattr(provider, method, None)) for method in ("generate", "embed", "rerank")):
raise ValidationError("provider must have generate, embed, and rerank methods", field="provider")
if llm is None:
llm = provider
if embedder is None:
embedder = provider
self._llm = resolve_llm(llm)
if level == "max" and max_tier == "max" and self._llm is None:
raise needs_llm("level 'max'")
Expand All @@ -192,7 +201,9 @@ def __init__(
self._level: tiers.Level = level
self._max_tier: tiers.Level = max_tier
self._embedder = embedder
self._reranker = reranker
self._score_context = (
reranker.score if reranker is not None else provider.rerank if provider is not None else None
)
self._embeddings: dict[tuple[str, str], tuple[str, list[float]]] = {}
preset = tiers.PRESETS[level]
if extraction is not None:
Expand All @@ -206,7 +217,7 @@ def __init__(
seeds = preset["seeds"] if embedder is not None or preset["seeds"] != "embeddings" else "synonyms"
self._seeds = self._seed_tier(seeds)
self._strategy = preset["traversal"]
if rerank is None and reranker is not None:
if rerank is None and (reranker is not None or (provider is not None and max_tier == "max")):
self._rerank = "custom"
else:
if rerank is None:
Expand Down
4 changes: 2 additions & 2 deletions src/selfgraph/llm/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from .base import build_llm_client, resolve_llm
from .base import build_llm_client, build_provider, resolve_llm

__all__ = ["build_llm_client", "resolve_llm"]
__all__ = ["build_llm_client", "build_provider", "resolve_llm"]
25 changes: 23 additions & 2 deletions src/selfgraph/llm/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
)
from ..ids import type_name
from ..models import _KNOWN_PROVIDERS, LLMConfig, as_input, did_you_mean, suggest_key
from ..protocols import LLMClient
from ..protocols import Embedder, LLMClient, Provider, Reranker

__all__ = ["build_llm_client", "resolve_llm", "summarize_error"]
__all__ = ["build_llm_client", "build_provider", "resolve_llm", "summarize_error"]

T = TypeVar("T")

Expand Down Expand Up @@ -230,6 +230,27 @@ def build_llm_client(config: LLMConfig) -> LLMClient:
return _UnifiedLLMClient(config)


class _ProviderAdapter:
def __init__(self, llm: LLMClient, embedder: Embedder, reranker: Reranker) -> None:
self.generate = llm.generate
self.embed = embedder.embed
self.rerank = reranker.score
self.base_url = getattr(llm, "base_url", None)
self.concurrency = getattr(llm, "concurrency", None)


def build_provider(llm: LLMConfig | LLMClient, embedder: Embedder, reranker: Reranker) -> Provider:
"""Adapt a configured generation client and existing retrieval clients into one provider.

@param llm (LLMConfig | LLMClient): the generation settings or client.
@param embedder (Embedder): the embedding client.
@param reranker (Reranker): the relevance scorer.
@return (Provider): the provider that delegates each capability.
"""
client = build_llm_client(llm) if isinstance(llm, LLMConfig) else llm
return _ProviderAdapter(client, embedder, reranker)


def resolve_llm(llm: LLMConfig | Mapping | LLMClient | None) -> LLMClient | None:
"""Normalise the llm argument to an LLMClient or None.

Expand Down
30 changes: 27 additions & 3 deletions src/selfgraph/protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,19 @@

from .models import CypherResult, Extraction, JsonValue, ParsedDocument

__all__ = ["LLMClient", "Extractor", "Embedder", "Reranker", "GraphStore"]
__all__ = [
"LLMClient",
"Extractor",
"Embedder",
"Reranker",
"GraphStore",
"Provider",
"EmbeddingVectors",
"RerankScores",
]

EmbeddingVectors = list[list[float]]
RerankScores = list[float]

T = TypeVar("T")

Expand Down Expand Up @@ -37,7 +49,7 @@ async def extract(self, document: ParsedDocument) -> Extraction: ...

@runtime_checkable
class Embedder(Protocol):
async def embed(self, texts: list[str]) -> list[list[float]]:
async def embed(self, texts: list[str]) -> EmbeddingVectors:
"""Return one vector per text, in order, all of one length.

@param texts (list[str]): the texts to embed.
Expand All @@ -48,7 +60,7 @@ async def embed(self, texts: list[str]) -> list[list[float]]:

@runtime_checkable
class Reranker(Protocol):
async def score(self, query: str, texts: list[str]) -> list[float]:
async def score(self, query: str, texts: list[str]) -> RerankScores:
"""Return one relevance score per context record text, in order, higher first.

@param query (str): the retrieve query.
Expand All @@ -58,6 +70,18 @@ async def score(self, query: str, texts: list[str]) -> list[float]:
...


@runtime_checkable
class Provider(LLMClient, Embedder, Protocol):
async def rerank(self, query: str, texts: list[str]) -> RerankScores:
"""Return one finite score per text in input order, with higher scores ranked first.

@param query (str): the query.
@param texts (list[str]): the candidate texts.
@return (RerankScores): the scores.
"""
...


@runtime_checkable
class GraphStore(Protocol):
async def initialize(self) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/selfgraph/retrieval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1193,7 +1193,7 @@ async def _rerank_scores(graph: SelfGraph, tier: str, query: str, texts: list[st
vectors.extend(await _embed(graph._embedder, texts[start : start + _EMBED_BATCH]))
scores = [_cosine(target, v) for v in vectors]
else:
scores = list(await graph._reranker.score(query, texts))
scores = list(await graph._score_context(query, texts))
if len(scores) != len(texts):
raise ValidationError(f"reranker returned {len(scores)} scores for {len(texts)} records")
if not all(isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) for x in scores):
Expand Down
Loading
Loading