Skip to content

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

sdk improvements

Max Deichmann4c5a9dee7c29
diff --git a/fern/api/definition/span.yml b/fern/api/definition/span.yml
index f586ef0432..0086b920bd 100644
--- a/fern/api/definition/span.yml
+++ b/fern/api/definition/span.yml
@@ -10,6 +10,12 @@ service:
path: /llm-span
request: CreateLLMSpanRequest
response: Span
+ updateLLMCall:
+ docs: Update a span to the database
+ method: PATCH
+ path: /llm-span
+ request: UpdateLLMSpanRequest
+ response: Span
create:
docs: Add a span to the database
method: POST
@@ -37,6 +43,12 @@ types:
spanId: string
endTime: datetime
+ UpdateLLMSpanRequest:
+ properties:
+ spanId: string
+ endTime: datetime
+ attributes: LLMAttributes
+
Span:
properties:
id: string
@@ -53,15 +65,15 @@ types:
traceId: string
name: string
startTime: datetime
- attributes: LLMAttributes
parentObservationId: optional<string>
+ attributes: LLMAttributes
LLMAttributes:
properties:
model: unknown
prompt: optional<string>
completion: optional<string>
- tokens: LLMTokens
+ tokens: optional<LLMTokens>
LLMTokens:
properties:
diff --git a/generated/openapi/openapi.yml b/generated/openapi/openapi.yml
index 6f04b922e7..67d4c50c41 100644
--- a/generated/openapi/openapi.yml
+++ b/generated/openapi/openapi.yml
@@ -63,6 +63,25 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/CreateLLMSpanRequest'
+ patch:
+ description: Update a span to the database
+ operationId: span_updateLLMCall
+ tags:
+ - Span
+ parameters: []
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Span'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UpdateLLMSpanRequest'
/api/spans:
post:
description: Add a span to the database
@@ -254,6 +273,21 @@ components:
required:
- spanId
- endTime
+ UpdateLLMSpanRequest:
+ title: UpdateLLMSpanRequest
+ type: object
+ properties:
+ spanId:
+ type: string
+ endTime:
+ type: string
+ format: date-time
+ attributes:
+ $ref: '#/components/schemas/LLMAttributes'
+ required:
+ - spanId
+ - endTime
+ - attributes
Span:
title: Span
type: object
@@ -293,10 +327,10 @@ components:
startTime:
type: string
format: date-time
- attributes:
- $ref: '#/components/schemas/LLMAttributes'
parentObservationId:
type: string
+ attributes:
+ $ref: '#/components/schemas/LLMAttributes'
required:
- traceId
- name
@@ -315,7 +349,6 @@ components:
$ref: '#/components/schemas/LLMTokens'
required:
- model
- - tokens
LLMTokens:
title: LLMTokens
type: object
diff --git a/generated/python/__init__.py b/generated/python/__init__.py
index 430bafd428..d0466258e7 100644
--- a/generated/python/__init__.py
+++ b/generated/python/__init__.py
@@ -12,6 +12,7 @@ from .resources import (
Score,
Span,
Trace,
+ UpdateLLMSpanRequest,
UpdateSpanRequest,
UpdateTraceRequest,
event,
@@ -32,6 +33,7 @@ __all__ = [
"Score",
"Span",
"Trace",
+ "UpdateLLMSpanRequest",
"UpdateSpanRequest",
"UpdateTraceRequest",
"event",
diff --git a/generated/python/resources/__init__.py b/generated/python/resources/__init__.py
index 2f7a0ac78f..70c6d3e9cb 100644
--- a/generated/python/resources/__init__.py
+++ b/generated/python/resources/__init__.py
@@ -3,7 +3,15 @@
from . import event, score, span, trace
from .event import CreateEventRequest, Event
from .score import CreateScoreRequest, Score
-from .span import CreateLLMSpanRequest, CreateSpanRequest, LLMAttributes, LLMTokens, Span, UpdateSpanRequest
+from .span import (
+ CreateLLMSpanRequest,
+ CreateSpanRequest,
+ LLMAttributes,
+ LLMTokens,
+ Span,
+ UpdateLLMSpanRequest,
+ UpdateSpanRequest,
+)
from .trace import CreateTraceRequest, Trace, UpdateTraceRequest
__all__ = [
@@ -18,6 +26,7 @@ __all__ = [
"Score",
"Span",
"Trace",
+ "UpdateLLMSpanRequest",
"UpdateSpanRequest",
"UpdateTraceRequest",
"event",
diff --git a/generated/python/resources/span/__init__.py b/generated/python/resources/span/__init__.py
index e86b80b7b3..8d4b949ac7 100644
--- a/generated/python/resources/span/__init__.py
+++ b/generated/python/resources/span/__init__.py
@@ -1,5 +1,21 @@
# This file was auto-generated by Fern from our API Definition.
-from .types import CreateLLMSpanRequest, CreateSpanRequest, LLMAttributes, LLMTokens, Span, UpdateSpanRequest
+from .types import (
+ CreateLLMSpanRequest,
+ CreateSpanRequest,
+ LLMAttributes,
+ LLMTokens,
+ Span,
+ UpdateLLMSpanRequest,
+ UpdateSpanRequest,
+)
-__all__ = ["CreateLLMSpanRequest", "CreateSpanRequest", "LLMAttributes", "LLMTokens", "Span", "UpdateSpanRequest"]
+__all__ = [
+ "CreateLLMSpanRequest",
+ "CreateSpanRequest",
+ "LLMAttributes",
+ "LLMTokens",
+ "Span",
+ "UpdateLLMSpanRequest",
+ "UpdateSpanRequest",
+]
diff --git a/generated/python/resources/span/client.py b/generated/python/resources/span/client.py
index 8b9219e2dd..201b7ec929 100644
--- a/generated/python/resources/span/client.py
+++ b/generated/python/resources/span/client.py
@@ -12,6 +12,7 @@ from ...environment import FintoLangfuseEnvironment
from .types.create_llm_span_request import CreateLLMSpanRequest
from .types.create_span_request import CreateSpanRequest
from .types.span import Span
+from .types.update_llm_span_request import UpdateLLMSpanRequest
from .types.update_span_request import UpdateSpanRequest
@@ -31,6 +32,18 @@ class SpanClient:
raise ApiError(status_code=_response.status_code, body=_response.text)
raise ApiError(status_code=_response.status_code, body=_response_json)
+ def update_llm_call(self, *, request: UpdateLLMSpanRequest) -> Span:
+ _response = httpx.request(
+ "PATCH", urllib.parse.urljoin(f"{self._environment}/", "api/llm-span"), json=jsonable_encoder(request)
+ )
+ if 200 <= _response.status_code < 300:
+ return pydantic.parse_obj_as(Span, _response.json()) # type: ignore
+ try:
+ _response_json = _response.json()
+ except JSONDecodeError:
+ raise ApiError(status_code=_response.status_code, body=_response.text)
+ raise ApiError(status_code=_response.status_code, body=_response_json)
+
def create(self, *, request: CreateSpanRequest) -> Span:
_response = httpx.request(
"POST", urllib.parse.urljoin(f"{self._environment}/", "api/spans"), json=jsonable_encoder(request)
diff --git a/generated/python/resources/span/types/__init__.py b/generated/python/resources/span/types/__init__.py
index 02b40f9531..0e8489a87e 100644
--- a/generated/python/resources/span/types/__init__.py
+++ b/generated/python/resources/span/types/__init__.py
@@ -5,6 +5,15 @@ from .create_span_request import CreateSpanRequest
from .llm_attributes import LLMAttributes
from .llm_tokens import LLMTokens
from .span import Span
+from .update_llm_span_request import UpdateLLMSpanRequest
from .update_span_request import UpdateSpanRequest
-__all__ = ["CreateLLMSpanRequest", "CreateSpanRequest", "LLMAttributes", "LLMTokens", "Span", "UpdateSpanRequest"]
+__all__ = [
+ "CreateLLMSpanRequest",
+ "CreateSpanRequest",
+ "LLMAttributes",
+ "LLMTokens",
+ "Span",
+ "UpdateLLMSpanRequest",
+ "UpdateSpanRequest",
+]
diff --git a/generated/python/resources/span/types/create_llm_span_request.py b/generated/python/resources/span/types/create_llm_span_request.py
index 483e2b48a1..c223718de7 100644
--- a/generated/python/resources/span/types/create_llm_span_request.py
+++ b/generated/python/resources/span/types/create_llm_span_request.py
@@ -13,8 +13,8 @@ class CreateLLMSpanRequest(pydantic.BaseModel):
trace_id: str = pydantic.Field(alias="traceId")
name: str
start_time: dt.datetime = pydantic.Field(alias="startTime")
- attributes: LLMAttributes
parent_observation_id: typing.Optional[str] = pydantic.Field(alias="parentObservationId")
+ attributes: LLMAttributes
def json(self, **kwargs: typing.Any) -> str:
kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs}
diff --git a/generated/python/resources/span/types/llm_attributes.py b/generated/python/resources/span/types/llm_attributes.py
index f359b6e87a..2e42cfc6f5 100644
--- a/generated/python/resources/span/types/llm_attributes.py
+++ b/generated/python/resources/span/types/llm_attributes.py
@@ -13,7 +13,7 @@ class LLMAttributes(pydantic.BaseModel):
model: typing.Any
prompt: typing.Optional[str]
completion: typing.Optional[str]
- tokens: LLMTokens
+ tokens: typing.Optional[LLMTokens]
def json(self, **kwargs: typing.Any) -> str:
kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs}
diff --git a/generated/python/resources/span/types/update_llm_span_request.py b/generated/python/resources/span/types/update_llm_span_request.py
new file mode 100644
index 0000000000..a9307b9dc6
--- /dev/null
+++ b/generated/python/resources/span/types/update_llm_span_request.py
@@ -0,0 +1,28 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import datetime as dt
+import typing
+
+import pydantic
+
+from ....core.datetime_utils import serialize_datetime
+from .llm_attributes import LLMAttributes
+
+
+class UpdateLLMSpanRequest(pydantic.BaseModel):
+ span_id: str = pydantic.Field(alias="spanId")
+ end_time: dt.datetime = pydantic.Field(alias="endTime")
+ attributes: LLMAttributes
+
+ def json(self, **kwargs: typing.Any) -> str:
+ kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs}
+ return super().json(**kwargs_with_defaults)
+
+ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]:
+ kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs}
+ return super().dict(**kwargs_with_defaults)
+
+ class Config:
+ frozen = True
+ allow_population_by_field_name = True
+ json_encoders = {dt.datetime: serialize_datetime}
diff --git a/package-lock.json b/package-lock.json
index 08ac939a34..03f9e702a6 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -29,10 +29,12 @@
"@trpc/server": "^10.27.1",
"@types/cors": "^2.8.13",
"@types/js-yaml": "^4.0.5",
+ "@types/lodash": "^4.14.194",
"class-variance-authority": "^0.6.0",
"clsx": "^1.2.1",
"cors": "^2.8.5",
"js-yaml": "^4.1.0",
+ "lodash": "^4.17.21",
"lucide-react": "^0.220.0",
"next": "^13.4.3",
"next-auth": "^4.22.1",
@@ -2036,6 +2038,11 @@
"integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==",
"dev": true
},
+ "node_modules/@types/lodash": {
+ "version": "4.14.194",
+ "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.194.tgz",
+ "integrity": "sha512-r22s9tAS7imvBt2lyHC9B8AGwWnXaYb1tY09oyLkXDs4vArpYJzw09nj8MLx5VfciBPGIb+ZwG0ssYnEPJxn/g=="
+ },
"node_modules/@types/node": {
"version": "20.2.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.2.3.tgz",
diff --git a/package.json b/package.json
index a5b9318e4d..213630bbf6 100644
--- a/package.json
+++ b/package.json
@@ -34,10 +34,12 @@
"@trpc/server": "^10.27.1",
"@types/cors": "^2.8.13",
"@types/js-yaml": "^4.0.5",
+ "@types/lodash": "^4.14.194",
"class-variance-authority": "^0.6.0",
"clsx": "^1.2.1",
"cors": "^2.8.5",
"js-yaml": "^4.1.0",
+ "lodash": "^4.17.21",
"lucide-react": "^0.220.0",
"next": "^13.4.3",
"next-auth": "^4.22.1",
diff --git a/src/pages/api/llm-span.ts b/src/pages/api/llm-span.ts
index 63ee74e422..a0f157cd38 100644
--- a/src/pages/api/llm-span.ts
+++ b/src/pages/api/llm-span.ts
@@ -1,30 +1,40 @@
import { prisma } from "@/src/server/db";
-import { ObservationType } from "@prisma/client";
+import { ObservationType, type Prisma } from "@prisma/client";
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { cors, runMiddleware } from "./cors";
+import { merge } from "lodash";
-const SpanPostSchema = z.object({
+const LLMSpanCreateSchema = z.object({
traceId: z.string(),
name: z.string(),
startTime: z.string().datetime(),
- attributes: z.record(z.string(), z.any()),
+ attributes: z.object({
+ prompt: z.string().optional(),
+ completion: z.string().optional(),
+ tokens: z
+ .object({
+ prompt: z.number().optional(),
+ completion: z.number().optional(),
+ })
+ .optional(),
+ }),
parentObservationId: z.string().optional(),
});
-const LLMSpanCreateSchema = z.object({
- traceId: z.string(),
- name: z.string(),
- startTime: z.string().datetime(),
+const LLMSpanUpdateSchema = z.object({
+ spanId: z.string(),
+ endTime: z.string().datetime(),
attributes: z.object({
prompt: z.string().optional(),
completion: z.string().optional(),
- tokens: z.object({
- prompt: z.number().optional(),
- completion: z.number().optional(),
- }),
+ tokens: z
+ .object({
+ prompt: z.number().optional(),
+ completion: z.number().optional(),
+ })
+ .optional(),
}),
- parentObservationId: z.string().optional(),
});
export default async function handler(
@@ -33,35 +43,71 @@ export default async function handler(
) {
await runMiddleware(req, res, cors);
- if (req.method !== "POST") {
+ if (req.method !== "POST" && req.method !== "PATCH") {
return res.status(405).json({ message: "Method not allowed" });
}
- try {
- const { traceId, name, startTime, attributes, parentObservationId } =
- LLMSpanCreateSchema.parse(req.body);
+ if (req.method === "POST") {
+ try {
+ const { traceId, name, startTime, attributes, parentObservationId } =
+ LLMSpanCreateSchema.parse(req.body);
+
+ const newObservation = await prisma.observation.create({
+ data: {
+ trace: { connect: { id: traceId } },
+ type: ObservationType.LLMCALL,
+ name,
+ startTime: new Date(startTime),
+ attributes,
+ parent: parentObservationId
+ ? { connect: { id: parentObservationId } }
+ : undefined,
+ },
+ });
+
+ res.status(201).json(newObservation);
+ } catch (error: unknown) {
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(400).json({
+ success: false,
+ message: "Invalid request data",
+ error: errorMessage,
+ });
+ }
+ } else {
+ try {
+ const { spanId, endTime, attributes } = LLMSpanUpdateSchema.parse(
+ req.body
+ );
+
+ const existingObservation = await prisma.observation.findUnique({
+ where: { id: spanId },
+ });
+
+ if (!existingObservation) {
+ return res.status(404).json({ message: "Span not found" });
+ }
+
+ const mergedAttributes = merge(
+ existingObservation.attributes,
+ attributes
+ );
- const newObservation = await prisma.observation.create({
- data: {
- trace: { connect: { id: traceId } },
- type: ObservationType.LLMCALL,
- name,
- startTime: new Date(startTime),
- attributes,
- parent: parentObservationId
- ? { connect: { id: parentObservationId } }
- : undefined,
- },
- });
+ const newObservation = await prisma.observation.update({
+ where: { id: spanId },
+ data: { endTime: new Date(endTime), attributes: mergedAttributes },
+ });
- res.status(201).json(newObservation);
- } catch (error: unknown) {
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(400).json({
- success: false,
- message: "Invalid request data",
- error: errorMessage,
- });
+ res.status(201).json(newObservation);
+ } catch (error: unknown) {
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(400).json({
+ success: false,
+ message: "Invalid request data",
+ error: errorMessage,
+ });
+ }
}
}
diff --git a/src/pages/api/traces.ts b/src/pages/api/traces.ts
index 2ae8f2ffe9..d652c64d63 100644
--- a/src/pages/api/traces.ts
+++ b/src/pages/api/traces.ts
@@ -6,19 +6,13 @@ import { prisma } from "@/src/server/db";
const CreateTraceSchema = z.object({
name: z.string(),
attributes: z.record(z.string(), z.any()),
- status: z
- .literal("success")
- .or(z.literal("error"))
- .or(z.literal("executing")),
+ status: z.enum(["success", "error", "executing"]),
statusMessage: z.string().optional(),
});
const UpdateTraceSchema = z.object({
id: z.string(),
- status: z
- .literal("success")
- .or(z.literal("error"))
- .or(z.literal("executing")),
+ status: z.enum(["success", "error", "executing"]),
statusMessage: z.string().optional(),
});
@@ -29,6 +23,7 @@ export default async function handler(
await runMiddleware(req, res, cors);
if (req.method !== "POST" && req.method !== "PATCH") {
+ console.log(req.method, req.body);
return res.status(405).json({ message: "Method not allowed" });
}