Skip to content

feat(graphile-llm): embed and complete through the metered gateway - #1961

Merged
pyramation merged 3 commits into
mainfrom
feat/llm-gateway-metering
Nov 5, 2026
Merged

pyramation merged 3 commits into
mainfrom
feat/llm-gateway-metering

Conversation

@pyramation

@pyramation pyramation commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

graphile-llm's server-side model calls — VectorNearbyInput.text, unifiedSearch, the {column}Text companions, ragQuery and embedText — called the model provider directly (EMBEDDER_BASE_URL / CHAT_BASE_URL), so none of them passed through the agentic-server gateway that records inference. They now go through the gateway at AGENTIC_SERVER_URL, once per model call, under the identity the request carries. There is no direct-provider route any more: configuring an embedder or chat completer without AGENTIC_SERVER_URL fails when the schema is built.

  • @constructive-io/llm-env: AGENTIC_SERVER_URL → gateway.url (no default).
  • graphile-llm: buildEmbedder / buildChatCompleter (preset defaultEmbedder / defaultChatCompleter) and the ...FromEnv variants return a gateway client (POST /v1/embeddings, POST /v1/chat/completions, X-LLM-Provider = the configured provider). EmbedderConfig / ChatConfig lose baseUrl; buildEmbedderFromModule / buildChatCompleterFromModule and the @agentic-kit/ollama dependency are gone. With a gateway and nothing else configured the default models are used; with a provider or model configured and no gateway, requireGatewayUrl throws; with neither, text fields and RAG stay disabled.
  • Identity is never a parameter. identityFromClaims(pgSettings) reads jwt.claims.database_id / entity_id / user_id from the request's own pgSettings; resolveRequestScope puts it (plus the database's llm_module model overrides) in the per-request llmConfigStore for the plan-time embedding step and the RAG plugin; the gateway client turns it into X-Database-Id / X-Entity-Id / X-Actor-Id via @agentic-kit/metering's buildIdentityHeaders. A request with no database_id claim is refused before it reaches the gateway.
  • agentic-server: Ollama's /api/embed prompt_eval_count is reported as usage.prompt_tokens / total_tokens (was always 0); max_tokens is forwarded to Ollama as options.num_predict.

Tests

graphql/server-test/__tests__/llm-gateway-metering.integration.test.ts runs the routed server over HTTP against a real agentic-server (in-memory InferenceSink) in front of a local Ollama stand-in, and asserts the recorded entries: one per embedding with the request's database and actor (Bearer) or database as entity (anonymous); none when the client sends a vector; ragQuery = one embed + one chat; embedText = one; an upstream failure is recorded as status: 'error' and fails the request.

On main (same test, pre-fix sources): 7 of 9 fail — the embedder tries localhost:11434 and nothing is recorded; only the two "records nothing" controls pass. On this branch: 9 of 9 pass.

The existing suites that embedded through a local Ollama now run through the same gateway (graphile-llm/test-utils/gateway.ts, server-test/__tests__/llm-gateway.shared.ts): graphile-llm 98/98 (unit cases for the gateway/no-gateway/nothing-configured outcomes of buildEmbedder* / buildChatCompleter*, and a refused unattributed call), vector-text-search + vector-text-mutations 14/14, packages/llm-env 14/14, agentic/agentic-server 22/22.

Link to Devin session: https://app.devin.ai/sessions/698c523a027547f2be44eb9cbbae8d8e
Open in Devin Desktop: https://app.devin.ai/desktop/session/698c523a027547f2be44eb9cbbae8d8e?variant=devin
Requested by: @pyramation

…ugh the metered gateway

