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.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(tracedetail): format OpenInference flattened messages (#13133)
Nityananda Gohain923d758f7c1e
diff --git a/pkg/types/aiobservabilitytypes/message_format.go b/pkg/types/aiobservabilitytypes/message_format.goindex c165b4fd55..89f6a2bbac 100644--- a/pkg/types/aiobservabilitytypes/message_format.go+++ b/pkg/types/aiobservabilitytypes/message_format.go@@ -4,27 +4,31 @@ import ("encoding/json""fmt""regexp"+ "sort"+ "strconv""strings""github.com/SigNoz/signoz/pkg/valuer")const (- FormatterSemconv = "semconv"- FormatterOpenAIChat = "openai.chat"- FormatterText = "text"- FormatterGeneric = "generic"+ FormatterSemconv = "semconv"+ FormatterOpenInference = "openinference"+ FormatterOpenAIChat = "openai.chat"+ FormatterText = "text"+ FormatterGeneric = "generic")var dataURL = regexp.MustCompile(`^data:([^;,]+);base64,(.+)$`)// Provider spellings of the finish reasons; the enum values themselves pass through. tool_calls and-// function_call are OpenAI's, end_turn, stop_sequence and max_tokens Anthropic's, tool-calls the Vercel AI SDK's:+// function_call are OpenAI's, end_turn, stop_sequence, max_tokens and tool_use Anthropic's, tool-calls the+// Vercel AI SDK's:// https://github.com/openai/openai-openapi/blob/aeb6a041dc56c011ca9f12127ec898f911100aa0/openapi.yaml#L44782// https://platform.claude.com/docs/en/api/messages// https://github.com/vercel/ai/blob/a5e92fe3c692f8e152fe1eb9ef50a4e734ad0ffb/packages/provider/src/language-model/v2/language-model-v2-finish-reason.tsvar finishReasonAliases = map[string]FinishReason{- "tool_calls": FinishReasonToolCall, "function_call": FinishReasonToolCall, "tool-calls": FinishReasonToolCall,+ "tool_calls": FinishReasonToolCall, "function_call": FinishReasonToolCall, "tool-calls": FinishReasonToolCall, "tool_use": FinishReasonToolCall,"end_turn": FinishReasonStop, "stop_sequence": FinishReasonStop,"max_tokens": FinishReasonLength,}@@ -39,12 +43,14 @@ type FormattedMessages struct {// FormatMessages builds the OTel GenAI view of a span's messages from the formats SDKs write. attributes// is the span's JSON attribute document, nested by key segment, so an object value is whole. Each-// message value is a JSON string or a structured value. A tool call and its result take precedence over-// messages beside them. gen_ai.system_instructions leads the input and gen_ai.response.finish_reasons-// overrides the finish reasons the converter found, whichever converter ran.+// message value is a JSON string or a structured value. OpenInference's flattened messages come first,+// then a tool call and its result, then the message attributes. gen_ai.system_instructions leads the+// input and gen_ai.response.finish_reasons overrides the finish reasons the converter found, whichever+// converter ran.func FormatMessages(attributes map[string]any) FormattedMessages {f := &formatting{attributes: attributes, out: FormattedMessages{Input: InputMessages{}, Output: OutputMessages{}, Warnings: []string{}}}switch {+ case f.openInference():case attribute(f.attributes, GenAIToolCallArguments) != nil || attribute(f.attributes, GenAIToolCallResult) != nil:f.tool()case attribute(f.attributes, GenAIInputMessages) != nil || attribute(f.attributes, GenAIOutputMessages) != nil:@@ -70,13 +76,15 @@ func (f *formatting) messages() {if input := attribute(f.attributes, GenAIInputMessages); input != nil {var msgs OutputMessagesmsgs, inputLabel = f.side(decode(input), RoleUser)- for _, m := range msgs {- f.out.Input = append(f.out.Input, ChatMessage{Role: m.Role, Parts: m.Parts, Name: m.Name})- }+ f.out.Input = inputMessages(msgs)}if output := attribute(f.attributes, GenAIOutputMessages); output != nil {f.out.Output, outputLabel = f.side(decode(output), RoleAssistant)}+ f.warnMixedFormats(inputLabel, outputLabel)+}++func (f *formatting) warnMixedFormats(inputLabel, outputLabel string) {if inputLabel != "" && outputLabel != "" && outputLabel != inputLabel {f.warn("output formatted as %s, input as %s", outputLabel, inputLabel)}@@ -167,6 +175,38 @@ func attribute(doc map[string]any, key string) any {return current}+// indexed reads a flattened list, "<key>.<N>.*" keys stored as an object keyed by N, in numeric order.+// A list value is returned as is.+func indexed(doc map[string]any, key string) []map[string]any {+ var items []any+ switch v := attribute(doc, key).(type) {+ case []any:+ items = v+ case map[string]any:+ indexes := make([]int, 0, len(v))+ byIndex := make(map[int]any, len(v))+ for k, item := range v {+ n, err := strconv.Atoi(k)+ if err != nil {+ continue+ }+ indexes = append(indexes, n)+ byIndex[n] = item+ }+ sort.Ints(indexes)+ for _, n := range indexes {+ items = append(items, byIndex[n])+ }+ }+ out := make([]map[string]any, 0, len(items))+ for _, item := range items {+ if m, ok := item.(map[string]any); ok {+ out = append(out, m)+ }+ }+ return out+}+func firstObject(list []any) (map[string]any, bool) {if len(list) == 0 {return nil, false@@ -179,6 +219,31 @@ func genericMessage(value any) OutputMessage {return OutputMessage{Parts: Parts{part(GenericPart{"type": FormatterGeneric, "content": stringOf(value)})}}}+func inputMessages(msgs OutputMessages) InputMessages {+ out := make(InputMessages, 0, len(msgs))+ for _, m := range msgs {+ out = append(out, ChatMessage{Role: m.Role, Parts: m.Parts, Name: m.Name})+ }+ return out+}++// foldAssistant merges runs of assistant messages into one and drops messages without parts, for+// SDKs that write one message per output item.+func foldAssistant(msgs OutputMessages) OutputMessages {+ out := make(OutputMessages, 0, len(msgs))+ for _, msg := range msgs {+ if len(out) > 0 && msg.Role == RoleAssistant && out[len(out)-1].Role == RoleAssistant {+ out[len(out)-1].Parts = append(out[len(out)-1].Parts, msg.Parts...)+ continue+ }+ if len(msg.Parts) == 0 {+ continue+ }+ out = append(out, msg)+ }+ return out+}+// decode parses a JSON-encoded attribute value, twice when an SDK encoded the string again.// Anything that is not JSON is returned as is.func decode(value any) any {diff --git a/pkg/types/aiobservabilitytypes/message_format_openinference.go b/pkg/types/aiobservabilitytypes/message_format_openinference.gonew file mode 100644index 0000000000..b0099e1d81--- /dev/null+++ b/pkg/types/aiobservabilitytypes/message_format_openinference.go@@ -0,0 +1,137 @@+package aiobservabilitytypes++import "github.com/SigNoz/signoz/pkg/valuer"++// Format: the flattened llm.input_messages.N.message.* and llm.output_messages.N.message.* keys, the+// provider-neutral copy of the conversation the OpenInference instrumentations write on LLM spans. A side+// without them falls back to the raw provider payload the mapper moved onto gen_ai.*.messages; pipecat+// streams the reply into output.value alone.+// https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/semantic_conventions.md#L77+// https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/tool_calling.md#L37+// https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/multimodal_attributes.md#L35+// https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/llm_spans.md#L181+// Handled: message.content, the ordered message.contents items (text, image, audio, video, reasoning),+// message.tool_calls, the legacy message.function_call_*, tool results, llm.finish_reason. A tool_use+// content item repeats a call from message.tool_calls and is skipped.+// Dropped: reasoning id, signature, data and encrypted_content; audio transcripts.++const (+ openInferenceInputMessages = "llm.input_messages"+ openInferenceOutputMessages = "llm.output_messages"+ openInferenceFinishReason = "llm.finish_reason"+)++func (f *formatting) openInference() bool {+ input := indexed(f.attributes, openInferenceInputMessages)+ output := indexed(f.attributes, openInferenceOutputMessages)+ if len(input) == 0 && len(output) == 0 {+ return false+ }+ inputLabel, outputLabel := FormatterOpenInference, FormatterOpenInference+ if len(input) > 0 {+ f.out.Input = inputMessages(openInferenceMessages(input))+ } else if raw := attribute(f.attributes, GenAIInputMessages); raw != nil {+ var msgs OutputMessages+ msgs, inputLabel = f.side(decode(raw), RoleUser)+ f.out.Input = inputMessages(msgs)+ }+ if len(output) > 0 {+ f.out.Output = openInferenceMessages(output)+ if fr := finishReason(stringOf(attribute(f.attributes, openInferenceFinishReason))); fr != nil {+ for i := range f.out.Output {+ f.out.Output[i].FinishReason = fr+ }+ }+ } else if raw := attribute(f.attributes, GenAIOutputMessages); raw != nil {+ f.out.Output, outputLabel = f.side(decode(raw), RoleAssistant)+ }+ f.warnMixedFormats(inputLabel, outputLabel)+ return true+}++// openInferenceMessages converts the message buckets and folds runs of assistant messages: the Responses+// path writes one message per output item, an empty one for a reasoning item without a summary.+func openInferenceMessages(buckets []map[string]any) OutputMessages {+ msgs := make(OutputMessages, 0, len(buckets))+ for _, bucket := range buckets {+ message, _ := bucket["message"].(map[string]any)+ msgs = append(msgs, openInferenceMessage(message))+ }+ return foldAssistant(msgs)+}++// openInferenceMessage converts one message.* object. A message without a role is a tool response when+// it has a tool_call_id, an assistant turn when it has tool calls, else a user turn, as the+// collector-contrib normalizer decides it:+// https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/fc79b95297776dec6c47490cd6f6026b942bf6fb/processor/genainormalizerprocessor/internal/openinference/messages.go#L473+func openInferenceMessage(m map[string]any) OutputMessage {+ msg := OutputMessage{Role: role(stringOf(m["role"])), Parts: Parts{}, Name: optionalString(m["name"])}+ id := stringOf(m["tool_call_id"])+ calls := indexed(m, "tool_calls")+ if msg.Role.IsZero() {+ switch {+ case id != "":+ msg.Role = RoleTool+ case len(calls) > 0:+ msg.Role = RoleAssistant+ default:+ msg.Role = RoleUser+ }+ }+ if msg.Role == RoleTool && id != "" {+ msg.Parts = Parts{part(ToolCallResponsePart{Type: PartTypeToolCallResponse, ID: &id, Response: decode(m["content"])})}+ return msg+ }+ if content := stringOf(m["content"]); content != "" {+ msg.Parts = append(msg.Parts, part(textPart(content)))+ }+ msg.Parts = append(msg.Parts, openInferenceContents(m)...)+ for _, call := range calls {+ if c, ok := call["tool_call"].(map[string]any); ok {+ msg.Parts = append(msg.Parts, openInferenceToolCall(c))+ }+ }+ if name := stringOf(m["function_call_name"]); name != "" {+ msg.Parts = append(msg.Parts, part(ToolCallRequestPart{Type: PartTypeToolCall, Name: name, Arguments: decode(m["function_call_arguments_json"])}))+ }+ return msg+}++// openInferenceContents converts the ordered message.contents items. A text item may come without+// message_content.type, as the collector-contrib normalizer reads it:+// https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/fc79b95297776dec6c47490cd6f6026b942bf6fb/processor/genainormalizerprocessor/internal/openinference/messages.go#L285+func openInferenceContents(m map[string]any) Parts {+ items := indexed(m, "contents")+ parts := make(Parts, 0, len(items))+ for _, item := range items {+ content, _ := item["message_content"].(map[string]any)+ typ := stringOf(content["type"])+ if typ == "" && content["text"] != nil {+ typ = "text"+ }+ switch typ {+ case "text":+ parts = append(parts, part(textPart(stringOf(content["text"]))))+ case "reasoning":+ parts = append(parts, part(ReasoningPart{Type: PartTypeReasoning, Content: stringOf(content["text"])}))+ case "image", "audio", "video":+ if url := stringOf(attribute(content, typ+"."+typ+".url")); url != "" {+ parts = append(parts, part(mediaPart(url, Modality{valuer.NewString(typ)})))+ }+ case "tool_use":+ default:+ parts = append(parts, part(GenericPart(content)))+ }+ }+ return parts+}++// openInferenceToolCall reads a tool_call.* object, {id, function: {name, arguments}}.+func openInferenceToolCall(call map[string]any) Part {+ fn, _ := call["function"].(map[string]any)+ p := ToolCallRequestPart{Type: PartTypeToolCall, Name: stringOf(fn["name"]), ID: optionalString(call["id"])}+ if args, ok := fn["arguments"]; ok {+ p.Arguments = decode(args)+ }+ return part(p)+}diff --git a/pkg/types/aiobservabilitytypes/message_format_openinference_test.go b/pkg/types/aiobservabilitytypes/message_format_openinference_test.gonew file mode 100644index 0000000000..c90d41e6ae--- /dev/null+++ b/pkg/types/aiobservabilitytypes/message_format_openinference_test.go@@ -0,0 +1,324 @@+package aiobservabilitytypes++import "testing"++// Captured cases are the llm.input_messages.N.* and llm.output_messages.N.* keys as the collector+// stored them for the SigNoz/scripts static-telemetry-generator captures.+func TestFormat_OpenInference(t *testing.T) {+ runFormatCases(t, []formatCase{+ {+ // openinference capture, ChatCompletion span: the flattened keys win over the raw request the+ // mapper moved onto gen_ai.input.messages+ name: "FlattenedMessages_RawRequestIgnored",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "system",+ "llm.input_messages.0.message.content": "You are concise.",+ "llm.input_messages.1.message.role": "user",+ "llm.input_messages.1.message.content": "Say hello in five words.",+ "llm.output_messages.0.message.role": "assistant",+ "llm.output_messages.0.message.content": "Hello! How are you today?",+ "llm.finish_reason": "stop",+ GenAIInputMessages: `{"messages": [{"role": "system", "content": "You are concise."}, {"role": "user", "content": "Say hello in five words."}], "model": "gpt-4o-mini", "max_tokens": 50, "temperature": 0.2}`,+ },+ wantInput: `[+ {"role": "system", "parts": [{"type": "text", "content": "You are concise."}]},+ {"role": "user", "parts": [{"type": "text", "content": "Say hello in five words."}]}+ ]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "text", "content": "Hello! How are you today?"}], "finish_reason": "stop"}]`,+ },+ {+ // openinference capture, ChatCompletion span: message.tool_calls and llm.finish_reason+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/tool_calling.md#L37+ name: "ToolCalls_ToolCallParts_FinishReasonFromLLMKey",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "user",+ "llm.input_messages.0.message.content": "What is the weather in Bengaluru in celsius?",+ "llm.output_messages.0.message.role": "assistant",+ "llm.output_messages.0.message.tool_calls.0.tool_call.id": "call_MdYKTRrkshuBG9W5oBXYZaRc",+ "llm.output_messages.0.message.tool_calls.0.tool_call.function.name": "get_current_weather",+ "llm.output_messages.0.message.tool_calls.0.tool_call.function.arguments": `{"city":"Bengaluru","unit":"c"}`,+ "llm.finish_reason": "tool_calls",+ },+ wantInput: `[{"role": "user", "parts": [{"type": "text", "content": "What is the weather in Bengaluru in celsius?"}]}]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "tool_call", "name": "get_current_weather", "id": "call_MdYKTRrkshuBG9W5oBXYZaRc", "arguments": {"city": "Bengaluru", "unit": "c"}}], "finish_reason": "tool_call"}]`,+ },+ {+ // openinference capture, the follow-up ChatCompletion span: tool role messages carry the result+ // in message.content with their tool_call_id+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/llm_spans.md#L50+ name: "ToolRoleMessages_ToolCallResponseParts",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "user",+ "llm.input_messages.0.message.content": "What's the weather in Paris and in London? Use the tool for each.",+ "llm.input_messages.1.message.role": "assistant",+ "llm.input_messages.1.message.tool_calls.0.tool_call.id": "call_SW4hst7nzysgvWSAz4OdyK9D",+ "llm.input_messages.1.message.tool_calls.0.tool_call.function.name": "get_current_weather",+ "llm.input_messages.1.message.tool_calls.0.tool_call.function.arguments": `{"city": "Paris"}`,+ "llm.input_messages.1.message.tool_calls.1.tool_call.id": "call_si8wiETYGpooMB7gMXSgMQpk",+ "llm.input_messages.1.message.tool_calls.1.tool_call.function.name": "get_current_weather",+ "llm.input_messages.1.message.tool_calls.1.tool_call.function.arguments": `{"city": "London"}`,+ "llm.input_messages.2.message.role": "tool",+ "llm.input_messages.2.message.tool_call_id": "call_SW4hst7nzysgvWSAz4OdyK9D",+ "llm.input_messages.2.message.content": `{"city": "Paris", "temp_c": 18, "summary": "Clear"}`,+ "llm.input_messages.3.message.role": "tool",+ "llm.input_messages.3.message.tool_call_id": "call_si8wiETYGpooMB7gMXSgMQpk",+ "llm.input_messages.3.message.content": `{"city": "London", "temp_c": 18, "summary": "Clear"}`,+ "llm.output_messages.0.message.role": "assistant",+ "llm.output_messages.0.message.content": "The current weather is as follows:\n\n- **Paris**: 18°C, Clear\n- **London**: 18°C, Clear",+ "llm.finish_reason": "stop",+ },+ wantInput: `[+ {"role": "user", "parts": [{"type": "text", "content": "What's the weather in Paris and in London? Use the tool for each."}]},+ {"role": "assistant", "parts": [+ {"type": "tool_call", "name": "get_current_weather", "id": "call_SW4hst7nzysgvWSAz4OdyK9D", "arguments": {"city": "Paris"}},+ {"type": "tool_call", "name": "get_current_weather", "id": "call_si8wiETYGpooMB7gMXSgMQpk", "arguments": {"city": "London"}}+ ]},+ {"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_SW4hst7nzysgvWSAz4OdyK9D", "response": {"city": "Paris", "temp_c": 18, "summary": "Clear"}}]},+ {"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_si8wiETYGpooMB7gMXSgMQpk", "response": {"city": "London", "temp_c": 18, "summary": "Clear"}}]}+ ]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "text", "content": "The current weather is as follows:\n\n- **Paris**: 18°C, Clear\n- **London**: 18°C, Clear"}], "finish_reason": "stop"}]`,+ },+ {+ // openinference capture, vision call; base64 trimmed. An image as a data URL:+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/multimodal_attributes.md#L47+ name: "ContentsTextAndImage_TextAndBlobParts",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "user",+ "llm.input_messages.0.message.contents.0.message_content.type": "text",+ "llm.input_messages.0.message.contents.0.message_content.text": "What animal is in this image? One sentence.",+ "llm.input_messages.0.message.contents.1.message_content.type": "image",+ "llm.input_messages.0.message.contents.1.message_content.image.image.url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD",+ "llm.output_messages.0.message.role": "assistant",+ "llm.output_messages.0.message.content": "The animal in the image is a duck.",+ "llm.finish_reason": "stop",+ },+ wantInput: `[{"role": "user", "parts": [+ {"type": "text", "content": "What animal is in this image? One sentence."},+ {"type": "blob", "modality": "image", "mime_type": "image/jpeg", "content": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD"}+ ]}]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "text", "content": "The animal in the image is a duck."}], "finish_reason": "stop"}]`,+ },+ {+ // openinference-openai-agents capture, Response span: one output message per item, an empty one+ // for a reasoning item without a summary+ name: "ResponsesOutputItems_AssistantMessagesFolded_EmptyDropped",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "system",+ "llm.input_messages.0.message.content": "You solve problems step by step and give a final answer.",+ "llm.input_messages.1.message.role": "user",+ "llm.input_messages.1.message.content": "A bat and a ball cost $1.10. How much is the ball?",+ "llm.output_messages.0.message.role": "assistant",+ "llm.output_messages.1.message.role": "assistant",+ "llm.output_messages.1.message.contents.0.message_content.type": "text",+ "llm.output_messages.1.message.contents.0.message_content.text": "Final Answer: The ball costs $0.05.",+ "llm.output_messages.2.message.role": "assistant",+ "llm.output_messages.2.message.tool_calls.0.tool_call.id": "call_1",+ "llm.output_messages.2.message.tool_calls.0.tool_call.function.name": "done",+ },+ wantInput: `[+ {"role": "system", "parts": [{"type": "text", "content": "You solve problems step by step and give a final answer."}]},+ {"role": "user", "parts": [{"type": "text", "content": "A bat and a ball cost $1.10. How much is the ball?"}]}+ ]`,+ wantOutput: `[{"role": "assistant", "parts": [+ {"type": "text", "content": "Final Answer: The ball costs $0.05."},+ {"type": "tool_call", "name": "done", "id": "call_1"}+ ]}]`,+ },+ {+ // openinference capture, the ChatCompletion span of a failed call+ name: "InputOnly_NoOutput",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "user",+ "llm.input_messages.0.message.content": "this should fail",+ },+ wantInput: `[{"role": "user", "parts": [{"type": "text", "content": "this should fail"}]}]`,+ wantOutput: `[]`,+ },+ {+ // the strands processor keeps the SDK's gen_ai.system_instructions on the span and inserts the same+ // prompt as message 0+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/python/instrumentation/openinference-instrumentation-strands-agents/src/openinference/instrumentation/strands_agents/processor.py#L152+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/python/instrumentation/openinference-instrumentation-strands-agents/src/openinference/instrumentation/strands_agents/processor.py#L293+ name: "StrandsSystemInstructionsRepeated_OneSystemMessage",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "system",+ "llm.input_messages.0.message.content": "You are concise.",+ "llm.input_messages.1.message.role": "user",+ "llm.input_messages.1.message.content": "hi",+ "llm.output_messages.0.message.role": "assistant",+ "llm.output_messages.0.message.content": "Hello.",+ GenAISystemInstructions: `[{"type": "text", "content": "You are concise."}]`,+ },+ wantInput: `[+ {"role": "system", "parts": [{"type": "text", "content": "You are concise."}]},+ {"role": "user", "parts": [{"type": "text", "content": "hi"}]}+ ]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "text", "content": "Hello."}]}]`,+ },+ {+ // pipecat writes the request as llm.input_messages and the streamed reply as output.value alone,+ // which the mapper copies onto gen_ai.output.messages+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/python/instrumentation/openinference-instrumentation-pipecat/src/openinference/instrumentation/pipecat/_attributes.py#L430+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/python/instrumentation/openinference-instrumentation-pipecat/src/openinference/instrumentation/pipecat/_observer.py#L628+ name: "OutputKeysAbsent_RawOutputFormatted_Warns",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "user",+ "llm.input_messages.0.message.content": "hi",+ GenAIOutputMessages: "Hello there.",+ },+ warnings: []string{"bare assistant text, role assumed", "output formatted as text, input as openinference"},+ wantInput: `[{"role": "user", "parts": [{"type": "text", "content": "hi"}]}]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "text", "content": "Hello there."}]}]`,+ },+ {+ // message.role left unset by some instrumentors: tool_call_id, tool_calls or neither decide it,+ // as the collector-contrib normalizer does+ // https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/fc79b95297776dec6c47490cd6f6026b942bf6fb/processor/genainormalizerprocessor/internal/openinference/messages.go#L473+ name: "MissingRole_InferredFromToolFields",+ attributes: map[string]any{+ "llm.input_messages.0.message.content": "Weather in Oslo?",+ "llm.input_messages.1.message.tool_calls.0.tool_call.id": "call_9",+ "llm.input_messages.1.message.tool_calls.0.tool_call.function.name": "get_weather",+ "llm.input_messages.1.message.tool_calls.0.tool_call.function.arguments": `{"city":"Oslo"}`,+ "llm.input_messages.2.message.tool_call_id": "call_9",+ "llm.input_messages.2.message.content": "4C, cloudy",+ },+ wantInput: `[+ {"role": "user", "parts": [{"type": "text", "content": "Weather in Oslo?"}]},+ {"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "id": "call_9", "arguments": {"city": "Oslo"}}]},+ {"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_9", "response": "4C, cloudy"}]}+ ]`,+ wantOutput: `[]`,+ },+ {+ // message_content.type left unset on text items by some instrumentors, as the collector-contrib+ // normalizer reads them+ // https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/fc79b95297776dec6c47490cd6f6026b942bf6fb/processor/genainormalizerprocessor/internal/openinference/messages.go#L285+ name: "UntypedContentWithText_TextPart",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "user",+ "llm.input_messages.0.message.contents.0.message_content.text": "Summarise this.",+ "llm.input_messages.0.message.contents.1.message_content.text": "Second block.",+ },+ wantInput: `[{"role": "user", "parts": [{"type": "text", "content": "Summarise this."}, {"type": "text", "content": "Second block."}]}]`,+ wantOutput: `[]`,+ },+ {+ // an image given by URL+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/multimodal_attributes.md#L42+ name: "ImageURL_UriPart",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "user",+ "llm.input_messages.0.message.contents.0.message_content.type": "image",+ "llm.input_messages.0.message.contents.0.message_content.image.image.url": "https://example.com/duck.jpg",+ },+ wantInput: `[{"role": "user", "parts": [{"type": "uri", "modality": "image", "uri": "https://example.com/duck.jpg"}]}]`,+ wantOutput: `[]`,+ },+ {+ // audio by URL with its transcript, or as the data URI built from a Chat Completions input_audio+ // block; the transcript has no part to go to+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/multimodal_attributes.md#L55+ name: "Audio_UriAndBlobParts_TranscriptDropped",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "user",+ "llm.input_messages.0.message.contents.0.message_content.type": "audio",+ "llm.input_messages.0.message.contents.0.message_content.audio.audio.url": "https://example.com/hello.mp3",+ "llm.input_messages.0.message.contents.0.message_content.audio.audio.transcript": "Hello, how are you?",+ "llm.input_messages.0.message.contents.1.message_content.type": "audio",+ "llm.input_messages.0.message.contents.1.message_content.audio.audio.url": "data:audio/wav;base64,UklGRg==",+ },+ wantInput: `[{"role": "user", "parts": [+ {"type": "uri", "modality": "audio", "uri": "https://example.com/hello.mp3"},+ {"type": "blob", "modality": "audio", "mime_type": "audio/wav", "content": "UklGRg=="}+ ]}]`,+ wantOutput: `[]`,+ },+ {+ // reasoning items; id, signature, data and encrypted_content have no field on the reasoning part+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/llm_spans.md#L181+ name: "Reasoning_ReasoningParts_ProviderKeysDropped",+ attributes: map[string]any{+ "llm.output_messages.0.message.role": "assistant",+ "llm.output_messages.0.message.contents.0.message_content.type": "reasoning",+ "llm.output_messages.0.message.contents.0.message_content.text": "The ball must cost less than a dollar.",+ "llm.output_messages.0.message.contents.0.message_content.signature": "EuYBCkQYAiJA",+ "llm.output_messages.0.message.contents.1.message_content.type": "reasoning",+ "llm.output_messages.0.message.contents.1.message_content.data": "EmwKAhgBEgy3",+ "llm.output_messages.0.message.contents.2.message_content.type": "reasoning",+ "llm.output_messages.0.message.contents.2.message_content.id": "rs_abc123",+ "llm.output_messages.0.message.contents.2.message_content.encrypted_content": "gAAAAA==",+ "llm.output_messages.0.message.contents.3.message_content.type": "text",+ "llm.output_messages.0.message.contents.3.message_content.text": "The ball costs 5 cents.",+ },+ wantInput: `[]`,+ wantOutput: `[{"role": "assistant", "parts": [+ {"type": "reasoning", "content": "The ball must cost less than a dollar."},+ {"type": "reasoning", "content": ""},+ {"type": "reasoning", "content": ""},+ {"type": "text", "content": "The ball costs 5 cents."}+ ]}]`,+ },+ {+ // a tool call repeated as an ordered tool_use content item; message.tool_calls stays the one+ // source. llm.finish_reason is Anthropic's stop_reason as the instrumentation passes it through+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/tool_calling.md#L63+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/python/instrumentation/openinference-instrumentation-anthropic/src/openinference/instrumentation/anthropic/_wrappers.py#L938+ name: "ToolUseBesideToolCalls_OneToolCallPart",+ attributes: map[string]any{+ "llm.output_messages.0.message.role": "assistant",+ "llm.output_messages.0.message.contents.0.message_content.type": "text",+ "llm.output_messages.0.message.contents.0.message_content.text": "Let me check.",+ "llm.output_messages.0.message.contents.1.message_content.type": "tool_use",+ "llm.output_messages.0.message.contents.1.tool_call.id": "toolu_01",+ "llm.output_messages.0.message.contents.1.tool_call.function.name": "get_weather",+ "llm.output_messages.0.message.contents.1.tool_call.function.arguments": `{"city": "Paris"}`,+ "llm.output_messages.0.message.tool_calls.0.tool_call.id": "toolu_01",+ "llm.output_messages.0.message.tool_calls.0.tool_call.function.name": "get_weather",+ "llm.output_messages.0.message.tool_calls.0.tool_call.function.arguments": `{"city": "Paris"}`,+ "llm.finish_reason": "tool_use",+ },+ wantInput: `[]`,+ wantOutput: `[{"role": "assistant", "parts": [+ {"type": "text", "content": "Let me check."},+ {"type": "tool_call", "name": "get_weather", "id": "toolu_01", "arguments": {"city": "Paris"}}+ ], "finish_reason": "tool_call"}]`,+ },+ {+ // a content type the spec does not name is kept as sent+ name: "UnknownContentType_GenericPart",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "user",+ "llm.input_messages.0.message.contents.0.message_content.type": "document",+ "llm.input_messages.0.message.contents.0.message_content.document.document.id": "file_1",+ },+ wantInput: `[{"role": "user", "parts": [{"type": "document", "document": {"document": {"id": "file_1"}}}]}]`,+ wantOutput: `[]`,+ },+ {+ // the legacy function_call keys+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/semantic_conventions.md#L111+ name: "LegacyFunctionCall_ToolCallPart",+ attributes: map[string]any{+ "llm.output_messages.0.message.role": "assistant",+ "llm.output_messages.0.message.function_call_name": "multiply",+ "llm.output_messages.0.message.function_call_arguments_json": `{"x": 2}`,+ },+ wantInput: `[]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "tool_call", "name": "multiply", "arguments": {"x": 2}}]}]`,+ },+ {+ // a tool result with message.name naming the function+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/llm_spans.md#L50+ name: "ToolResultWithName_NameKept",+ attributes: map[string]any{+ "llm.input_messages.0.message.role": "tool",+ "llm.input_messages.0.message.name": "multiply",+ "llm.input_messages.0.message.tool_call_id": "call_62136355",+ "llm.input_messages.0.message.content": "2001",+ },+ wantInput: `[{"role": "tool", "name": "multiply", "parts": [{"type": "tool_call_response", "id": "call_62136355", "response": "2001"}]}]`,+ wantOutput: `[]`,+ },+ })+}diff --git a/pkg/types/aiobservabilitytypes/message_format_test.go b/pkg/types/aiobservabilitytypes/message_format_test.goindex 3ae76537ee..a62bf8f0e8 100644--- a/pkg/types/aiobservabilitytypes/message_format_test.go+++ b/pkg/types/aiobservabilitytypes/message_format_test.go@@ -121,6 +121,31 @@ So, the ball costs 5 cents.`,})}+func TestIndexed(t *testing.T) {+ testCases := []struct {+ name string+ doc map[string]any+ want []map[string]any+ }{+ {+ name: "NumericKeys_SortedNumerically",+ doc: document(map[string]any{"llm.input_messages.10.message.role": "user", "llm.input_messages.2.message.role": "system", "llm.input_messages.x.message.role": "skipped"}),+ want: []map[string]any{{"message": map[string]any{"role": "system"}}, {"message": map[string]any{"role": "user"}}},+ },+ {+ name: "StructuredList_KeptInOrder",+ doc: map[string]any{"llm": map[string]any{"input_messages": []any{map[string]any{"message": "b"}, map[string]any{"message": "a"}, "not an object"}}},+ want: []map[string]any{{"message": "b"}, {"message": "a"}},+ },+ {name: "Absent_Empty", doc: map[string]any{}, want: []map[string]any{}},+ }+ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ assert.Equal(t, testCase.want, indexed(testCase.doc, openInferenceInputMessages))+ })+ }+}+func TestFormat_SystemInstructions(t *testing.T) {input := `[{"role":"user","parts":[{"type":"text","content":"hi"}]}]`runFormatCases(t, []formatCase{diff --git a/tests/integration/tests/tracedetail/02_thread.py b/tests/integration/tests/tracedetail/02_thread.pyindex fd0d0d7b15..97154ad9f2 100644--- a/tests/integration/tests/tracedetail/02_thread.py+++ b/tests/integration/tests/tracedetail/02_thread.py@@ -21,7 +21,7 @@ def test_thread_returns_gen_ai_spans_in_order(seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)now = datetime.now(tz=UTC).replace(microsecond=0)trace_id = TraceIdGenerator.trace_id()- root_id, first_llm_id, tool_id, agent_id, second_llm_id, third_llm_id = (TraceIdGenerator.span_id() for _ in range(6))+ root_id, first_llm_id, tool_id, agent_id, second_llm_id, third_llm_id, flattened_llm_id = (TraceIdGenerator.span_id() for _ in range(7))resources = {"service.name": "tracedetail-thread"}first_input = json.dumps([{"role": "user", "parts": [{"type": "text", "content": "weather in Bangalore?"}]}])first_output = json.dumps([{"role": "assistant", "parts": [{"type": "tool_call", "id": "call_1", "name": "get_weather", "arguments": {"city": "Bangalore"}}]}])@@ -54,6 +54,23 @@ def test_thread_returns_gen_ai_spans_in_order(Traces(timestamp=now - timedelta(seconds=5), trace_id=trace_id, span_id=agent_id, parent_span_id=root_id, name="invoke_agent planner", resources=resources, attributes={"gen_ai.agent.name": "planner"}, attribute_write_mode="json_only"),Traces(timestamp=now - timedelta(seconds=4), trace_id=trace_id, span_id=second_llm_id, parent_span_id=root_id, name="chat gpt-4o", resources=resources, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.input.messages": second_input}, attribute_write_mode="json_only"),Traces(timestamp=now - timedelta(seconds=2), trace_id=trace_id, span_id=third_llm_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."}, attribute_write_mode="json_only"),+ Traces(+ timestamp=now - timedelta(seconds=1),+ trace_id=trace_id,+ span_id=flattened_llm_id,+ parent_span_id=root_id,+ name="ChatCompletion",+ resources=resources,+ attributes={+ "gen_ai.request.model": "gpt-4o",+ "llm.input_messages.0.message.role": "user",+ "llm.input_messages.0.message.content": "thanks",+ "llm.output_messages.0.message.role": "assistant",+ "llm.output_messages.0.message.content": "You're welcome.",+ "llm.finish_reason": "stop",+ },+ attribute_write_mode="json_only",+ ),])@@ -62,10 +79,10 @@ def test_thread_returns_gen_ai_spans_in_order(assert response.status_code == HTTPStatus.OK, response.textthread = response.json()["data"]- assert [span["span_id"] for span in thread["spans"]] == [first_llm_id, tool_id, agent_id, second_llm_id, third_llm_id]+ assert [span["span_id"] for span in thread["spans"]] == [first_llm_id, tool_id, agent_id, second_llm_id, third_llm_id, flattened_llm_id]assert "nextCursor" not in thread- first, tool, agent, input_only, output_only = thread["spans"]+ first, tool, agent, input_only, output_only, flattened = thread["spans"]assert agent["attributes"]["gen_ai.agent.name"] == "planner"assert agent["formattedInput"] == []assert agent["formattedOutput"] == []@@ -91,6 +108,9 @@ def test_thread_returns_gen_ai_spans_in_order(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"]+ assert flattened["attributes"]["llm.input_messages.0.message.content"] == "thanks"+ assert flattened["formattedInput"] == [{"role": "user", "parts": [{"type": "text", "content": "thanks"}]}]+ assert flattened["formattedOutput"] == [{"role": "assistant", "parts": [{"type": "text", "content": "You're welcome."}], "finish_reason": "stop"}]def test_thread_paginates_with_cursors(