Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: return formatted gen ai message in waterfall (#13121)

Nityananda Gohain3e087fe7bde0
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index f6cf85d530..e5066defae 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -10517,13 +10517,11 @@ components:
items:
$ref: '#/components/schemas/SpantypesEvent'
type: array
- formatted_input:
+ formattedInput:
$ref: '#/components/schemas/AiobservabilitytypesInputMessages'
- formatted_output:
+ formattedOutput:
$ref: '#/components/schemas/AiobservabilitytypesOutputMessages'
- formatter:
- type: string
- formatter_warnings:
+ formatterWarnings:
items:
type: string
type: array
@@ -10569,10 +10567,9 @@ components:
- attributes
- events
- references
- - formatted_input
- - formatted_output
- - formatter
- - formatter_warnings
+ - formattedInput
+ - formattedOutput
+ - formatterWarnings
type: object
SpantypesTraceAISummary:
properties:
@@ -10653,6 +10650,14 @@ components:
flags:
minimum: 0
type: integer
+ formattedInput:
+ $ref: '#/components/schemas/AiobservabilitytypesInputMessages'
+ formattedOutput:
+ $ref: '#/components/schemas/AiobservabilitytypesOutputMessages'
+ formatterWarnings:
+ items:
+ type: string
+ type: array
has_children:
type: boolean
has_error:
@@ -16442,10 +16447,10 @@ paths:
deprecated: false
description: Returns the gen_ai spans of a trace, model calls, tool calls and
agent spans, in timestamp order. The messages a span carries are decoded into
- formatted_input and formatted_output, with formatter naming the converter
- and formatter_warnings what it could not resolve; a span without messages
- has both empty. Pass nextCursor as after or prevCursor as before to page,
- or spanId to open the page around a span.
+ formattedInput and formattedOutput, with formatterWarnings holding what the
+ converter could not resolve; a span without messages has both empty. Pass
+ nextCursor as after or prevCursor as before to page, or spanId to open the
+ page around a span.
operationId: GetTraceThread
parameters:
- description: Page size, at most 100. 0 means 20.
@@ -28589,7 +28594,9 @@ paths:
deprecated: false
description: Returns the waterfall view of spans including all spans if total
spans are under a limit, a max count otherwise. Aggregations are dropped compared
- to v3
+ to v3. A span carrying gen_ai input or output messages also has them decoded
+ into formattedInput and formattedOutput, with formatterWarnings holding what
+ the converter could not resolve.
operationId: GetWaterfallV4
parameters:
- in: path
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index ba5674d1bc..9f39bb8f7c 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -11789,16 +11789,12 @@ export interface SpantypesThreadSpanDTO {
* @type array
*/
events: SpantypesEventDTO[];
- formatted_input: AiobservabilitytypesInputMessagesDTO;
- formatted_output: AiobservabilitytypesOutputMessagesDTO;
- /**
- * @type string
- */
- formatter: string;
+ formattedInput: AiobservabilitytypesInputMessagesDTO;
+ formattedOutput: AiobservabilitytypesOutputMessagesDTO;
/**
* @type array
*/
- formatter_warnings: string[];
+ formatterWarnings: string[];
/**
* @type boolean
*/
@@ -11914,6 +11910,12 @@ export interface SpantypesWaterfallSpanDTO {
* @minimum 0
*/
flags?: number;
+ formattedInput?: AiobservabilitytypesInputMessagesDTO;
+ formattedOutput?: AiobservabilitytypesOutputMessagesDTO;
+ /**
+ * @type array
+ */
+ formatterWarnings?: string[];
/**
* @type boolean
*/
diff --git a/frontend/src/api/generated/services/tracedetail/index.ts b/frontend/src/api/generated/services/tracedetail/index.ts
index 9bf78a15f1..162ff061ae 100644
--- a/frontend/src/api/generated/services/tracedetail/index.ts
+++ b/frontend/src/api/generated/services/tracedetail/index.ts
@@ -261,7 +261,7 @@ export const invalidateGetTraceSummary = async (
};
/**
- * Returns the gen_ai spans of a trace, model calls, tool calls and agent spans, in timestamp order. The messages a span carries are decoded into formatted_input and formatted_output, with formatter naming the converter and formatter_warnings what it could not resolve; a span without messages has both empty. Pass nextCursor as after or prevCursor as before to page, or spanId to open the page around a span.
+ * Returns the gen_ai spans of a trace, model calls, tool calls and agent spans, in timestamp order. The messages a span carries are decoded into formattedInput and formattedOutput, with formatterWarnings holding what the converter could not resolve; a span without messages has both empty. Pass nextCursor as after or prevCursor as before to page, or spanId to open the page around a span.
* @summary Get thread view for a trace
*/
export const getTraceThread = (
@@ -475,7 +475,7 @@ export const useGetFlamegraph = <
return useMutation(getGetFlamegraphMutationOptions(options));
};
/**
- * Returns the waterfall view of spans including all spans if total spans are under a limit, a max count otherwise. Aggregations are dropped compared to v3
+ * Returns the waterfall view of spans including all spans if total spans are under a limit, a max count otherwise. Aggregations are dropped compared to v3. A span carrying gen_ai input or output messages also has them decoded into formattedInput and formattedOutput, with formatterWarnings holding what the converter could not resolve.
* @summary Get waterfall view for a trace
*/
export const getWaterfallV4 = (
diff --git a/pkg/apiserver/signozapiserver/tracedetail.go b/pkg/apiserver/signozapiserver/tracedetail.go
index a582b140c5..0683560202 100644
--- a/pkg/apiserver/signozapiserver/tracedetail.go
+++ b/pkg/apiserver/signozapiserver/tracedetail.go
@@ -33,7 +33,7 @@ func (provider *provider) addTraceDetailRoutes(router *mux.Router) error {
ID: "GetWaterfallV4",
Tags: []string{"tracedetail"},
Summary: "Get waterfall view for a trace",
- Description: "Returns the waterfall view of spans including all spans if total spans are under a limit, a max count otherwise. Aggregations are dropped compared to v3",
+ Description: "Returns the waterfall view of spans including all spans if total spans are under a limit, a max count otherwise. Aggregations are dropped compared to v3. A span carrying gen_ai input or output messages also has them decoded into formattedInput and formattedOutput, with formatterWarnings holding what the converter could not resolve.",
Request: new(spantypes.PostableWaterfall),
RequestContentType: "application/json",
Response: new(spantypes.GettableWaterfallTrace),
@@ -90,7 +90,7 @@ func (provider *provider) addTraceDetailRoutes(router *mux.Router) error {
ID: "GetTraceThread",
Tags: []string{"tracedetail"},
Summary: "Get thread view for a trace",
- Description: "Returns the gen_ai spans of a trace, model calls, tool calls and agent spans, in timestamp order. The messages a span carries are decoded into formatted_input and formatted_output, with formatter naming the converter and formatter_warnings what it could not resolve; a span without messages has both empty. Pass nextCursor as after or prevCursor as before to page, or spanId to open the page around a span.",
+ Description: "Returns the gen_ai spans of a trace, model calls, tool calls and agent spans, in timestamp order. The messages a span carries are decoded into formattedInput and formattedOutput, with formatterWarnings holding what the converter could not resolve; a span without messages has both empty. Pass nextCursor as after or prevCursor as before to page, or spanId to open the page around a span.",
RequestQuery: new(spantypes.GetTraceThreadParams),
Response: new(spantypes.GettableTraceThread),
ResponseContentType: "application/json",
diff --git a/pkg/modules/tracedetail/impltracedetail/handler.go b/pkg/modules/tracedetail/impltracedetail/handler.go
index 34f23df31b..ff7f38b1af 100644
--- a/pkg/modules/tracedetail/impltracedetail/handler.go
+++ b/pkg/modules/tracedetail/impltracedetail/handler.go
@@ -37,6 +37,12 @@ func (h *handler) GetTraceSummary(rw http.ResponseWriter, r *http.Request) {
}
func (h *handler) GetWaterfallV4(rw http.ResponseWriter, r *http.Request) {
+ claims, err := authtypes.ClaimsFromContext(r.Context())
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
req := new(spantypes.PostableWaterfall)
if err := binding.JSON.BindBody(r.Body, req); err != nil {
render.Error(rw, err)
@@ -48,7 +54,7 @@ func (h *handler) GetWaterfallV4(rw http.ResponseWriter, r *http.Request) {
return
}
- result, err := h.module.GetWaterfallV4(r.Context(), mux.Vars(r)["traceID"], req.SelectedSpanID, req.UncollapsedSpans)
+ result, err := h.module.GetWaterfallV4(r.Context(), valuer.MustNewUUID(claims.OrgID), mux.Vars(r)["traceID"], req.SelectedSpanID, req.UncollapsedSpans)
if err != nil {
render.Error(rw, err)
return
diff --git a/pkg/modules/tracedetail/impltracedetail/module.go b/pkg/modules/tracedetail/impltracedetail/module.go
index 7f2738f8cc..b24014aa12 100644
--- a/pkg/modules/tracedetail/impltracedetail/module.go
+++ b/pkg/modules/tracedetail/impltracedetail/module.go
@@ -2,6 +2,7 @@ package impltracedetail
import (
"context"
+ "log/slog"
"time"
"github.com/SigNoz/signoz/pkg/factory"
@@ -12,6 +13,10 @@ import (
"go.opentelemetry.io/otel/metric"
)
+// formattedSpansLogThreshold is the number of formatted gen_ai spans in one waterfall response above which
+// the response is logged, to size the memory the formatted copies of the messages take.
+const formattedSpansLogThreshold = 200
+
type module struct {
store spantypes.TraceStore
settings factory.ScopedProviderSettings
@@ -59,22 +64,35 @@ func (m *module) GetTraceSummary(ctx context.Context, orgID valuer.UUID, traceID
// For large traces (NumSpans > effectiveLimit) it uses a two-step fetch:
// minimal fields for all spans to build the tree, then full fields for the
// visible window only. Aggregations are not returned.
-func (m *module) GetWaterfallV4(ctx context.Context, traceID string, selectedSpanID string, uncollapsedSpans []string) (*spantypes.GettableWaterfallTrace, error) {
+func (m *module) GetWaterfallV4(ctx context.Context, orgID valuer.UUID, traceID string, selectedSpanID string, uncollapsedSpans []string) (*spantypes.GettableWaterfallTrace, error) {
bounds, err := m.store.GetTraceBounds(ctx, traceID)
if err != nil {
return nil, err
}
- if bounds.NumSpans > uint64(m.config.Waterfall.MaxLimitToSelectAllSpans) {
+ windowed := bounds.NumSpans > uint64(m.config.Waterfall.MaxLimitToSelectAllSpans)
+ if windowed {
attrs := metric.WithAttributes(attrResponseType.String(attrResponseTypeWindowed))
m.metrics.waterfallRequestCount.Add(ctx, 1, attrs)
m.metrics.waterfallSpanCount.Add(ctx, int64(bounds.NumSpans), attrs)
- return m.getWindowedWaterfall(ctx, traceID, selectedSpanID, uncollapsedSpans, bounds.Start, bounds.End)
}
- return m.getFullWaterfall(ctx, traceID, bounds)
+
+ var trace *spantypes.GettableWaterfallTrace
+ if windowed {
+ trace, err = m.getWindowedWaterfall(ctx, orgID, traceID, selectedSpanID, uncollapsedSpans, bounds.Start, bounds.End)
+ } else {
+ trace, err = m.getFullWaterfall(ctx, orgID, traceID, bounds)
+ }
+ if err != nil {
+ return nil, err
+ }
+ if trace.FormattedSpans > formattedSpansLogThreshold {
+ m.settings.Logger().WarnContext(ctx, "waterfall response carries many formatted gen_ai spans", slog.String("trace_id", traceID), slog.Int("formatted_spans", trace.FormattedSpans), slog.Int("spans", len(trace.Spans)), slog.Bool("windowed", trace.HasMore))
+ }
+ return trace, nil
}
-func (m *module) getFullWaterfall(ctx context.Context, traceID string, bounds *spantypes.TraceBounds) (*spantypes.GettableWaterfallTrace, error) {
- spanItems, err := m.store.GetTraceSpans(ctx, traceID, bounds)
+func (m *module) getFullWaterfall(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.GettableWaterfallTrace, error) {
+ spanItems, err := m.store.GetTraceSpans(ctx, orgID, traceID, bounds)
if err != nil {
return nil, err
}
@@ -149,7 +167,7 @@ func (m *module) GetFlamegraph(ctx context.Context, traceID string, selectedSpan
}
// getWindowedWaterfall builds the waterfall tree with minimal data and then returns only a window of full spans.
-func (m *module) getWindowedWaterfall(ctx context.Context, traceID, selectedSpanID string, uncollapsedSpans []string, start, end time.Time) (*spantypes.GettableWaterfallTrace, error) {
+func (m *module) getWindowedWaterfall(ctx context.Context, orgID valuer.UUID, traceID, selectedSpanID string, uncollapsedSpans []string, start, end time.Time) (*spantypes.GettableWaterfallTrace, error) {
// Step 1: minimal fetch → build full tree → select visible window
minimalSpans, err := m.store.GetMinimalSpans(ctx, traceID, start, end)
if err != nil {
@@ -177,7 +195,7 @@ func (m *module) getWindowedWaterfall(ctx context.Context, traceID, selectedSpan
for i, s := range selectedSpans {
spanIDs[i] = s.SpanID
}
- fullSpans, err := m.store.GetTraceSpansByIDs(ctx, traceID, start, end, spanIDs)
+ fullSpans, err := m.store.GetTraceSpansByIDs(ctx, orgID, traceID, start, end, spanIDs)
if err != nil {
return nil, err
}
diff --git a/pkg/modules/tracedetail/impltracedetail/store.go b/pkg/modules/tracedetail/impltracedetail/store.go
index 70f8975bf4..cad38475dc 100644
--- a/pkg/modules/tracedetail/impltracedetail/store.go
+++ b/pkg/modules/tracedetail/impltracedetail/store.go
@@ -16,6 +16,7 @@ import (
"github.com/SigNoz/signoz/pkg/telemetryschema/tracestelemetryschema"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/types/aiobservabilitytypes"
+ "github.com/SigNoz/signoz/pkg/types/featuretypes"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/spantypes"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
@@ -24,6 +25,17 @@ import (
const colServiceName = `resource_string_service$$$$name` // $ gets escaped so $$$$ converts to $$.
+// storableSpanColumns are the columns a waterfall span scans; the JSON attributes column is added per flag.
+var storableSpanColumns = []string{
+ "DISTINCT ON (span_id) timestamp", "duration_nano", "span_id", "has_error", "kind",
+ colServiceName, "name",
+ "attributes_string", "attributes_number", "attributes_bool", "resources_string",
+ "events", "status_message", "status_code_string", "kind_string", "parent_span_id",
+ "flags", "is_remote", "trace_state", "status_code",
+ "db_name", "db_operation", "http_method", "http_url", "http_host",
+ "external_http_method", "external_http_url", "response_status_code", "links as references",
+}
+
func buildFieldExpr(fieldKey telemetrytypes.TelemetryFieldKey) (string, error) {
switch fieldKey.FieldContext {
case telemetrytypes.FieldContextResource:
@@ -195,33 +207,22 @@ func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bo
return columns, nil
}
-func (s *traceStore) GetTraceSpans(ctx context.Context, traceID string, bounds *spantypes.TraceBounds) ([]spantypes.StorableSpan, error) {
- // DISTINCT ON (span_id) is ClickHouse-specific syntax not supported by sqlbuilder
- query := fmt.Sprintf(`
- SELECT DISTINCT ON (span_id)
- timestamp, duration_nano, span_id, has_error, kind,
- resource_string_service$$name, name,
- attributes_string, attributes_number, attributes_bool, resources_string,
- events, status_message, status_code_string, kind_string, parent_span_id,
- flags, is_remote, trace_state, status_code,
- db_name, db_operation, http_method, http_url, http_host,
- external_http_method, external_http_url, response_status_code, links as references
- FROM %s.%s
- WHERE trace_id=? AND ts_bucket_start>=? AND ts_bucket_start<=?
- ORDER BY timestamp ASC, name ASC`,
- spantypes.TraceDB, spantypes.TraceTable,
- )
- var spanItems []spantypes.StorableSpan
- err := s.telemetryStore.ClickhouseDB().Select(
- ctx, &spanItems, query,
- traceID,
- bounds.Start.Unix()-1800,
- bounds.End.Unix(),
+func (s *traceStore) GetTraceSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) ([]spantypes.StorableSpan, error) {
+ sb := s.selectStorableSpans(ctx, orgID)
+ sb.Where(
+ sb.E("trace_id", traceID),
+ sb.GE("ts_bucket_start", bounds.Start.Unix()-1800),
+ sb.LE("ts_bucket_start", bounds.End.Unix()),
)
- if err != nil {
+ sb.OrderByAsc("timestamp")
+ sb.OrderByAsc("name")
+ query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
+
+ var spans []spantypes.StorableSpan
+ if err := s.telemetryStore.ClickhouseDB().Select(ctx, &spans, query, args...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace spans")
}
- return spanItems, nil
+ return spans, nil
}
func (s *traceStore) GetMinimalSpans(ctx context.Context, traceID string, start, end time.Time) ([]spantypes.MinimalSpan, error) {
@@ -248,21 +249,11 @@ func (s *traceStore) GetMinimalSpans(ctx context.Context, traceID string, start,
return spans, nil
}
-func (s *traceStore) GetTraceSpansByIDs(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]spantypes.StorableSpan, error) {
+func (s *traceStore) GetTraceSpansByIDs(ctx context.Context, orgID valuer.UUID, traceID string, start, end time.Time, spanIDs []string) ([]spantypes.StorableSpan, error) {
if len(spanIDs) == 0 {
return []spantypes.StorableSpan{}, nil
}
- sb := sqlbuilder.NewSelectBuilder()
- sb.Select(
- "DISTINCT ON (span_id) timestamp", "duration_nano", "span_id", "has_error", "kind",
- colServiceName, "name",
- "attributes_string", "attributes_number", "attributes_bool", "resources_string",
- "events", "status_message", "status_code_string", "kind_string", "parent_span_id",
- "flags", "is_remote", "trace_state", "status_code",
- "db_name", "db_operation", "http_method", "http_url", "http_host",
- "external_http_method", "external_http_url", "response_status_code", "links as references",
- )
- sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
+ sb := s.selectStorableSpans(ctx, orgID)
ids := make([]any, len(spanIDs))
for i, id := range spanIDs {
ids[i] = id
@@ -284,6 +275,18 @@ func (s *traceStore) GetTraceSpansByIDs(ctx context.Context, traceID string, sta
return spans, nil
}
+// selectStorableSpans reads the JSON attributes column alongside the legacy maps when the
+// use_trace_attributes_json flag is on, as the query builder does.
+func (s *traceStore) selectStorableSpans(ctx context.Context, orgID valuer.UUID) *sqlbuilder.SelectBuilder {
+ sb := sqlbuilder.NewSelectBuilder()
+ sb.Select(storableSpanColumns...)
+ if s.flagger.BooleanOrEmpty(ctx, flagger.FeatureUseTraceAttributesJSON, featuretypes.NewFlaggerEvaluationContext(orgID)) {
+ sb.SelectMore("attributes")
+ }
+ sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
+ return sb
+}
+
func (s *traceStore) GetThreadSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds, page spantypes.ThreadPage) ([]spantypes.StorableSpan, error) {
q := querybuilder.NewQueryInfo(ctx, orgID, s.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
sb := sqlbuilder.NewSelectBuilder()
diff --git a/pkg/modules/tracedetail/tracedetail.go b/pkg/modules/tracedetail/tracedetail.go
index ab0d2688cc..a5b0903325 100644
--- a/pkg/modules/tracedetail/tracedetail.go
+++ b/pkg/modules/tracedetail/tracedetail.go
@@ -21,7 +21,7 @@ type Handler interface {
// Module defines the business logic for trace detail operations.
type Module interface {
GetTraceSummary(ctx context.Context, orgID valuer.UUID, traceID string) (*spantypes.TraceStats, error)
- GetWaterfallV4(ctx context.Context, traceID string, selectedSpanID string, uncollapsedSpans []string) (*spantypes.GettableWaterfallTrace, error)
+ GetWaterfallV4(ctx context.Context, orgID valuer.UUID, traceID string, selectedSpanID string, uncollapsedSpans []string) (*spantypes.GettableWaterfallTrace, error)
GetTraceAggregations(ctx context.Context, traceID string, req *spantypes.PostableTraceAggregations) (*spantypes.GettableTraceAggregations, error)
GetFlamegraph(ctx context.Context, traceID string, selectedSpanID string, selectFields []telemetrytypes.TelemetryFieldKey) (*spantypes.GettableFlamegraphTrace, error)
GetThread(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.ThreadQuery) (*spantypes.GettableTraceThread, error)
diff --git a/pkg/types/aiobservabilitytypes/message_format.go b/pkg/types/aiobservabilitytypes/message_format.go
index ba93bcc7ad..05108857aa 100644
--- a/pkg/types/aiobservabilitytypes/message_format.go
+++ b/pkg/types/aiobservabilitytypes/message_format.go
@@ -11,7 +11,6 @@ import (
const (
FormatterSemconv = "semconv"
- FormatterTool = "tool"
FormatterOpenAIChat = "openai.chat"
FormatterText = "text"
FormatterGeneric = "generic"
@@ -26,13 +25,12 @@ var finishReasonAliases = map[string]FinishReason{
"max_tokens": FinishReasonLength,
}
-// FormattedMessages is the OTel GenAI view of one span's messages. Formatter names the converter that
-// produced it, Warnings what the converter could not resolve. The lists are never nil.
+// FormattedMessages is the OTel GenAI view of one span's messages; Warnings holds what the converter could
+// not resolve. The lists are never nil.
type FormattedMessages struct {
- Input InputMessages
- Output OutputMessages
- Formatter string
- Warnings []string
+ Input InputMessages
+ Output OutputMessages
+ Warnings []string
}
// FormatMessages builds the OTel GenAI view of a span's messages from the formats SDKs write. attributes
@@ -59,8 +57,7 @@ func (f *formatting) warn(format string, args ...any) {
f.out.Warnings = append(f.out.Warnings, fmt.Sprintf(format, args...))
}
-// messages converts gen_ai.input.messages and gen_ai.output.messages, each by its own shape, and names
-// the formatter after the input side, or the output side when the input has none.
+// messages converts gen_ai.input.messages and gen_ai.output.messages, each by its own shape.
func (f *formatting) messages() {
var inputLabel, outputLabel string
if input := attribute(f.attributes, GenAIInputMessages); input != nil {
@@ -73,10 +70,7 @@ func (f *formatting) messages() {
if output := attribute(f.attributes, GenAIOutputMessages); output != nil {
f.out.Output, outputLabel = f.side(decode(output), RoleAssistant)
}
- f.out.Formatter = inputLabel
- if inputLabel == "" {
- f.out.Formatter = outputLabel
- } else if outputLabel != "" && outputLabel != inputLabel {
+ if inputLabel != "" && outputLabel != "" && outputLabel != inputLabel {
f.warn("output formatted as %s, input as %s", outputLabel, inputLabel)
}
}
diff --git a/pkg/types/aiobservabilitytypes/message_format_openai_chat_test.go b/pkg/types/aiobservabilitytypes/message_format_openai_chat_test.go
index e52f7b8254..7b01b48c97 100644
--- a/pkg/types/aiobservabilitytypes/message_format_openai_chat_test.go
+++ b/pkg/types/aiobservabilitytypes/message_format_openai_chat_test.go
@@ -8,10 +8,9 @@ func TestFormat_OpenAIChat(t *testing.T) {
runFormatCases(t, []formatCase{
{
// openinference capture, ChatCompletion span: the raw OpenAI request and response
- name: "ResponseWithToolCalls_ToolCallParts_FinishReasonToolCall",
- input: `{"messages": [{"role": "user", "content": "What's the weather in Paris and in London? Use the tool for each."}], "model": "gpt-4o-mini", "max_tokens": 120, "tool_choice": "auto", "tools": [{"type": "function", "function": {"name": "get_current_weather", "description": "Get the current weather for a city.", "parameters": {"type": "object", "properties": {"city": {"type": "string"}, "unit": {"type": "string", "enum": ["c", "f"]}}, "required": ["city"]}}}]}`,
- output: `{"id":"chatcmpl-DksBDptnQ3aTu18YrqSdYQgiPOuRV","choices":[{"finish_reason":"tool_calls","index":0,"logprobs":null,"message":{"content":null,"refusal":null,"role":"assistant","annotations":[],"tool_calls":[{"id":"call_SW4hst7nzysgvWSAz4OdyK9D","function":{"arguments":"{\"city\": \"Paris\"}","name":"get_current_weather"},"type":"function"},{"id":"call_si8wiETYGpooMB7gMXSgMQpk","function":{"arguments":"{\"city\": \"London\"}","name":"get_current_weather"},"type":"function"}]}}],"created":1780063727,"model":"gpt-4o-mini-2024-07-18","object":"chat.completion","service_tier":"default","system_fingerprint":"fp_6e71a9f378","usage":{"completion_tokens":46,"prompt_tokens":71,"total_tokens":117,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0}}}`,
- formatter: FormatterOpenAIChat,
+ name: "ResponseWithToolCalls_ToolCallParts_FinishReasonToolCall",
+ input: `{"messages": [{"role": "user", "content": "What's the weather in Paris and in London? Use the tool for each."}], "model": "gpt-4o-mini", "max_tokens": 120, "tool_choice": "auto", "tools": [{"type": "function", "function": {"name": "get_current_weather", "description": "Get the current weather for a city.", "parameters": {"type": "object", "properties": {"city": {"type": "string"}, "unit": {"type": "string", "enum": ["c", "f"]}}, "required": ["city"]}}}]}`,
+ output: `{"id":"chatcmpl-DksBDptnQ3aTu18YrqSdYQgiPOuRV","choices":[{"finish_reason":"tool_calls","index":0,"logprobs":null,"message":{"content":null,"refusal":null,"role":"assistant","annotations":[],"tool_calls":[{"id":"call_SW4hst7nzysgvWSAz4OdyK9D","function":{"arguments":"{\"city\": \"Paris\"}","name":"get_current_weather"},"type":"function"},{"id":"call_si8wiETYGpooMB7gMXSgMQpk","function":{"arguments":"{\"city\": \"London\"}","name":"get_current_weather"},"type":"function"}]}}],"created":1780063727,"model":"gpt-4o-mini-2024-07-18","object":"chat.completion","service_tier":"default","system_fingerprint":"fp_6e71a9f378","usage":{"completion_tokens":46,"prompt_tokens":71,"total_tokens":117,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0}}}`,
wantInput: `[
{
"role": "user",
@@ -50,10 +49,9 @@ func TestFormat_OpenAIChat(t *testing.T) {
},
{
// openinference capture, the follow-up ChatCompletion span
- name: "ToolRoleMessages_BecomeToolCallResponseParts",
- input: `{"messages": [{"role": "user", "content": "What's the weather in Paris and in London? Use the tool for each."}, {"content": null, "refusal": null, "role": "assistant", "annotations": [], "audio": null, "function_call": null, "tool_calls": [{"id": "call_SW4hst7nzysgvWSAz4OdyK9D", "function": {"arguments": "{\"city\": \"Paris\"}", "name": "get_current_weather"}, "type": "function"}, {"id": "call_si8wiETYGpooMB7gMXSgMQpk", "function": {"arguments": "{\"city\": \"London\"}", "name": "get_current_weather"}, "type": "function"}]}, {"role": "tool", "tool_call_id": "call_SW4hst7nzysgvWSAz4OdyK9D", "content": "{\"city\": \"Paris\", \"temp_c\": 18, \"summary\": \"Clear\"}"}, {"role": "tool", "tool_call_id": "call_si8wiETYGpooMB7gMXSgMQpk", "content": "{\"city\": \"London\", \"temp_c\": 18, \"summary\": \"Clear\"}"}], "model": "gpt-4o-mini", "max_tokens": 80}`,
- output: `{"id":"chatcmpl-DksBF2QuaoMMMFg9UAXX9Rc28XVJT","choices":[{"finish_reason":"stop","index":0,"logprobs":null,"message":{"content":"The current weather is as follows:\n\n- **Paris**: 18°C, Clear\n- **London**: 18°C, Clear\n\nBoth cities are enjoying clear skies with the same temperature.","refusal":null,"role":"assistant","annotations":[]}}],"created":1780063729,"model":"gpt-4o-mini-2024-07-18","object":"chat.completion","service_tier":"default","system_fingerprint":"fp_e2d886d409","usage":{"completion_tokens":40,"prompt_tokens":118,"total_tokens":158,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0}}}`,
- formatter: FormatterOpenAIChat,
+ name: "ToolRoleMessages_BecomeToolCallResponseParts",
+ input: `{"messages": [{"role": "user", "content": "What's the weather in Paris and in London? Use the tool for each."}, {"content": null, "refusal": null, "role": "assistant", "annotations": [], "audio": null, "function_call": null, "tool_calls": [{"id": "call_SW4hst7nzysgvWSAz4OdyK9D", "function": {"arguments": "{\"city\": \"Paris\"}", "name": "get_current_weather"}, "type": "function"}, {"id": "call_si8wiETYGpooMB7gMXSgMQpk", "function": {"arguments": "{\"city\": \"London\"}", "name": "get_current_weather"}, "type": "function"}]}, {"role": "tool", "tool_call_id": "call_SW4hst7nzysgvWSAz4OdyK9D", "content": "{\"city\": \"Paris\", \"temp_c\": 18, \"summary\": \"Clear\"}"}, {"role": "tool", "tool_call_id": "call_si8wiETYGpooMB7gMXSgMQpk", "content": "{\"city\": \"London\", \"temp_c\": 18, \"summary\": \"Clear\"}"}], "model": "gpt-4o-mini", "max_tokens": 80}`,
+ output: `{"id":"chatcmpl-DksBF2QuaoMMMFg9UAXX9Rc28XVJT","choices":[{"finish_reason":"stop","index":0,"logprobs":null,"message":{"content":"The current weather is as follows:\n\n- **Paris**: 18°C, Clear\n- **London**: 18°C, Clear\n\nBoth cities are enjoying clear skies with the same temperature.","refusal":null,"role":"assistant","annotations":[]}}],"created":1780063729,"model":"gpt-4o-mini-2024-07-18","object":"chat.completion","service_tier":"default","system_fingerprint":"fp_e2d886d409","usage":{"completion_tokens":40,"prompt_tokens":118,"total_tokens":158,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0}}}`,
wantInput: `[
{
"role": "user",
@@ -129,11 +127,10 @@ func TestFormat_OpenAIChat(t *testing.T) {
},
{
// bifrost-gateway capture, HTTP span
- name: "GatewayFlattenedToolCalls_ToolCallParts_BareInputWarns",
- input: `What's the weather in Paris and in London? Use the tool for each.`,
- output: `[{"role":"assistant","content":"","tool_calls":[{"id":"call_xP33RT5exgBrNsvsWQZwiY9D","type":"function","name":"get_current_weather","args":"{\"city\": \"Paris\"}"},{"id":"call_lC6GgT8JW2ygJqWEM2wcohIz","type":"function","name":"get_current_weather","args":"{\"city\": \"London\"}"}]}]`,
- formatter: FormatterText,
- warnings: []string{"bare user text, role assumed", "output formatted as openai.chat, input as text"},
+ name: "GatewayFlattenedToolCalls_ToolCallParts_BareInputWarns",
+ input: `What's the weather in Paris and in London? Use the tool for each.`,
+ output: `[{"role":"assistant","content":"","tool_calls":[{"id":"call_xP33RT5exgBrNsvsWQZwiY9D","type":"function","name":"get_current_weather","args":"{\"city\": \"Paris\"}"},{"id":"call_lC6GgT8JW2ygJqWEM2wcohIz","type":"function","name":"get_current_weather","args":"{\"city\": \"London\"}"}]}]`,
+ warnings: []string{"bare user text, role assumed", "output formatted as openai.chat, input as text"},
wantInput: `[
{
"role": "user",
@@ -171,10 +168,9 @@ func TestFormat_OpenAIChat(t *testing.T) {
},
{
// openinference capture, input.value of the ChatCompletion span
- name: "FileByID_FilePart",
- input: `{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": [{"type": "text", "text": "Summarise this document in one sentence."}, {"type": "file", "file": {"file_id": "file-6F2ksmvXxt4VdoqmHRw6kL"}}]}], "max_tokens": 60}`,
- output: `{"id":"chatcmpl-DktFileCapture0001","object":"chat.completion","model":"gpt-4o-mini-2024-07-18","choices":[{"index":0,"finish_reason":"stop","logprobs":null,"message":{"role":"assistant","content":"The document is a short PDF about dragons.","refusal":null,"annotations":[]}}]}`,
- formatter: FormatterOpenAIChat,
+ name: "FileByID_FilePart",
+ input: `{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": [{"type": "text", "text": "Summarise this document in one sentence."}, {"type": "file", "file": {"file_id": "file-6F2ksmvXxt4VdoqmHRw6kL"}}]}], "max_tokens": 60}`,
+ output: `{"id":"chatcmpl-DktFileCapture0001","object":"chat.completion","model":"gpt-4o-mini-2024-07-18","choices":[{"index":0,"finish_reason":"stop","logprobs":null,"message":{"role":"assistant","content":"The document is a short PDF about dragons.","refusal":null,"annotations":[]}}]}`,
wantInput: `[
{
"role": "user",
@@ -194,9 +190,8 @@ func TestFormat_OpenAIChat(t *testing.T) {
},
{
// openinference capture, input.value of the ChatCompletion span
- name: "FileInline_BlobPart",
- input: `{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": [{"type": "text", "text": "Summarise this document in one sentence."}, {"type": "file", "file": {"filename": "draconomicon.pdf", "file_data": "data:application/pdf;base64,JVBERi0xLjQKMSAwIG9iajw8L1R5cGUvQ2F0YWxvZy9QYWdlcyAyIDAgUj4+ZW5kb2JqCjIgMCBvYmo8PC9UeXBlL1BhZ2VzL0tpZHNbXS9Db3VudCAwPj5lbmRvYmoKdHJhaWxlcjw8L1Jvb3QgMSAwIFI+PgolJUVPRgo="}}]}], "max_tokens": 60}`,
- formatter: FormatterOpenAIChat,
+ name: "FileInline_BlobPart",
+ input: `{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": [{"type": "text", "text": "Summarise this document in one sentence."}, {"type": "file", "file": {"filename": "draconomicon.pdf", "file_data": "data:application/pdf;base64,JVBERi0xLjQKMSAwIG9iajw8L1R5cGUvQ2F0YWxvZy9QYWdlcyAyIDAgUj4+ZW5kb2JqCjIgMCBvYmo8PC9UeXBlL1BhZ2VzL0tpZHNbXS9Db3VudCAwPj5lbmRvYmoKdHJhaWxlcjw8L1Jvb3QgMSAwIFI+PgolJUVPRgo="}}]}], "max_tokens": 60}`,
wantInput: `[
{
"role": "user",
@@ -211,7 +206,6 @@ func TestFormat_OpenAIChat(t *testing.T) {
{
name: "ResponseWithScalarChoice_KeptAsGeneric",
output: `{"choices":["oops",{"finish_reason":"stop","index":1,"message":{"role":"assistant","content":"hi"}}]}`,
- formatter: FormatterOpenAIChat,
wantInput: `[]`,
wantOutput: `[
{"role": "", "parts": [{"type": "generic", "content": "oops"}]},
diff --git a/pkg/types/aiobservabilitytypes/message_format_semconv_test.go b/pkg/types/aiobservabilitytypes/message_format_semconv_test.go
index 2569a55c33..182b51c35e 100644
--- a/pkg/types/aiobservabilitytypes/message_format_semconv_test.go
+++ b/pkg/types/aiobservabilitytypes/message_format_semconv_test.go
@@ -8,10 +8,9 @@ func TestFormat_Semconv(t *testing.T) {
runFormatCases(t, []formatCase{
{
// litellm capture, litellm_request span
- name: "SemconvMessages_DecodedUnchanged",
- input: `[{"role": "system", "parts": [{"type": "text", "content": "You are a concise assistant."}]}, {"role": "user", "parts": [{"type": "text", "content": "Give me a one-line definition of observability."}]}]`,
- output: `[{"role": "assistant", "parts": [{"type": "text", "content": "Observability is the ability to understand the internal state of a system based on external outputs, enabling effective monitoring and troubleshooting."}], "finish_reason": "stop"}]`,
- formatter: FormatterSemconv,
+ name: "SemconvMessages_DecodedUnchanged",
+ input: `[{"role": "system", "parts": [{"type": "text", "content": "You are a concise assistant."}]}, {"role": "user", "parts": [{"type": "text", "content": "Give me a one-line definition of observability."}]}]`,
+ output: `[{"role": "assistant", "parts": [{"type": "text", "content": "Observability is the ability to understand the internal state of a system based on external outputs, enabling effective monitoring and troubleshooting."}], "finish_reason": "stop"}]`,
wantInput: `[
{
"role": "system",
@@ -47,10 +46,9 @@ func TestFormat_Semconv(t *testing.T) {
},
{
// litellm capture, vision call; base64 trimmed
- name: "SemconvTextSpelledAsTextKey_ContentFilled_ImageBlockBecomesBlob",
- input: `[{"role": "user", "parts": [{"type": "text", "text": "What animal is in this image? One sentence."}, {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD"}}]}]`,
- output: `[{"role": "assistant", "parts": [{"type": "text", "content": "The animal in the image is a cartoon duck."}], "finish_reason": "stop"}]`,
- formatter: FormatterSemconv,
+ name: "SemconvTextSpelledAsTextKey_ContentFilled_ImageBlockBecomesBlob",
+ input: `[{"role": "user", "parts": [{"type": "text", "text": "What animal is in this image? One sentence."}, {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD"}}]}]`,
+ output: `[{"role": "assistant", "parts": [{"type": "text", "content": "The animal in the image is a cartoon duck."}], "finish_reason": "stop"}]`,
wantInput: `[
{
"role": "user",
@@ -83,10 +81,9 @@ func TestFormat_Semconv(t *testing.T) {
},
{
// langchain capture, ChatOpenAI.chat span
- name: "SemconvToolCallTurn_DecodedUnchanged",
- input: `[{"role": "user", "parts": [{"type": "text", "content": "Search for SigNoz AI observability docs, then tell me the weather in Bengaluru."}]}, {"role": "assistant", "parts": [{"type": "tool_call", "id": "call_jL9UhSdUC9wWn2qfWwOjpzFd", "name": "search_web", "arguments": {"query": "SigNoz AI observability documentation"}}, {"type": "tool_call", "id": "call_nkVdZ8xX8d17HtmVddbUgJUc", "name": "get_weather", "arguments": {"city": "Bengaluru"}}]}, {"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_jL9UhSdUC9wWn2qfWwOjpzFd", "response": "{\"query\": \"SigNoz AI observability documentation\", \"results\": [{\"title\": \"SigNoz docs: AI observability\", \"snippet\": \"...\"}, {\"title\": \"OpenTelemetry GenAI conventions\", \"snippet\": \"...\"}]}"}]}, {"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_nkVdZ8xX8d17HtmVddbUgJUc", "response": "{\"city\": \"Bengaluru\", \"temp_c\": 18, \"summary\": \"Clear\"}"}]}]`,
- output: `[{"role": "assistant", "parts": [{"type": "text", "content": "I found some results for the SigNoz AI observability documentation. Here's one of the titles you might be interested in:\n\n- **SigNoz docs: AI observability**\n\nUnfortunately, a snippet was not provided, but you can look it up directly for more details.\n\nAs for the weather in Bengaluru, it's currently 18\u00b0C and clear."}], "finish_reason": "stop"}]`,
- formatter: FormatterSemconv,
+ name: "SemconvToolCallTurn_DecodedUnchanged",
+ input: `[{"role": "user", "parts": [{"type": "text", "content": "Search for SigNoz AI observability docs, then tell me the weather in Bengaluru."}]}, {"role": "assistant", "parts": [{"type": "tool_call", "id": "call_jL9UhSdUC9wWn2qfWwOjpzFd", "name": "search_web", "arguments": {"query": "SigNoz AI observability documentation"}}, {"type": "tool_call", "id": "call_nkVdZ8xX8d17HtmVddbUgJUc", "name": "get_weather", "arguments": {"city": "Bengaluru"}}]}, {"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_jL9UhSdUC9wWn2qfWwOjpzFd", "response": "{\"query\": \"SigNoz AI observability documentation\", \"results\": [{\"title\": \"SigNoz docs: AI observability\", \"snippet\": \"...\"}, {\"title\": \"OpenTelemetry GenAI conventions\", \"snippet\": \"...\"}]}"}]}, {"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_nkVdZ8xX8d17HtmVddbUgJUc", "response": "{\"city\": \"Bengaluru\", \"temp_c\": 18, \"summary\": \"Clear\"}"}]}]`,
+ output: `[{"role": "assistant", "parts": [{"type": "text", "content": "I found some results for the SigNoz AI observability documentation. Here's one of the titles you might be interested in:\n\n- **SigNoz docs: AI observability**\n\nUnfortunately, a snippet was not provided, but you can look it up directly for more details.\n\nAs for the weather in Bengaluru, it's currently 18\u00b0C and clear."}], "finish_reason": "stop"}]`,
wantInput: `[
{
"role": "user",
@@ -155,7 +152,6 @@ func TestFormat_Semconv(t *testing.T) {
{
name: "StructuredSemconvValue_DecodedWithoutJSONString",
input: []any{map[string]any{"role": "user", "parts": []any{map[string]any{"type": "text", "content": "hi"}}}},
- formatter: FormatterSemconv,
wantInput: `[{"role": "user", "parts": [{"type": "text", "content": "hi"}]}]`,
wantOutput: `[]`,
},
diff --git a/pkg/types/aiobservabilitytypes/message_format_test.go b/pkg/types/aiobservabilitytypes/message_format_test.go
index 3b40d15fcc..5aee4b73ce 100644
--- a/pkg/types/aiobservabilitytypes/message_format_test.go
+++ b/pkg/types/aiobservabilitytypes/message_format_test.go
@@ -15,7 +15,6 @@ type formatCase struct {
input any
output any
attributes map[string]any // flat dotted keys beside the two message attributes
- formatter string
warnings []string
wantInput string
wantOutput string
@@ -28,7 +27,6 @@ func runFormatCases(t *testing.T, testCases []formatCase) {
attributes := map[string]any{GenAIInputMessages: testCase.input, GenAIOutputMessages: testCase.output}
maps.Copy(attributes, testCase.attributes)
formatted := FormatMessages(document(attributes))
- assert.Equal(t, testCase.formatter, formatted.Formatter)
assert.Equal(t, append([]string{}, testCase.warnings...), formatted.Warnings)
input, err := json.Marshal(formatted.Input)
@@ -83,8 +81,7 @@ Divide by 2:
  x = 0.05
So, the ball costs 5 cents.`,
- formatter: FormatterText,
- warnings: []string{"bare user text, role assumed", "bare assistant text, role assumed"},
+ warnings: []string{"bare user text, role assumed", "bare assistant text, role assumed"},
wantInput: `[
{
"role": "user",
@@ -111,13 +108,12 @@ So, the ball costs 5 cents.`,
{
name: "UnrecognisedObject_GenericPart_Warns",
input: `{"city": "Paris", "temp_c": 21}`,
- formatter: FormatterGeneric,
warnings: []string{"message format not recognised, kept as generic"},
wantInput: `[{"role": "", "parts": [{"type": "generic", "content": "{\"city\":\"Paris\",\"temp_c\":21}"}]}]`,
wantOutput: `[]`,
},
{
- name: "NoMessageAttributes_EmptyListsNoFormatter",
+ name: "NoMessageAttributes_EmptyLists",
attributes: map[string]any{GenAIRequestModel: "gpt-4o", GenAIToolName: "get_weather"},
wantInput: `[]`,
wantOutput: `[]`,
diff --git a/pkg/types/aiobservabilitytypes/message_format_tool.go b/pkg/types/aiobservabilitytypes/message_format_tool.go
index 9fb4595eca..0ddedb61fb 100644
--- a/pkg/types/aiobservabilitytypes/message_format_tool.go
+++ b/pkg/types/aiobservabilitytypes/message_format_tool.go
@@ -20,7 +20,6 @@ func (f *formatting) tool() {
result := ToolCallResponsePart{Type: PartTypeToolCallResponse, ID: id, Response: toolResult(decode(raw))}
f.out.Output = OutputMessages{{Role: RoleTool, Parts: Parts{part(result)}}}
}
- f.out.Formatter = FormatterTool
}
func toolArguments(value any) any {
diff --git a/pkg/types/aiobservabilitytypes/message_format_tool_test.go b/pkg/types/aiobservabilitytypes/message_format_tool_test.go
index 9b37f5e23c..c5eb2553e6 100644
--- a/pkg/types/aiobservabilitytypes/message_format_tool_test.go
+++ b/pkg/types/aiobservabilitytypes/message_format_tool_test.go
@@ -15,7 +15,6 @@ func TestFormat_Tool(t *testing.T) {
GenAIToolCallArguments: `{"input_str": "{'city': 'Bengaluru'}", "tags": [], "metadata": {}, "inputs": {"city": "Bengaluru"}, "kwargs": {"color": "green", "name": null, "tool_call_id": null}}`,
GenAIToolCallResult: `{"output": "{\"city\": \"Bengaluru\", \"temp_c\": 18, \"summary\": \"Clear\"}", "kwargs": {"tags": [], "color": "green", "name": "get_weather"}}`,
},
- formatter: FormatterTool,
wantInput: `[{"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "arguments": {"city": "Bengaluru"}}]}]`,
wantOutput: `[{"role": "tool", "parts": [{"type": "tool_call_response", "response": {"city": "Bengaluru", "temp_c": 18, "summary": "Clear"}}]}]`,
},
@@ -28,7 +27,6 @@ func TestFormat_Tool(t *testing.T) {
GenAIToolCallArguments: `{"args": [], "kwargs": {"city": "Bengaluru"}}`,
GenAIToolCallResult: `"{\"city\": \"Bengaluru\", \"temp_c\": 28, \"summary\": \"Partly cloudy\"}"`,
},
- formatter: FormatterTool,
wantInput: `[{"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "arguments": {"city": "Bengaluru"}}]}]`,
wantOutput: `[{"role": "tool", "parts": [{"type": "tool_call_response", "response": {"city": "Bengaluru", "temp_c": 28, "summary": "Partly cloudy"}}]}]`,
},
@@ -41,7 +39,6 @@ func TestFormat_Tool(t *testing.T) {
GenAIToolCallArguments: `{"args": ["OpenAI", "What's the weather in Paris?"], "kwargs": {}}`,
GenAIToolCallResult: `null`,
},
- formatter: FormatterTool,
wantInput: `[{"role": "assistant", "parts": [{"type": "tool_call", "name": "lookup", "arguments": ["OpenAI", "What's the weather in Paris?"]}]}]`,
wantOutput: `[{"role": "tool", "parts": [{"type": "tool_call_response", "response": null}]}]`,
},
@@ -51,7 +48,6 @@ func TestFormat_Tool(t *testing.T) {
GenAIToolName: "lookup",
GenAIToolCallArguments: `{"args": ["Paris"], "kwargs": {"unit": "c"}}`,
},
- formatter: FormatterTool,
wantInput: `[{"role": "assistant", "parts": [{"type": "tool_call", "name": "lookup", "arguments": {"args": ["Paris"], "kwargs": {"unit": "c"}}}]}]`,
wantOutput: `[]`,
},
@@ -64,7 +60,6 @@ func TestFormat_Tool(t *testing.T) {
GenAIToolCallArguments: `{"city":"Bangalore"}`,
GenAIToolCallResult: `27C, partly cloudy, light breeze from the south.`,
},
- formatter: FormatterTool,
wantInput: `[{"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "arguments": {"city": "Bangalore"}}]}]`,
wantOutput: `[{"role": "tool", "parts": [{"type": "tool_call_response", "response": "27C, partly cloudy, light breeze from the south."}]}]`,
},
@@ -78,7 +73,6 @@ func TestFormat_Tool(t *testing.T) {
GenAIToolCallArguments: `{"city":"Bengaluru","unit":"c"}`,
GenAIToolCallResult: `{"city":"Bengaluru","unit":"c","temperature":27,"condition":"partly cloudy"}`,
},
- formatter: FormatterTool,
wantInput: `[{"role": "assistant", "parts": [{"type": "tool_call", "name": "get_current_weather", "id": "call_l0ycKcmt1uPCdGWR4SkwoLBv", "arguments": {"city": "Bengaluru", "unit": "c"}}]}]`,
wantOutput: `[{"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_l0ycKcmt1uPCdGWR4SkwoLBv", "response": {"city": "Bengaluru", "unit": "c", "temperature": 27, "condition": "partly cloudy"}}]}]`,
},
@@ -90,7 +84,6 @@ func TestFormat_Tool(t *testing.T) {
GenAIToolCallID: "call_1",
GenAIToolCallArguments: map[string]any{"city": "Paris", "days": []any{1.0, 2.0}},
},
- formatter: FormatterTool,
wantInput: `[{"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "id": "call_1", "arguments": {"city": "Paris", "days": [1, 2]}}]}]`,
wantOutput: `[]`,
},
@@ -102,7 +95,6 @@ func TestFormat_Tool(t *testing.T) {
GenAIToolName: "lookup",
GenAIToolCallArguments: `{"city": "Paris"}`,
},
- formatter: FormatterTool,
wantInput: `[{"role": "assistant", "parts": [{"type": "tool_call", "name": "lookup", "arguments": {"city": "Paris"}}]}]`,
wantOutput: `[]`,
},
diff --git a/pkg/types/spantypes/store.go b/pkg/types/spantypes/store.go
index 758bfcd54c..848d752d50 100644
--- a/pkg/types/spantypes/store.go
+++ b/pkg/types/spantypes/store.go
@@ -33,9 +33,9 @@ type SpanMapperStore interface {
type TraceStore interface {
GetTraceBounds(ctx context.Context, traceID string) (*TraceBounds, error)
GetTraceStats(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds) (*TraceStats, error)
- GetTraceSpans(ctx context.Context, traceID string, bounds *TraceBounds) ([]StorableSpan, error)
+ GetTraceSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds) ([]StorableSpan, error)
GetMinimalSpans(ctx context.Context, traceID string, start, end time.Time) ([]MinimalSpan, error)
- GetTraceSpansByIDs(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]StorableSpan, error)
+ GetTraceSpansByIDs(ctx context.Context, orgID valuer.UUID, traceID string, start, end time.Time, spanIDs []string) ([]StorableSpan, error)
GetFlamegraphSpans(ctx context.Context, traceID string, start, end time.Time, spanIDs []string) ([]StorableSpan, error)
GetThreadSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds, page ThreadPage) ([]StorableSpan, error)
GetThreadCursor(ctx context.Context, traceID string, bounds *TraceBounds, spanID string) (*ThreadCursor, error)
diff --git a/pkg/types/spantypes/thread.go b/pkg/types/spantypes/thread.go
index 8ce601dc35..2d055e8907 100644
--- a/pkg/types/spantypes/thread.go
+++ b/pkg/types/spantypes/thread.go
@@ -77,12 +77,11 @@ type ThreadSpan struct {
Attributes map[string]any `json:"attributes" required:"true" nullable:"false"`
Events []Event `json:"events" required:"true" nullable:"false"`
References []OtelSpanRef `json:"references" required:"true" nullable:"false"`
- // The formatted fields hold the span's messages in the OTel GenAI shape; Formatter names the
- // converter that produced them and FormatterWarnings what it could not resolve.
- FormattedInput aiobservabilitytypes.InputMessages `json:"formatted_input" required:"true" nullable:"false"`
- FormattedOutput aiobservabilitytypes.OutputMessages `json:"formatted_output" required:"true" nullable:"false"`
- Formatter string `json:"formatter" required:"true"`
- FormatterWarnings []string `json:"formatter_warnings" required:"true" nullable:"false"`
+ // The formatted fields hold the span's messages in the OTel GenAI shape; FormatterWarnings holds what
+ // the converter could not resolve.
+ FormattedInput aiobservabilitytypes.InputMessages `json:"formattedInput" required:"true" nullable:"false"`
+ FormattedOutput aiobservabilitytypes.OutputMessages `json:"formattedOutput" required:"true" nullable:"false"`
+ FormatterWarnings []string `json:"formatterWarnings" required:"true" nullable:"false"`
timeUnixNano uint64
}
@@ -199,7 +198,6 @@ func newThreadSpan(traceID string, storable *StorableSpan) *ThreadSpan {
References: storable.UnmarshalledRefs(),
FormattedInput: formatted.Input,
FormattedOutput: formatted.Output,
- Formatter: formatted.Formatter,
FormatterWarnings: formatted.Warnings,
timeUnixNano: timeUnixNano,
}
diff --git a/pkg/types/spantypes/waterfall_span.go b/pkg/types/spantypes/waterfall_span.go
index fd0c186652..0a33c85877 100644
--- a/pkg/types/spantypes/waterfall_span.go
+++ b/pkg/types/spantypes/waterfall_span.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/types/aiobservabilitytypes"
"github.com/SigNoz/signoz/pkg/types/telemetrystoretypes"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
)
@@ -82,6 +83,12 @@ type WaterfallSpan struct {
StatusCodeString string `json:"status_code_string,omitempty"`
StatusMessage string `json:"status_message,omitempty"`
+ // The formatted fields hold the span's gen_ai messages or tool call in the OTel GenAI shape, omitted
+ // when the span carries neither; FormatterWarnings holds what the converter could not resolve.
+ FormattedInput aiobservabilitytypes.InputMessages `json:"formattedInput,omitempty"`
+ FormattedOutput aiobservabilitytypes.OutputMessages `json:"formattedOutput,omitempty"`
+ FormatterWarnings []string `json:"formatterWarnings,omitempty"`
+
// Internal tree structure fields
Children []*WaterfallSpan `json:"-"`
SubTreeNodeCount uint64 `json:"sub_tree_node_count"`
@@ -317,6 +324,7 @@ func (item *StorableSpan) ToWaterfallSpan(traceID string) *WaterfallSpan {
resources := make(map[string]string)
maps.Copy(resources, item.ResourcesString)
+ formatted := aiobservabilitytypes.FormatMessages(item.AttributesJSON)
return &WaterfallSpan{
Attributes: item.Attributes(),
DBName: item.DBName,
@@ -347,6 +355,9 @@ func (item *StorableSpan) ToWaterfallSpan(traceID string) *WaterfallSpan {
TimeUnix: uint64(item.StartTime.UnixNano()),
ServiceName: item.ServiceName,
References: item.UnmarshalledRefs(),
+ FormattedInput: formatted.Input,
+ FormattedOutput: formatted.Output,
+ FormatterWarnings: formatted.Warnings,
}
}
diff --git a/pkg/types/spantypes/waterfall_trace.go b/pkg/types/spantypes/waterfall_trace.go
index 2f67bea64a..5ee7076670 100644
--- a/pkg/types/spantypes/waterfall_trace.go
+++ b/pkg/types/spantypes/waterfall_trace.go
@@ -40,6 +40,8 @@ type GettableWaterfallTrace struct {
HasMissingSpans bool `json:"hasMissingSpans"`
UncollapsedSpans []string `json:"uncollapsedSpans"`
HasMore bool `json:"hasMore"`
+ // FormattedSpans counts the spans in Spans carrying formatted gen_ai messages.
+ FormattedSpans int `json:"-"`
}
// NewWaterfallTrace constructs a WaterfallTrace from processed span data.
@@ -226,8 +228,12 @@ func NewGettableWaterfallTrace(
}
// convert start timestamp to millis because client is expecting it in millis
+ formattedSpans := 0
for _, span := range selectedSpans {
span.TimeUnix = span.TimeUnix / 1_000_000
+ if len(span.FormattedInput) > 0 || len(span.FormattedOutput) > 0 {
+ formattedSpans++
+ }
}
return &GettableWaterfallTrace{
@@ -241,6 +247,7 @@ func NewGettableWaterfallTrace(
RootServiceEntryPoint: rootServiceEntryPoint,
HasMissingSpans: traceData.HasMissingSpans,
HasMore: !selectAllSpans,
+ FormattedSpans: formattedSpans,
}
}
diff --git a/tests/integration/tests/tracedetail/02_thread.py b/tests/integration/tests/tracedetail/02_thread.py
index d19f3261ff..6e3439182c 100644
--- a/tests/integration/tests/tracedetail/02_thread.py
+++ b/tests/integration/tests/tracedetail/02_thread.py
@@ -59,9 +59,8 @@ def test_thread_returns_gen_ai_spans_in_order(
first, tool, agent, input_only, output_only = thread["spans"]
assert agent["attributes"]["gen_ai.agent.name"] == "planner"
- assert agent["formatter"] == ""
- assert agent["formatted_input"] == []
- assert agent["formatted_output"] == []
+ assert agent["formattedInput"] == []
+ assert agent["formattedOutput"] == []
assert tool["attributes"]["gen_ai.tool.call.arguments"] == json.dumps({"city": "Bangalore"})
assert tool["attributes"]["gen_ai.tool.call.result"] == "sunny"
assert first["time_unix"] == int((now - timedelta(seconds=8)).timestamp() * 1000)
@@ -74,20 +73,16 @@ def test_thread_returns_gen_ai_spans_in_order(
assert output_only["attributes"]["gen_ai.output.messages"] == "It is sunny in Bangalore."
tool_call = {"type": "tool_call", "name": "get_weather", "id": "call_1", "arguments": {"city": "Bangalore"}}
- assert first["formatter"] == "semconv"
- assert first["formatted_input"] == [{"role": "user", "parts": [{"type": "text", "content": "weather in Bangalore?"}]}]
- assert first["formatted_output"] == [{"role": "assistant", "parts": [tool_call], "finish_reason": "tool_call"}]
- assert first["formatter_warnings"] == []
- assert tool["formatter"] == "tool"
- assert tool["formatted_input"] == [{"role": "assistant", "parts": [tool_call]}]
- assert tool["formatted_output"] == [{"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_1", "response": "sunny"}]}]
- assert input_only["formatter"] == "openai.chat"
- assert input_only["formatted_input"] == [{"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_1", "response": "sunny"}]}]
- assert input_only["formatted_output"] == []
- assert output_only["formatter"] == "text"
- assert output_only["formatted_input"] == []
- assert output_only["formatted_output"] == [{"role": "assistant", "parts": [{"type": "text", "content": "It is sunny in Bangalore."}]}]
- assert output_only["formatter_warnings"] == ["bare assistant text, role assumed"]
+ assert first["formattedInput"] == [{"role": "user", "parts": [{"type": "text", "content": "weather in Bangalore?"}]}]
+ assert first["formattedOutput"] == [{"role": "assistant", "parts": [tool_call], "finish_reason": "tool_call"}]
+ assert first["formatterWarnings"] == []
+ assert tool["formattedInput"] == [{"role": "assistant", "parts": [tool_call]}]
+ assert tool["formattedOutput"] == [{"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_1", "response": "sunny"}]}]
+ assert input_only["formattedInput"] == [{"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_1", "response": "sunny"}]}]
+ assert input_only["formattedOutput"] == []
+ assert output_only["formattedInput"] == []
+ assert output_only["formattedOutput"] == [{"role": "assistant", "parts": [{"type": "text", "content": "It is sunny in Bangalore."}]}]
+ assert output_only["formatterWarnings"] == ["bare assistant text, role assumed"]
def test_thread_paginates_with_cursors(
@@ -318,9 +313,8 @@ def test_thread_reads_spans_across_json_rollout(
assert before_spans[1]["attributes"]["gen_ai.output.messages"] == json.dumps([{"role": "assistant", "content": "second"}])
# messages are decoded from the JSON column only, never from the legacy maps
for span in before_spans:
- assert span["formatter"] == ""
- assert span["formatted_input"] == []
- assert span["formatted_output"] == []
+ assert span["formattedInput"] == []
+ assert span["formattedOutput"] == []
straddle = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{straddle_trace_id}/thread"), headers=headers, timeout=10)
assert straddle.status_code == HTTPStatus.OK, straddle.text
@@ -328,10 +322,8 @@ def test_thread_reads_spans_across_json_rollout(
assert [span["span_id"] for span in straddle_spans] == [legacy_id, json_id]
assert straddle_spans[0]["attributes"]["gen_ai.input.messages"] == json.dumps([{"role": "user", "content": "legacy"}])
assert straddle_spans[1]["attributes"]["gen_ai.input.messages"] == json.dumps([{"role": "user", "content": "json"}])
- assert straddle_spans[0]["formatter"] == ""
- assert straddle_spans[0]["formatted_input"] == []
- assert straddle_spans[1]["formatter"] == "openai.chat"
- assert straddle_spans[1]["formatted_input"] == [{"role": "user", "parts": [{"type": "text", "content": "json"}]}]
+ assert straddle_spans[0]["formattedInput"] == []
+ assert straddle_spans[1]["formattedInput"] == [{"role": "user", "parts": [{"type": "text", "content": "json"}]}]
def test_thread_without_gen_ai_spans_is_empty(
diff --git a/tests/integration/tests/tracedetail/03_waterfall.py b/tests/integration/tests/tracedetail/03_waterfall.py
new file mode 100644
index 0000000000..224f96a632
--- /dev/null
+++ b/tests/integration/tests/tracedetail/03_waterfall.py
@@ -0,0 +1,67 @@
+import json
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+from http import HTTPStatus
+
+import requests
+
+from fixtures import types
+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
+from fixtures.traces import ATTRIBUTE_JSON_ROLLOUT_TIME, TraceIdGenerator, Traces, TracesKind
+
+
+def test_waterfall_formats_messages_on_gen_ai_spans(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ insert_traces: Callable[[list[Traces]], None],
+ seed_attribute_evolution: Callable[[str, datetime], None],
+) -> None:
+ seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)
+ now = datetime.now(tz=UTC).replace(microsecond=0)
+ trace_id = TraceIdGenerator.trace_id()
+ root_id, llm_id, tool_id, output_only_id = (TraceIdGenerator.span_id() for _ in range(4))
+ resources = {"service.name": "tracedetail-waterfall"}
+ llm_input = json.dumps([{"role": "user", "parts": [{"type": "text", "content": "weather in Bangalore?"}]}])
+ llm_output = json.dumps([{"role": "assistant", "parts": [{"type": "tool_call", "id": "call_1", "name": "get_weather", "arguments": {"city": "Bangalore"}}], "finish_reason": "tool_call"}])
+
+ insert_traces(
+ [
+ Traces(timestamp=now - timedelta(seconds=10), duration=timedelta(seconds=9), trace_id=trace_id, span_id=root_id, name="POST /chat", kind=TracesKind.SPAN_KIND_SERVER, resources=resources, attributes={"http.method": "POST"}),
+ Traces(timestamp=now - timedelta(seconds=8), trace_id=trace_id, span_id=llm_id, parent_span_id=root_id, name="chat gpt-4o", resources=resources, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.input.messages": llm_input, "gen_ai.output.messages": llm_output}),
+ Traces(timestamp=now - timedelta(seconds=6), trace_id=trace_id, span_id=tool_id, parent_span_id=root_id, name="execute_tool get_weather", resources=resources, attributes={"gen_ai.tool.name": "get_weather", "gen_ai.tool.call.result": "sunny"}),
+ Traces(timestamp=now - timedelta(seconds=4), trace_id=trace_id, span_id=output_only_id, parent_span_id=root_id, name="chat gpt-4o", resources=resources, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.output.messages": "It is sunny in Bangalore."}),
+ ]
+ )
+
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(f"/api/v4/traces/{trace_id}/waterfall"),
+ json={"selectedSpanId": "", "uncollapsedSpans": []},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=10,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+
+ waterfall = response.json()["data"]
+ assert [span["span_id"] for span in waterfall["spans"]] == [root_id, llm_id, tool_id, output_only_id]
+ root, llm, tool, output_only = waterfall["spans"]
+
+ # spans without messages carry no formatted keys
+ assert not {"formattedInput", "formattedOutput", "formatterWarnings"} & root.keys(), root
+ assert root["attributes"]["http.method"] == "POST"
+
+ assert tool["attributes"]["gen_ai.tool.call.result"] == "sunny"
+ assert "formattedInput" not in tool
+ assert tool["formattedOutput"] == [{"role": "tool", "parts": [{"type": "tool_call_response", "response": "sunny"}]}]
+
+ # the raw messages stay in attributes for the raw view
+ assert llm["attributes"]["gen_ai.input.messages"] == llm_input
+ assert llm["attributes"]["gen_ai.output.messages"] == llm_output
+ assert llm["formattedInput"] == [{"role": "user", "parts": [{"type": "text", "content": "weather in Bangalore?"}]}]
+ assert llm["formattedOutput"] == [{"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "id": "call_1", "arguments": {"city": "Bangalore"}}], "finish_reason": "tool_call"}]
+ assert "formatterWarnings" not in llm
+
+ assert "formattedInput" not in output_only
+ assert output_only["formattedOutput"] == [{"role": "assistant", "parts": [{"type": "text", "content": "It is sunny in Bangalore."}]}]
+ assert output_only["formatterWarnings"] == ["bare assistant text, role assumed"]