Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): record AI Gateway session affinity on step spans (#5041)

Andrew Barba09b423a5e6b5
diff --git a/.changeset/gateway-session-affinity-spans.md b/.changeset/gateway-session-affinity-spans.md
new file mode 100644
index 000000000..4912729d3
--- /dev/null
+++ b/.changeset/gateway-session-affinity-spans.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`agent.step` spans for AI Gateway model calls now record the Gateway's session affinity report: the session ID, where that ID came from, the affinity outcome, and the pinned and displaced providers. Use these attributes to match a step to its session in the AI Gateway logs Sessions view.
diff --git a/docs/agent-config.md b/docs/agent-config.md
index 5593ed4f7..6e2dd4086 100644
--- a/docs/agent-config.md
+++ b/docs/agent-config.md
@@ -67,6 +67,28 @@ Gateway, share that ID so their Gateway generations can be found together.
Direct-provider calls do not receive the option. An authored `gateway.sessionId`
takes precedence; AI Gateway hashes IDs longer than 256 characters.
+AI Gateway also uses this ID for
+[session affinity](https://vercel.com/docs/ai-gateway/models-and-providers/session-affinity),
+which tries the provider that served the session's previous call first, among
+the providers your routing settings allow, so that provider can read the prompt
+from its cache. The conversation
+appears as one session in the AI Gateway logs Sessions view. Affinity can move
+the pinned provider ahead of your `order`. To keep `order` exactly, set
+`sessionAffinity: false`:
+
+```ts title="agent/agent.ts"
+import { defineAgent } from "eve";
+
+export default defineAgent({
+ model: "anthropic/claude-opus-5.5",
+ modelOptions: {
+ providerOptions: {
+ gateway: { order: ["bedrock", "anthropic"], sessionAffinity: false },
+ },
+ },
+});
+```
+
For direct OpenAI and `chatgpt()` model calls, eve sets
`providerOptions.openai.promptCacheKey` to a SHA-256 hash of the session ID,
which helps OpenAI route a session's calls to the cache that holds its prompt
diff --git a/docs/guides/instrumentation/otel.mdx b/docs/guides/instrumentation/otel.mdx
index 8679147d7..061bb04db 100644
--- a/docs/guides/instrumentation/otel.mdx
+++ b/docs/guides/instrumentation/otel.mdx
@@ -188,6 +188,26 @@ Gateway-routed model calls propagate the configured OpenTelemetry context at
each provider request. Eve-owned baggage is removed before forwarding. Gateway
controls whether its spans are sampled and which destinations receive them.
+When AI Gateway reports
+[session affinity](https://vercel.com/docs/ai-gateway/models-and-providers/session-affinity)
+for a model call, the `agent.step` span records it. These attributes appear even
+when the trace content policy omits outputs.
+
+`vercel.ai_gateway.client_session_id` is the session ID AI Gateway used for
+affinity. It is not the eve session ID that `vercel.session_id` records. It
+equals `gen_ai.conversation.id` unless you set `gateway.sessionId` yourself or
+the ID is longer than 256 characters, in which case AI Gateway hashes it. An
+authored `gateway.sessionId` is recorded verbatim, so don't put personal data in
+it.
+
+| Attribute | Value |
+| ----------------------------------------------- | --------------------------------------------------------------- |
+| `vercel.ai_gateway.client_session_id` | Session ID AI Gateway used |
+| `vercel.ai_gateway.client_session_id_source` | `explicit`, `agent`, or `fingerprint` |
+| `vercel.ai_gateway.affinity.outcome` | What affinity did, such as `promoted`, `confirmed`, or `no_pin` |
+| `vercel.ai_gateway.affinity.pinned_provider` | Provider the session's pin named |
+| `vercel.ai_gateway.affinity.displaced_provider` | Provider that would have gone first, when the pin moved it |
+
## Local traces
`eve dev` records local traces by default. Omitting
diff --git a/packages/eve/src/instrumentation/content.test.ts b/packages/eve/src/instrumentation/content.test.ts
index cf80e0e84..74e95685f 100644
--- a/packages/eve/src/instrumentation/content.test.ts
+++ b/packages/eve/src/instrumentation/content.test.ts
@@ -135,7 +135,16 @@ describe("withInstrumentationDecision", () => {
{
idempotencyKey: "attempt-1",
providerMetadata: {
- gateway: { cost: "0.01", generationId: "gen-1", secret: "hidden" },
+ gateway: {
+ cost: "0.01",
+ generationId: "gen-1",
+ routing: {
+ affinity: { outcome: "confirmed", pinnedProvider: "anthropic", secret: "hidden" },
+ clientSessionId: "conversation-1",
+ secret: "hidden",
+ },
+ secret: "hidden",
+ },
secret: "hidden",
},
scope,
@@ -146,7 +155,16 @@ describe("withInstrumentationDecision", () => {
expect(projected).toEqual(
expect.objectContaining({
- providerMetadata: { gateway: { cost: "0.01", generationId: "gen-1" } },
+ providerMetadata: {
+ gateway: {
+ cost: "0.01",
+ generationId: "gen-1",
+ routing: {
+ affinity: { outcome: "confirmed", pinnedProvider: "anthropic" },
+ clientSessionId: "conversation-1",
+ },
+ },
+ },
}),
);
});
diff --git a/packages/eve/src/instrumentation/content.ts b/packages/eve/src/instrumentation/content.ts
index ed08f7daa..07afe6e45 100644
--- a/packages/eve/src/instrumentation/content.ts
+++ b/packages/eve/src/instrumentation/content.ts
@@ -1,4 +1,5 @@
import type { InstrumentationEvent } from "#instrumentation/lifecycle.js";
+import { readGatewayRouting } from "#shared/gateway-routing.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
/** Returns an immutable event projection with conversation content removed. */
@@ -68,7 +69,7 @@ export function withInstrumentationDecision(
}
}
-/** Provider metadata fields that describe cost/identity rather than content. */
+/** Provider metadata fields that describe cost, identity, or routing rather than content. */
export function structuralProviderMetadata(
metadata: Readonly<Record<string, unknown>>,
): Readonly<Record<string, unknown>> {
@@ -77,11 +78,13 @@ export function structuralProviderMetadata(
return Object.freeze({});
}
const source = gateway as Readonly<Record<string, unknown>>;
- const structural: Record<string, string | number> = {};
+ const structural: Record<string, unknown> = {};
for (const key of ["cost", "generationId"] as const) {
const value = source[key];
if (typeof value === "string" || typeof value === "number") structural[key] = value;
}
+ const routing = readGatewayRouting(source["routing"]);
+ if (routing !== undefined) structural["routing"] = routing;
return Object.freeze(
Object.keys(structural).length === 0 ? {} : { gateway: Object.freeze(structural) },
);
diff --git a/packages/eve/src/instrumentation/lifecycle.ts b/packages/eve/src/instrumentation/lifecycle.ts
index f9ce0999e..ce1043742 100644
--- a/packages/eve/src/instrumentation/lifecycle.ts
+++ b/packages/eve/src/instrumentation/lifecycle.ts
@@ -407,8 +407,10 @@ export type InstrumentationStepAttemptTerminalEvent =
/**
* Provider metadata for one completed attempt, as reported by the AI SDK
- * (`StepResult.providerMetadata`). Carries Vercel AI Gateway cost data when
- * the request went through the gateway; absent for other providers.
+ * (`StepResult.providerMetadata`). Carries Vercel AI Gateway cost and session
+ * affinity routing data when the request went through the gateway; absent for
+ * other providers. When the trace policy omits outputs, only the gateway's
+ * `cost`, `generationId`, and `routing` fields remain.
*/
export interface InstrumentationStepAttemptMetadataEvent {
readonly type: "step.attempt.metadata";
diff --git a/packages/eve/src/shared/gateway-routing.ts b/packages/eve/src/shared/gateway-routing.ts
new file mode 100644
index 000000000..6db412fbb
--- /dev/null
+++ b/packages/eve/src/shared/gateway-routing.ts
@@ -0,0 +1,50 @@
+import { isObject, readNonEmptyString } from "#shared/guards.js";
+
+/**
+ * The session affinity report AI Gateway returns in `providerMetadata.gateway.routing`.
+ *
+ * Gateway documents that new `affinity.outcome` values may appear, so every
+ * field stays an open string.
+ */
+export interface GatewayRouting {
+ readonly clientSessionId?: string;
+ readonly clientSessionIdSource?: string;
+ readonly affinity?: {
+ readonly displacedProvider?: string;
+ readonly outcome?: string;
+ readonly pinnedProvider?: string;
+ };
+}
+
+/**
+ * Reads the session affinity fields from an unknown-shaped
+ * `providerMetadata.gateway.routing` value and drops every other key.
+ */
+export function readGatewayRouting(value: unknown): GatewayRouting | undefined {
+ if (!isObject(value)) return undefined;
+ const routing = value;
+ const affinitySource = isObject(routing.affinity) ? routing.affinity : undefined;
+ const affinity = pickStrings(affinitySource, [
+ "displacedProvider",
+ "outcome",
+ "pinnedProvider",
+ ] as const);
+ const result: { -readonly [K in keyof GatewayRouting]: GatewayRouting[K] } = {
+ ...pickStrings(routing, ["clientSessionId", "clientSessionIdSource"] as const),
+ };
+ if (affinity !== undefined) result.affinity = affinity;
+ return Object.keys(result).length === 0 ? undefined : result;
+}
+
+function pickStrings<const K extends string>(
+ source: Readonly<Record<string, unknown>> | undefined,
+ keys: readonly K[],
+): { [P in K]?: string } | undefined {
+ if (source === undefined) return undefined;
+ const picked: { [P in K]?: string } = {};
+ for (const key of keys) {
+ const value = readNonEmptyString(source[key]);
+ if (value !== undefined) picked[key] = value;
+ }
+ return Object.keys(picked).length === 0 ? undefined : picked;
+}
diff --git a/packages/eve/src/tracing/eve/agent-otel-provider.test.ts b/packages/eve/src/tracing/eve/agent-otel-provider.test.ts
index cae190b4a..b27d4f29c 100644
--- a/packages/eve/src/tracing/eve/agent-otel-provider.test.ts
+++ b/packages/eve/src/tracing/eve/agent-otel-provider.test.ts
@@ -3010,7 +3010,7 @@ describe("createAgentOtelInstrumentation", () => {
withSpy.mockRestore();
});
- it("writes gateway cost attributes on the step span when the gateway reports them", async () => {
+ it("writes gateway cost and session affinity attributes on the step span when the gateway reports them", async () => {
const runtime = createRuntime();
await emitAttempt({
hooks: runtime.hooks,
@@ -3021,6 +3021,15 @@ describe("createAgentOtelInstrumentation", () => {
generationId: "gen_01KYR80F7ZV4RM3PJ635KMXB5V",
inputInferenceCost: "0.000042",
outputInferenceCost: "0.00004",
+ routing: {
+ affinity: {
+ displacedProvider: "bedrock",
+ outcome: "promoted",
+ pinnedProvider: "anthropic",
+ },
+ clientSessionId: "conversation-1",
+ clientSessionIdSource: "explicit",
+ },
},
},
runInContext: runtime.runInContext,
@@ -3037,14 +3046,25 @@ describe("createAgentOtelInstrumentation", () => {
"gen_ai.usage.gateway_cost": 0.000182,
"gen_ai.usage.input_cost": 0.000042,
"gen_ai.usage.output_cost": 0.00004,
+ "vercel.ai_gateway.affinity.displaced_provider": "bedrock",
+ "vercel.ai_gateway.affinity.outcome": "promoted",
+ "vercel.ai_gateway.affinity.pinned_provider": "anthropic",
+ "vercel.ai_gateway.client_session_id": "conversation-1",
+ "vercel.ai_gateway.client_session_id_source": "explicit",
});
});
- it("emits no cost attributes when the provider is not the gateway", async () => {
+ it("emits no gateway attributes when the provider is not the gateway", async () => {
const runtime = createRuntime();
await emitAttempt({
hooks: runtime.hooks,
- providerMetadata: { anthropic: { cacheCreationInputTokens: 0 } },
+ providerMetadata: {
+ anthropic: {
+ cacheCreationInputTokens: 0,
+ cost: "0.01",
+ routing: { affinity: { outcome: "confirmed" }, clientSessionId: "conversation-1" },
+ },
+ },
runInContext: runtime.runInContext,
sessionId: "session-1",
turnId: "turn-1",
@@ -3056,6 +3076,7 @@ describe("createAgentOtelInstrumentation", () => {
const keys = Object.keys(step.attributes);
for (const key of keys) {
expect(key).not.toContain("cost");
+ expect(key).not.toContain("ai_gateway");
}
});
diff --git a/packages/eve/src/tracing/eve/agent-otel-provider.ts b/packages/eve/src/tracing/eve/agent-otel-provider.ts
index 5b640bf41..0f832252f 100644
--- a/packages/eve/src/tracing/eve/agent-otel-provider.ts
+++ b/packages/eve/src/tracing/eve/agent-otel-provider.ts
@@ -29,7 +29,7 @@ import type {
import { resolveInstrumentationEnvironment } from "#internal/application/dev-environment.js";
import type { ConversationEnvironment } from "#shared/conversation-context.js";
import { createEveTracing } from "#tracing/eve/operation-input.js";
-import { gatewayCostAttributes } from "#tracing/eve/gateway.js";
+import { gatewayCostAttributes, gatewayRoutingAttributes } from "#tracing/eve/gateway.js";
import type {
AgentSpanIdGenerator,
AgentTelemetry,
@@ -222,10 +222,12 @@ export function createAgentOtelInstrumentation(
const onStepMetadata = (event: InstrumentationStepAttemptMetadataEvent): void => {
const attempt = steps.get(event.scope.attemptId);
if (attempt === undefined) return;
- // Vercel AI Gateway reports per-call cost in providerMetadata.gateway;
+ // Vercel AI Gateway reports per-call cost and session affinity routing in providerMetadata.gateway;
// attributes exist only when it was actually the gateway serving the call.
const cost = readGatewayCostData(event.providerMetadata);
if (cost !== undefined) attempt.attributes(gatewayCostAttributes(cost));
+ const routing = gatewayRoutingAttributes(event.providerMetadata);
+ if (routing !== undefined) attempt.attributes(routing);
};
return {
diff --git a/packages/eve/src/tracing/eve/gateway.ts b/packages/eve/src/tracing/eve/gateway.ts
index 950a937eb..7c1cefc32 100644
--- a/packages/eve/src/tracing/eve/gateway.ts
+++ b/packages/eve/src/tracing/eve/gateway.ts
@@ -8,6 +8,8 @@ import {
} from "#compiled/@opentelemetry/api/index.js";
import { stripEveTraceBaggage } from "#protocol/baggage.js";
+import { readGatewayRouting } from "#shared/gateway-routing.js";
+import { isObject } from "#shared/guards.js";
const SUPPRESS_TRACING_KEY = createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
const traceContextSetter: TextMapSetter<Record<string, string>> = {
@@ -66,6 +68,25 @@ export function readGatewayCostData(
};
}
+/**
+ * Converts Gateway session affinity metadata to span attributes, so a step can
+ * be matched to its session in the Gateway logs Sessions view.
+ */
+export function gatewayRoutingAttributes(
+ providerMetadata: Readonly<Record<string, unknown>> | undefined,
+): Attributes | undefined {
+ const gateway = providerMetadata?.gateway;
+ const routing = readGatewayRouting(isObject(gateway) ? gateway.routing : undefined);
+ if (routing === undefined) return undefined;
+ return {
+ "vercel.ai_gateway.client_session_id": routing.clientSessionId,
+ "vercel.ai_gateway.client_session_id_source": routing.clientSessionIdSource,
+ "vercel.ai_gateway.affinity.outcome": routing.affinity?.outcome,
+ "vercel.ai_gateway.affinity.pinned_provider": routing.affinity?.pinnedProvider,
+ "vercel.ai_gateway.affinity.displaced_provider": routing.affinity?.displacedProvider,
+ };
+}
+
function readUsd(value: unknown): number | undefined {
if (typeof value !== "string" || value.trim() === "") return undefined;
const parsed = Number(value);