Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(api): allow selective expansion of metadata on observations-v2 endpoints (#11416)

Valery Meleshkinfa072d0074b5
diff --git a/fern/apis/server/definition/observations-v2.yml b/fern/apis/server/definition/observations-v2.yml
index 8b8e5d1bce..6d5638ca49 100644
--- a/fern/apis/server/definition/observations-v2.yml
+++ b/fern/apis/server/definition/observations-v2.yml
@@ -20,7 +20,7 @@ service:
- `basic` - name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId
- `time` - completionStartTime, createdAt, updatedAt
- `io` - input, output
- - `metadata` - metadata
+ - `metadata` - metadata (truncated to 200 chars by default, use `expandMetadata` to get full values)
- `model` - providedModelName, internalModelId, modelParameters
- `usage` - usageDetails, costDetails, totalCost
- `prompt` - promptId, promptName, promptVersion
@@ -43,6 +43,13 @@ service:
Available groups: core, basic, time, io, metadata, model, usage, prompt, metrics.
If not specified, `core` and `basic` field groups are returned.
Example: "basic,usage,model"
+ expandMetadata:
+ type: optional<string>
+ docs: |
+ Comma-separated list of metadata keys to return non-truncated.
+ By default, metadata values over 200 characters are truncated.
+ Use this parameter to retrieve full values for specific keys.
+ Example: "key1,key2"
limit:
type: optional<integer>
docs: Number of items to return per page. Maximum 1000, default 50.
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
index ec2fc1f3fa..b6745e698e 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
@@ -504,6 +504,8 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
typeof EVENTS_FIELDS
> {
private ioFields: { truncated: boolean; charLimit?: number } | null = null;
+ // Metadata expansion config: null = use truncated (default), string[] = expand specific keys, empty array = expand all
+ private metadataExpansionKeys: string[] | null = null;
/**
* Constructor
@@ -520,6 +522,23 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
super(EVENTS_FIELDS, options);
}
+ /**
+ * Select metadata with expanded values for specified keys.
+ * Expands truncated metadata values by coalescing with metadata_long_values.
+ *
+ * @param keys - Keys to expand. Only the specified keys will have their full values returned.
+ *
+ * @example
+ * // Expand specific keys only
+ * builder.selectMetadataExpanded(['transcript', 'transitions'])
+ */
+ selectMetadataExpanded(keys: string[]): this {
+ this.metadataExpansionKeys = keys;
+ // Also ensure metadata is in the select fields (will be replaced in buildSelectClause)
+ this.selectFields.add("metadata");
+ return this;
+ }
+
/**
* Add SELECT fields from predefined field sets
*/
@@ -547,10 +566,22 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
*/
protected buildSelectClause(): string {
// Build field expressions from field keys
- // If ioFields are configured, exclude regular input/output from selectFields
- const fieldsToProcess = this.ioFields
- ? [...this.selectFields].filter((f) => f !== "input" && f !== "output")
- : [...this.selectFields];
+ // Exclude fields that have custom handling (IO, metadata)
+ let fieldsToExclude: string[] = [];
+ if (this.ioFields) {
+ fieldsToExclude.push("input", "output");
+ }
+ // Only exclude metadata if we have actual keys to expand
+ if (
+ this.metadataExpansionKeys !== null &&
+ this.metadataExpansionKeys.length > 0
+ ) {
+ fieldsToExclude.push("metadata");
+ }
+
+ const fieldsToProcess = [...this.selectFields].filter(
+ (f) => !fieldsToExclude.includes(f),
+ );
const fieldExpressions: string[] = fieldsToProcess.flatMap((fieldKey) => {
const fieldExpr = EVENTS_FIELDS[fieldKey as keyof typeof EVENTS_FIELDS];
@@ -568,6 +599,30 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
}
}
+ // Add metadata field with expansion if configured
+ if (
+ this.metadataExpansionKeys !== null &&
+ this.metadataExpansionKeys.length > 0 &&
+ this.selectFields.has("metadata")
+ ) {
+ // Add keys to params for safe parameterized query
+ this.params.expandMetadataKeys = this.metadataExpansionKeys;
+
+ fieldExpressions.push(`mapFromArrays(
+ e.metadata_names,
+ arrayMap(
+ (name, prefix, hash) -> if(
+ has({expandMetadataKeys: Array(String)}, name) AND isNotNull(hash) AND mapContains(e.metadata_long_values, hash),
+ e.metadata_long_values[hash],
+ prefix
+ ),
+ e.metadata_names,
+ e.metadata_prefixes,
+ e.metadata_hashes
+ )
+ ) as metadata`);
+ }
+
return `SELECT\n ${fieldExpressions.join(",\n ")}`;
}
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index ce4064189d..70af38be28 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -702,6 +702,12 @@ type PublicApiObservationsQuery = {
lastId: string;
};
fields?: ObservationFieldGroup[] | null;
+ /**
+ * Metadata keys to expand (return full non-truncated values).
+ * - null/undefined: use truncated metadata (default behavior)
+ * - string[]: expand specified keys (or all keys if empty array)
+ */
+ expandMetadataKeys?: string[] | null;
};
function buildObservationsQueryBase(
@@ -903,7 +909,7 @@ export const getObservationsFromEventsTableForPublicApi = async (
export const getObservationsV2FromEventsTableForPublicApi = async (
opts: PublicApiObservationsQuery & { fields: ObservationFieldGroup[] },
): Promise<Array<EventsObservationPublic>> => {
- const { projectId } = opts;
+ const { projectId, expandMetadataKeys } = opts;
// Build query with filters and common CTEs
let queryBuilder = buildObservationsQueryBase(
@@ -925,6 +931,14 @@ export const getObservationsV2FromEventsTableForPublicApi = async (
queryBuilder.selectFieldSet(fieldGroup);
});
+ // Handle metadata field with optional expansion
+ if (requestedFields.includes("metadata")) {
+ if (expandMetadataKeys && expandMetadataKeys.length > 0) {
+ // Use expanded metadata (coalesces truncated values with full values)
+ queryBuilder.selectMetadataExpanded(expandMetadataKeys);
+ }
+ }
+
queryBuilder = applyCursorPagination(
opts,
applyOrderByForObservationsQuery(queryBuilder),
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index e4c4f46ea0..1a0ff40910 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -2582,7 +2582,8 @@ paths:
- `io` - input, output
- - `metadata` - metadata
+ - `metadata` - metadata (truncated to 200 chars by default, use
+ `expandMetadata` to get full values)
- `model` - providedModelName, internalModelId, modelParameters
@@ -2622,6 +2623,17 @@ paths:
schema:
type: string
nullable: true
+ - name: expandMetadata
+ in: query
+ description: |-
+ Comma-separated list of metadata keys to return non-truncated.
+ By default, metadata values over 200 characters are truncated.
+ Use this parameter to retrieve full values for specific keys.
+ Example: "key1,key2"
+ required: false
+ schema:
+ type: string
+ nullable: true
- name: limit
in: query
description: Number of items to return per page. Maximum 1000, default 50.
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 9cdd110faf..9af498f40d 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -1758,9 +1758,9 @@
"_type": "endpoint",
"name": "Get Many",
"request": {
- "description": "Get a list of observations with cursor-based pagination and flexible field selection.\n\n## Cursor-based Pagination\nThis endpoint uses cursor-based pagination for efficient traversal of large datasets.\nThe cursor is returned in the response metadata and should be passed in subsequent requests\nto retrieve the next page of results.\n\n## Field Selection\nUse the `fields` parameter to control which observation fields are returned:\n- `core` - Always included: id, traceId, startTime, endTime, projectId, parentObservationId, type\n- `basic` - name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId\n- `time` - completionStartTime, createdAt, updatedAt\n- `io` - input, output\n- `metadata` - metadata\n- `model` - providedModelName, internalModelId, modelParameters\n- `usage` - usageDetails, costDetails, totalCost\n- `prompt` - promptId, promptName, promptVersion\n- `metrics` - latency, timeToFirstToken\n\nIf not specified, `core` and `basic` field groups are returned.\n\n## Filters\nMultiple filtering options are available via query parameters or the structured `filter` parameter.\nWhen using the `filter` parameter, it takes precedence over individual query parameter filters.",
+ "description": "Get a list of observations with cursor-based pagination and flexible field selection.\n\n## Cursor-based Pagination\nThis endpoint uses cursor-based pagination for efficient traversal of large datasets.\nThe cursor is returned in the response metadata and should be passed in subsequent requests\nto retrieve the next page of results.\n\n## Field Selection\nUse the `fields` parameter to control which observation fields are returned:\n- `core` - Always included: id, traceId, startTime, endTime, projectId, parentObservationId, type\n- `basic` - name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId\n- `time` - completionStartTime, createdAt, updatedAt\n- `io` - input, output\n- `metadata` - metadata (truncated to 200 chars by default, use `expandMetadata` to get full values)\n- `model` - providedModelName, internalModelId, modelParameters\n- `usage` - usageDetails, costDetails, totalCost\n- `prompt` - promptId, promptName, promptVersion\n- `metrics` - latency, timeToFirstToken\n\nIf not specified, `core` and `basic` field groups are returned.\n\n## Filters\nMultiple filtering options are available via query parameters or the structured `filter` parameter.\nWhen using the `filter` parameter, it takes precedence over individual query parameter filters.",
"url": {
- "raw": "{{baseUrl}}/api/public/v2/observations?fields=&limit=&cursor=&parseIoAsJson=&name=&userId=&type=&traceId=&level=&parentObservationId=&environment=&fromStartTime=&toStartTime=&version=&filter=",
+ "raw": "{{baseUrl}}/api/public/v2/observations?fields=&expandMetadata=&limit=&cursor=&parseIoAsJson=&name=&userId=&type=&traceId=&level=&parentObservationId=&environment=&fromStartTime=&toStartTime=&version=&filter=",
"host": [
"{{baseUrl}}"
],
@@ -1776,6 +1776,11 @@
"value": "",
"description": "Comma-separated list of field groups to include in the response.\nAvailable groups: core, basic, time, io, metadata, model, usage, prompt, metrics.\nIf not specified, `core` and `basic` field groups are returned.\nExample: \"basic,usage,model\""
},
+ {
+ "key": "expandMetadata",
+ "value": "",
+ "description": "Comma-separated list of metadata keys to return non-truncated.\nBy default, metadata values over 200 characters are truncated.\nUse this parameter to retrieve full values for specific keys.\nExample: \"key1,key2\""
+ },
{
"key": "limit",
"value": "",
diff --git a/web/src/__tests__/async/observations-api-v2.servertest.ts b/web/src/__tests__/async/observations-api-v2.servertest.ts
index 373e9c9ac3..68ca561d27 100644
--- a/web/src/__tests__/async/observations-api-v2.servertest.ts
+++ b/web/src/__tests__/async/observations-api-v2.servertest.ts
@@ -504,6 +504,189 @@ describe("/api/public/v2/observations API Endpoint", () => {
});
});
+ maybe("Metadata expansion with expandMetadata parameter", () => {
+ // Cutoff is 200 chars - values longer than 200 chars are truncated by default
+ const METADATA_CUTOFF = 200;
+
+ it("should selectively expand only specified metadata keys", async () => {
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ // Create two long metadata values
+ const longValue1 = "a".repeat(300);
+ const longValue2 = "b".repeat(300);
+
+ const observation = createEvent({
+ id: observationId,
+ span_id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "selective-expansion-test",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue,
+ metadata: {
+ expandMe: longValue1,
+ keepTruncated: longValue2,
+ shortKey: "shortValue",
+ },
+ metadata_names: ["expandMe", "keepTruncated", "shortKey"],
+ metadata_raw_values: [longValue1, longValue2, "shortValue"],
+ });
+
+ await createEventsCh([observation]);
+
+ // Wait for ClickHouse to process
+ await waitForExpect(
+ async () => {
+ const result = await queryClickhouse<{ count: string }>({
+ query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id = {id: String}`,
+ params: { projectId, id: observationId },
+ });
+ expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(1);
+ },
+ 5000,
+ 10,
+ );
+
+ // Request metadata with expansion for only 'expandMe' key
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&fields=metadata&expandMetadata=expandMe`,
+ );
+
+ expect(response.status).toBe(200);
+ const obs = response.body.data.find((o: any) => o.id === observationId);
+ expect(obs).toBeDefined();
+
+ // 'expandMe' should be full (300 chars)
+ expect(obs?.metadata?.expandMe?.length).toBe(300);
+ expect(obs?.metadata?.expandMe).toBe(longValue1);
+
+ // 'keepTruncated' should still be truncated (200 chars)
+ expect(obs?.metadata?.keepTruncated?.length).toBe(METADATA_CUTOFF);
+ expect(obs?.metadata?.keepTruncated).toBe(
+ longValue2.substring(0, METADATA_CUTOFF),
+ );
+
+ // 'shortValue' should be present as is
+ expect(obs?.metadata?.shortKey).toBe("shortValue");
+ });
+
+ it("should handle expansion of non-existent metadata key gracefully", async () => {
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ const observation = createEvent({
+ id: observationId,
+ span_id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "non-existent-key-test",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue,
+ metadata: { existingKey: "value" },
+ metadata_names: ["existingKey"],
+ metadata_raw_values: ["value"],
+ });
+
+ await createEventsCh([observation]);
+
+ // Wait for ClickHouse to process
+ await waitForExpect(
+ async () => {
+ const result = await queryClickhouse<{ count: string }>({
+ query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id = {id: String}`,
+ params: { projectId, id: observationId },
+ });
+ expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(1);
+ },
+ 5000,
+ 10,
+ );
+
+ // Request expansion for a key that doesn't exist
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&fields=metadata&expandMetadata=nonExistentKey`,
+ );
+
+ // Should not error, just return metadata without the non-existent key
+ expect(response.status).toBe(200);
+ const obs = response.body.data.find((o: any) => o.id === observationId);
+ expect(obs).toBeDefined();
+
+ // Existing key should still be present
+ expect(obs?.metadata?.existingKey).toBe("value");
+ // Non-existent key should not be in metadata
+ expect(obs?.metadata?.nonExistentKey).toBeUndefined();
+ });
+
+ it("should return truncated metadata when expandMetadata is empty string", async () => {
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ // Create a long metadata value (> 200 chars)
+ const longValue = "z".repeat(300);
+
+ const observation = createEvent({
+ id: observationId,
+ span_id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "empty-expansion-test",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue,
+ metadata: { longKey: longValue },
+ metadata_names: ["longKey"],
+ metadata_raw_values: [longValue],
+ });
+
+ await createEventsCh([observation]);
+
+ // Wait for ClickHouse to process
+ await waitForExpect(
+ async () => {
+ const result = await queryClickhouse<{ count: string }>({
+ query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id = {id: String}`,
+ params: { projectId, id: observationId },
+ });
+ expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(1);
+ },
+ 5000,
+ 10,
+ );
+
+ // Request metadata with empty expandMetadata - should use truncated
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&fields=metadata&expandMetadata=`,
+ );
+
+ expect(response.status).toBe(200);
+ const obs = response.body.data.find((o: any) => o.id === observationId);
+ expect(obs).toBeDefined();
+
+ // Metadata should still be present but truncated (empty expandMetadata means no expansion)
+ expect(obs?.metadata?.longKey).toBeDefined();
+ expect(obs?.metadata?.longKey?.length).toBe(METADATA_CUTOFF);
+ expect(obs?.metadata?.longKey).toBe(
+ longValue.substring(0, METADATA_CUTOFF),
+ );
+ });
+ });
+
maybe("Cursor-based pagination", () => {
it("should return cursor when results equal limit", async () => {
const traceId = randomUUID();
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
index 443d54708f..cd6ad3880f 100644
--- a/web/src/features/public-api/types/observations.ts
+++ b/web/src/features/public-api/types/observations.ts
@@ -284,6 +284,7 @@ export const encodeCursor = (
// GET /v2/observations
export const GetObservationsV2Query = z.object({
// Field groups parameter (optional - defaults to all groups)
+ // Comma-separated list of field groups: fields=basic,metadata,io
fields: z
.string()
.nullish()
@@ -292,11 +293,25 @@ export const GetObservationsV2Query = z.object({
return v
.split(",")
.map((f) => f.trim())
- .filter((f) =>
+ .filter((f): f is ObservationFieldGroup =>
OBSERVATION_FIELD_GROUPS.includes(f as ObservationFieldGroup),
);
})
.pipe(z.array(z.enum(OBSERVATION_FIELD_GROUPS)).nullable()),
+ // Metadata expansion keys (optional)
+ // Comma-separated list of metadata keys to return non-truncated: expandMetadata=transcript,steps
+ expandMetadata: z
+ .string()
+ .nullish()
+ .transform((v) => {
+ if (!v) return null;
+ const keys = v
+ .split(",")
+ .map((k) => k.trim())
+ .filter((k) => k.length > 0);
+ return keys.length > 0 ? keys : null;
+ })
+ .pipe(z.array(z.string()).nullable()),
// Pagination
limit: z.coerce.number().nonnegative().lte(1000).default(50),
cursor: EncodedObservationsCursorV2.optional(),
diff --git a/web/src/pages/api/public/v2/observations/index.ts b/web/src/pages/api/public/v2/observations/index.ts
index 91fed2ff5d..a7282af21b 100644
--- a/web/src/pages/api/public/v2/observations/index.ts
+++ b/web/src/pages/api/public/v2/observations/index.ts
@@ -23,6 +23,10 @@ export default withMiddlewares({
);
}
+ // Extract field groups and metadata expansion keys
+ const fieldGroups = query.fields ?? undefined;
+ const expandMetadataKeys = query.expandMetadata ?? undefined;
+
const filterProps = {
projectId: auth.scope.projectId,
page: 0, // v2 doesn't use page-based pagination
@@ -40,7 +44,8 @@ export default withMiddlewares({
advancedFilters: query.filter,
parseIoAsJson: query.parseIoAsJson ?? false,
cursor: query.cursor ?? undefined,
- fields: query.fields ?? undefined,
+ fields: fieldGroups,
+ expandMetadataKeys,
};
// Fetch observations from events table with field groups applied at query time