With AGENTIC_SERVER_URL set, graphile-llm embeds VectorNearbyInput.text,
{column}Text companions, ragQuery and embedText through the gateway's
/v1/embeddings (and ragQuery's answer through /v1/chat/completions) under
the identity the request's jwt.claims carry, so every model call is
recorded once with its database and actor. The gateway reports Ollama's
prompt_eval_count as embedding usage.
@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@luxor-code-review

luxor-code-review Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (1)

📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — Gateway chat drops max_tokens for Ollama · transforms.ts:72–81 · unchanged line

// agentic/agentic-server/src/transforms.ts
72	  if (provider.type === 'ollama') {
73	    return {
74	      model: model || 'llama3',
75	      messages: flattenContentParts(body.messages),
76	      stream: false,
77	      ...(body.temperature !== undefined && {
78	        options: { temperature: body.temperature }
79	      })
80	    };
81	  }

The new gateway chat completer sends max_tokens to the gateway (graphile/graphile-llm/src/chat.ts:106), but transformChatRequest's Ollama branch maps only temperature into the options object and never forwards max_tokens (agentic/agentic-server/src/transforms.ts:72-81). RAG calls the completer with maxTokens (graphile/graphile-llm/src/plugins/rag-plugin.ts:353), which the direct OllamaAdapter path honored. Via the new gateway route the cap is silently dropped, so completions can run unbounded where they were previously limited.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Restore test env and close servers in finally (llm-gateway-metering.integration.test.ts:216) — The afterAll awaits teardown() before closing the gateway/model servers and restoring the seven process.env keys it rewrote (graphql/server-test/tests/llm-gateway-metering.integration.test.ts:216-224).

This PR routes embed and chat completions through the agentic-server LLM gateway with usage metering, adds gateway-aware env resolution in llm-env, and wires identity attribution into the request scope.

Files Change
graphile/graphile-llm/src/*, packages/llm-env/src/index.ts Add gateway URL resolution, an llmConfigStore for per-database model overrides, and gateway completers/embedders that forward usage to the metering service.
agentic/agentic-server/src/transforms.ts Add request/response transforms translating between OpenAI-shaped gateway calls and provider adapters (Ollama/OpenAI).
graphql/server-test/* Add metering seed fixture and an integration test asserting per-tenant metering and identity attribution.

Three issues were flagged: RAG plugin scopes omit the per-database model overrides, the Ollama transform drops max_tokens, and the integration test teardown does not restore env in a finally.

Reviewed commit: 037c1ed

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Integrates an LLM gateway metering path across graphile-llm, agentic-server, llm-env, and the server-test suite, with per-tenant llm_module model overrides and Ollama/OpenAI request transforms.

Key findings

Comment on lines +260 to +262
return lambda($combined, (input: any) => llmConfigStore.run(
{ identity: identityFromClaims(input.pgSettings) },
async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 bug · medium

RAG scopes drop llm_module model overrides

The new llmConfigStore.run scopes in ragQuery and embedText carry only identity (graphile/graphile-llm/src/plugins/rag-plugin.ts:260-262), while the gateway embedder and chat completer read embeddingModel/chatModel overrides from the store (graphile/graphile-llm/src/embedder.ts:149, graphile/graphile-llm/src/chat.ts:98). Those per-database llm_module overrides are only resolved on the embed-inputs path via resolveConfigOverrides (graphile/graphile-llm/src/embed-inputs.ts:54-73), and the RAG plugin receives the raw, unwrapped embedder. In a multi-tenant deployment where a database overrides its model, ragQuery embeds its prompt and generates its answer with the env-default model while the chunk-search embeddings on the same request use the tenant's model — mismatched embedding dimensions can silently break the vector search and the metered calls record the wrong model.

📋 Prompt for AI Agents

In graphile/graphile-llm/src/plugins/rag-plugin.ts, the ragQuery lambda (lines 260-262) and the embedText lambda (lines 380-382) call llmConfigStore.run({ identity: identityFromClaims(...) }, ...) with only an identity, while the gateway embedder/chat completer also read embeddingModel/chatModel/baseUrl from the store (graphile/graphile-llm/src/embedder.ts:149, graphile/graphile-llm/src/chat.ts:98). Export resolveConfigOverrides from graphile/graphile-llm/src/embed-inputs.ts:54 and, inside both RAG lambdas, await it with the request's grafast context and spread the result into the scope: llmConfigStore.run({ ...(await resolveConfigOverrides(ctx)), identity: identityFromClaims(input.pgSettings) }, ...), so ragQuery/embedText honor the database's llm_module model configuration like the embed-inputs path does.

@pyramation
pyramation merged commit ea164a4 into main Nov 5, 2026
19 checks passed
@pyramation
pyramation deleted the feat/llm-gateway-metering branch November 5, 2026 13:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant