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 gen_ai system instructions and finish reasons (#13131)
Nityananda Gohaineeb57ceff247
diff --git a/pkg/types/aiobservabilitytypes/keys.go b/pkg/types/aiobservabilitytypes/keys.goindex ac4475dd31..0ae2b9297d 100644--- a/pkg/types/aiobservabilitytypes/keys.go+++ b/pkg/types/aiobservabilitytypes/keys.go@@ -17,8 +17,10 @@ const (GenAIUsageCacheCreationInputTokens = "gen_ai.usage.cache_creation.input_tokens"GenAIUsageReasoningOutputTokens = "gen_ai.usage.reasoning.output_tokens"- GenAIInputMessages = "gen_ai.input.messages"- GenAIOutputMessages = "gen_ai.output.messages"+ GenAIInputMessages = "gen_ai.input.messages"+ GenAIOutputMessages = "gen_ai.output.messages"+ GenAISystemInstructions = "gen_ai.system_instructions"+ GenAIResponseFinishReasons = "gen_ai.response.finish_reasons"GenAIToolCallID = "gen_ai.tool.call.id"GenAIToolCallArguments = "gen_ai.tool.call.arguments"diff --git a/pkg/types/aiobservabilitytypes/message.go b/pkg/types/aiobservabilitytypes/message.goindex d12a0af891..ce13890d3c 100644--- a/pkg/types/aiobservabilitytypes/message.go+++ b/pkg/types/aiobservabilitytypes/message.go@@ -1,5 +1,6 @@// The message types mirror the OpenTelemetry GenAI message schemas, one type per schema definition:-// open-telemetry/semantic-conventions-genai@06ec68e, model/gen-ai/gen-ai-{input,output}-messages.json.+// https://github.com/open-telemetry/semantic-conventions-genai/blob/06ec68e722c45a7218e23ea1bc1339fe4e21ecae/model/gen-ai/gen-ai-input-messages.json+// https://github.com/open-telemetry/semantic-conventions-genai/blob/06ec68e722c45a7218e23ea1bc1339fe4e21ecae/model/gen-ai/gen-ai-output-messages.json// Keys the schema does not name are dropped; the raw attribute on the span still has them.package aiobservabilitytypesdiff --git a/pkg/types/aiobservabilitytypes/message_format.go b/pkg/types/aiobservabilitytypes/message_format.goindex 05108857aa..c165b4fd55 100644--- a/pkg/types/aiobservabilitytypes/message_format.go+++ b/pkg/types/aiobservabilitytypes/message_format.go@@ -18,9 +18,13 @@ const (var dataURL = regexp.MustCompile(`^data:([^;,]+);base64,(.+)$`)-// Provider spellings of the finish reasons; the enum values themselves pass through.+// 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:+// 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, "function_call": FinishReasonToolCall, "tool-calls": FinishReasonToolCall,"end_turn": FinishReasonStop, "stop_sequence": FinishReasonStop,"max_tokens": FinishReasonLength,}@@ -36,7 +40,8 @@ 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.+// 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.func FormatMessages(attributes map[string]any) FormattedMessages {f := &formatting{attributes: attributes, out: FormattedMessages{Input: InputMessages{}, Output: OutputMessages{}, Warnings: []string{}}}switch {@@ -45,6 +50,8 @@ func FormatMessages(attributes map[string]any) FormattedMessages {case attribute(f.attributes, GenAIInputMessages) != nil || attribute(f.attributes, GenAIOutputMessages) != nil:f.messages()}+ f.prependSystemInstructions()+ f.fillFinishReasons()return f.out}@@ -75,6 +82,45 @@ func (f *formatting) messages() {}}+// prependSystemInstructions adds gen_ai.system_instructions, a list of parts, as a leading system message,+// unless the input already starts with a system message of the same text: the OpenInference strands+// processor keeps the attribute and inserts it as message 0 as well. A span without messages, such as+// create_agent, stays without them.+// https://github.com/open-telemetry/semantic-conventions-genai/blob/06ec68e722c45a7218e23ea1bc1339fe4e21ecae/model/gen-ai/gen-ai-system-instructions.json+// 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+func (f *formatting) prependSystemInstructions() {+ raw := attribute(f.attributes, GenAISystemInstructions)+ if raw == nil || (len(f.out.Input) == 0 && len(f.out.Output) == 0) {+ return+ }+ parts := systemParts(decode(raw))+ if len(parts) == 0 || (len(f.out.Input) > 0 && f.out.Input[0].Role == RoleSystem && textOf(f.out.Input[0].Parts) == textOf(parts)) {+ return+ }+ f.out.Input = append(InputMessages{{Role: RoleSystem, Parts: parts}}, f.out.Input...)+}++// fillFinishReasons applies gen_ai.response.finish_reasons, one entry per output message, over+// whatever the converter found in the payload.+// https://github.com/open-telemetry/semantic-conventions-genai/blob/06ec68e722c45a7218e23ea1bc1339fe4e21ecae/model/gen-ai/registry.yaml#L210+func (f *formatting) fillFinishReasons() {+ raw := attribute(f.attributes, GenAIResponseFinishReasons)+ if raw == nil || len(f.out.Output) == 0 {+ return+ }+ reasons := stringList(decode(raw))+ if len(reasons) != len(f.out.Output) {+ f.warn("gen_ai.response.finish_reasons has %d entries for %d output messages", len(reasons), len(f.out.Output))+ return+ }+ for i, reason := range reasons {+ if fr := finishReason(reason); fr != nil {+ f.out.Output[i].FinishReason = fr+ }+ }+}+// side converts one attribute value by its shape; role is what a bare string on this side is// spoken as.func (f *formatting) side(value any, role Role) (OutputMessages, string) {@@ -179,6 +225,23 @@ func finishReason(value string) *FinishReason {return &fr}+// stringList reads a list of strings, or a bare string as a list of one.+func stringList(value any) []string {+ switch v := value.(type) {+ case []any:+ out := make([]string, 0, len(v))+ for _, item := range v {+ out = append(out, stringOf(item))+ }+ return out+ case string:+ if v != "" {+ return []string{v}+ }+ }+ return nil+}+func optionalString(value any) *string {s := stringOf(value)if s == "" {@@ -195,8 +258,37 @@ func textPart(content string) TextPart {return TextPart{Type: PartTypeText, Content: content}}-// contentPart converts one OpenAI content block, which semconv parts may also carry; a block of-// any other type is kept as sent.+// textOf joins the text parts, for comparing a system message with gen_ai.system_instructions.+func textOf(parts Parts) string {+ var texts []string+ for _, p := range parts {+ if t, ok := p.Value.(TextPart); ok {+ texts = append(texts, t.Content)+ }+ }+ return strings.Join(texts, "\n")+}++// systemParts reads a system prompt given outside the history, a list of parts or a bare string.+func systemParts(value any) Parts {+ switch v := value.(type) {+ case []any:+ parts := make(Parts, 0, len(v))+ for _, item := range v {+ parts = append(parts, contentPart(item))+ }+ return parts+ case string:+ if v != "" {+ return Parts{part(textPart(v))}+ }+ }+ return nil+}++// contentPart converts one OpenAI content block, which semconv parts may also carry; a text part+// in the semconv spelling has content where OpenAI has text. A block of any other type is kept+// as sent.func contentPart(item any) Part {p, ok := item.(map[string]any)if !ok {@@ -207,6 +299,9 @@ func contentPart(item any) Part {}switch stringOf(p["type"]) {case "text":+ if p["text"] == nil {+ return part(textPart(stringOf(p["content"])))+ }return part(textPart(stringOf(p["text"])))case "refusal":return part(textPart(stringOf(p["refusal"])))diff --git a/pkg/types/aiobservabilitytypes/message_format_openai_chat_test.go b/pkg/types/aiobservabilitytypes/message_format_openai_chat_test.goindex 7b01b48c97..ec64b127fe 100644--- a/pkg/types/aiobservabilitytypes/message_format_openai_chat_test.go+++ b/pkg/types/aiobservabilitytypes/message_format_openai_chat_test.go@@ -167,7 +167,8 @@ func TestFormat_OpenAIChat(t *testing.T) {]`,},{- // openinference capture, input.value of the ChatCompletion span+ // ChatCompletionRequestMessageContentPartFile {file: {file_id}}, as OpenInference records the request in input.value:+ // https://github.com/openai/openai-openapi/blob/aeb6a041dc56c011ca9f12127ec898f911100aa0/openapi.yaml#L42650name: "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":[]}}]}`,@@ -189,7 +190,8 @@ func TestFormat_OpenAIChat(t *testing.T) {]`,},{- // openinference capture, input.value of the ChatCompletion span+ // ChatCompletionRequestMessageContentPartFile {file: {filename, file_data}}, file_data a data URL:+ // https://github.com/openai/openai-openapi/blob/aeb6a041dc56c011ca9f12127ec898f911100aa0/openapi.yaml#L42650name: "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: `[diff --git a/pkg/types/aiobservabilitytypes/message_format_semconv.go b/pkg/types/aiobservabilitytypes/message_format_semconv.goindex 3f004de9f9..dd286d67d7 100644--- a/pkg/types/aiobservabilitytypes/message_format_semconv.go+++ b/pkg/types/aiobservabilitytypes/message_format_semconv.go@@ -6,15 +6,20 @@ import ()// Format: the OTel shape itself, [{role, parts}].-// Written by: litellm, langchain, openllmetry, portkey, traceloop LLM spans.-// Decoding is the genai types. Repairs: "text" used for "content" on text parts; OpenAI content-// blocks left inside parts.-// Not yet: "thinking" for "reasoning"; "result" or "output" for "response" on tool call responses.+// Written by: litellm, langchain, openllmetry, portkey, traceloop LLM spans, pydantic-ai.+// Decoding is the genai types. Repairs: "text" used for "content" on text parts; OpenAI content blocks+// left inside parts; tool call arguments as a JSON string and "result" for "response", as pydantic-ai+// writes them:+// https://github.com/pydantic/pydantic-ai/blob/9ac853bb84ffed7ba0edccb026c5b4f3228c1de7/pydantic_ai_slim/pydantic_ai/messages.py#L3130+// https://github.com/pydantic/pydantic-ai/blob/9ac853bb84ffed7ba0edccb026c5b4f3228c1de7/pydantic_ai_slim/pydantic_ai/messages.py#L1724+// The choice finish_reason as the provider spells it, as litellm copies it:+// https://github.com/BerriAI/litellm/blob/9d72bae336ec0d14c41651adcb0d2e1149721f46/litellm/integrations/opentelemetry.py#L2822+// Not yet: "thinking" for "reasoning".// semconv decodes messages that already follow the schema through the genai types. A part of a// type the schema does not name is a provider content block, which contentPart converts.func (f *formatting) semconv(list []any) OutputMessages {- data, err := json.Marshal(semconvTextKey(list))+ data, err := json.Marshal(semconvRepairs(list))if err != nil {f.warn("messages could not be encoded: %s", err)return OutputMessages{genericMessage(list)}@@ -28,6 +33,9 @@ func (f *formatting) semconv(list []any) OutputMessages {if msgs[i].Parts == nil {msgs[i].Parts = Parts{}}+ if msgs[i].FinishReason != nil {+ msgs[i].FinishReason = finishReason(msgs[i].FinishReason.StringValue())+ }for j, p := range msgs[i].Parts {if block, ok := p.Value.(GenericPart); ok {msgs[i].Parts[j] = contentPart(map[string]any(block))@@ -37,9 +45,9 @@ func (f *formatting) semconv(list []any) OutputMessages {return msgs}-// semconvTextKey copies the text and reasoning parts some SDKs write with "text" in place of the-// schema's "content". The input is left untouched, it is also the span's raw attribute.-func semconvTextKey(list []any) []any {+// semconvRepairs copies the parts whose keys SDKs misspell into the schema's spelling. The input+// is left untouched, it is also the span's raw attribute.+func semconvRepairs(list []any) []any {out := make([]any, 0, len(list))for _, item := range list {m, ok := item.(map[string]any)@@ -50,13 +58,8 @@ func semconvTextKey(list []any) []any {}fixedParts := make([]any, 0, len(parts))for _, p := range parts {- part, ok := p.(map[string]any)- typ := stringOf(part["type"])- if ok && (typ == "text" || typ == "reasoning") && part["content"] == nil && part["text"] != nil {- fixed := maps.Clone(part)- fixed["content"] = fixed["text"]- delete(fixed, "text")- p = fixed+ if part, ok := p.(map[string]any); ok {+ p = semconvRepairPart(part)}fixedParts = append(fixedParts, p)}@@ -66,3 +69,24 @@ func semconvTextKey(list []any) []any {}return out}++func semconvRepairPart(part map[string]any) map[string]any {+ fixed := maps.Clone(part)+ switch stringOf(part["type"]) {+ case "text", "reasoning":+ if part["content"] == nil && part["text"] != nil {+ fixed["content"] = fixed["text"]+ delete(fixed, "text")+ }+ case "tool_call":+ if args, ok := part["arguments"].(string); ok {+ fixed["arguments"] = decode(args)+ }+ case "tool_call_response":+ if _, ok := part["response"]; !ok && part["result"] != nil {+ fixed["response"] = part["result"]+ delete(fixed, "result")+ }+ }+ return fixed+}diff --git a/pkg/types/aiobservabilitytypes/message_format_semconv_test.go b/pkg/types/aiobservabilitytypes/message_format_semconv_test.goindex 182b51c35e..8ff1dece68 100644--- a/pkg/types/aiobservabilitytypes/message_format_semconv_test.go+++ b/pkg/types/aiobservabilitytypes/message_format_semconv_test.go@@ -157,3 +157,34 @@ func TestFormat_Semconv(t *testing.T) {},})}++func TestFormat_Semconv_Repairs(t *testing.T) {+ runFormatCases(t, []formatCase{+ {+ // pydantic-ai keeps string tool call arguments as sent, writes the tool result under result, and the+ // instructions as a gen_ai.system_instructions text part:+ // https://github.com/pydantic/pydantic-ai/blob/9ac853bb84ffed7ba0edccb026c5b4f3228c1de7/pydantic_ai_slim/pydantic_ai/messages.py#L3130+ // https://github.com/pydantic/pydantic-ai/blob/9ac853bb84ffed7ba0edccb026c5b4f3228c1de7/pydantic_ai_slim/pydantic_ai/messages.py#L1724+ // https://github.com/pydantic/pydantic-ai/blob/9ac853bb84ffed7ba0edccb026c5b4f3228c1de7/pydantic_ai_slim/pydantic_ai/models/instrumented.py#L292+ name: "PydanticAI_ArgumentsDecoded_ResultBecomesResponse_InstructionsLead",+ input: `[{"role":"user","parts":[{"type":"text","content":"Weather in Paris?"}]},{"role":"assistant","parts":[{"type":"tool_call","id":"call_stub1","name":"get_weather","arguments":"{\"city\": \"Paris\"}"}],"finish_reason":"tool_call"},{"role":"user","parts":[{"type":"tool_call_response","id":"call_stub1","name":"get_weather","result":{"city":"Paris","temp_c":18}}]}]`,+ output: `[{"role":"assistant","parts":[{"type":"text","content":"Paris is clear at 18C."}],"finish_reason":"stop"}]`,+ attributes: map[string]any{GenAISystemInstructions: `[{"type":"text","content":"Use the tool."}]`},+ wantInput: `[+ {"role": "system", "parts": [{"type": "text", "content": "Use the tool."}]},+ {"role": "user", "parts": [{"type": "text", "content": "Weather in Paris?"}]},+ {"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "id": "call_stub1", "arguments": {"city": "Paris"}}]},+ {"role": "user", "parts": [{"type": "tool_call_response", "id": "call_stub1", "response": {"city": "Paris", "temp_c": 18}}]}+ ]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "text", "content": "Paris is clear at 18C."}], "finish_reason": "stop"}]`,+ },+ {+ // litellm copies the choice finish_reason into the semconv message as OpenAI spells it:+ // https://github.com/BerriAI/litellm/blob/9d72bae336ec0d14c41651adcb0d2e1149721f46/litellm/integrations/opentelemetry.py#L2822+ name: "LiteLLMFinishReasonSpelling_Normalised",+ output: `[{"role": "assistant", "parts": [], "finish_reason": "tool_calls"}]`,+ wantInput: `[]`,+ wantOutput: `[{"role": "assistant", "parts": [], "finish_reason": "tool_call"}]`,+ },+ })+}diff --git a/pkg/types/aiobservabilitytypes/message_format_test.go b/pkg/types/aiobservabilitytypes/message_format_test.goindex 5aee4b73ce..3ae76537ee 100644--- a/pkg/types/aiobservabilitytypes/message_format_test.go+++ b/pkg/types/aiobservabilitytypes/message_format_test.go@@ -120,3 +120,83 @@ So, the ball costs 5 cents.`,},})}++func TestFormat_SystemInstructions(t *testing.T) {+ input := `[{"role":"user","parts":[{"type":"text","content":"hi"}]}]`+ runFormatCases(t, []formatCase{+ {+ // the langchain instrumentation moves system messages out of the history into gen_ai.system_instructions,+ // a JSON list of parts:+ // https://github.com/traceloop/openllmetry/blob/93429cfb9767e6b51db6cb35f6b70f758117669a/packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/span_utils.py#L304+ name: "ListOfParts_LeadsInput",+ input: input,+ attributes: map[string]any{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: `[]`,+ },+ {+ // the OpenInference strands processor keeps 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: "SameTextLeadsInput_Skipped",+ input: `[{"role":"system","parts":[{"type":"text","content":"You are concise."}]},{"role":"user","parts":[{"type":"text","content":"hi"}]}]`,+ attributes: map[string]any{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: `[]`,+ },+ {+ name: "BareString_TextPart",+ input: input,+ attributes: map[string]any{GenAISystemInstructions: "be brief"},+ wantInput: `[+ {"role": "system", "parts": [{"type": "text", "content": "be brief"}]},+ {"role": "user", "parts": [{"type": "text", "content": "hi"}]}+ ]`,+ wantOutput: `[]`,+ },+ {+ // a create_agent span carries instructions alone+ name: "NoMessages_Nothing",+ attributes: map[string]any{GenAISystemInstructions: "be brief"},+ wantInput: `[]`,+ wantOutput: `[]`,+ },+ })+}++func TestFormat_FinishReasons(t *testing.T) {+ output := `[{"role":"assistant","parts":[{"type":"text","content":"a"}],"finish_reason":"stop"},{"role":"assistant","parts":[{"type":"text","content":"b"}]}]`+ runFormatCases(t, []formatCase{+ {+ name: "List_OverridesMessages",+ output: output,+ attributes: map[string]any{GenAIResponseFinishReasons: []any{"tool_calls", "length"}},+ wantInput: `[]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "text", "content": "a"}], "finish_reason": "tool_call"}, {"role": "assistant", "parts": [{"type": "text", "content": "b"}], "finish_reason": "length"}]`,+ },+ {+ name: "LengthMismatch_LeavesMessages_Warns",+ output: output,+ attributes: map[string]any{GenAIResponseFinishReasons: []any{"stop"}},+ warnings: []string{"gen_ai.response.finish_reasons has 1 entries for 2 output messages"},+ wantInput: `[]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "text", "content": "a"}], "finish_reason": "stop"}, {"role": "assistant", "parts": [{"type": "text", "content": "b"}]}]`,+ },+ {+ // llm.finish_reason copied by the mapper as a bare string, in the Vercel AI SDK spelling:+ // https://github.com/vercel/ai/blob/a5e92fe3c692f8e152fe1eb9ef50a4e734ad0ffb/packages/provider/src/language-model/v2/language-model-v2-finish-reason.ts+ name: "BareString_SingleChoice",+ output: `{"choices":[{"finish_reason":"stop","message":{"role":"assistant","content":"hi"}}]}`,+ attributes: map[string]any{GenAIResponseFinishReasons: "tool-calls"},+ wantInput: `[]`,+ wantOutput: `[{"role": "assistant", "parts": [{"type": "text", "content": "hi"}], "finish_reason": "tool_call"}]`,+ },+ })+}diff --git a/pkg/types/aiobservabilitytypes/message_format_tool.go b/pkg/types/aiobservabilitytypes/message_format_tool.goindex 0ddedb61fb..b9fd42953d 100644--- a/pkg/types/aiobservabilitytypes/message_format_tool.go+++ b/pkg/types/aiobservabilitytypes/message_format_tool.go@@ -1,12 +1,15 @@package aiobservabilitytypes// Format: gen_ai.tool.call.arguments and gen_ai.tool.call.result on an execute_tool span, each an-// object or its JSON string (open-telemetry/semantic-conventions-genai@06ec68e, model/gen-ai/registry.yaml).+// object or its JSON string:+// https://github.com/open-telemetry/semantic-conventions-genai/blob/06ec68e722c45a7218e23ea1bc1339fe4e21ecae/model/gen-ai/registry.yaml#L545// Written by: opentelemetry-instrumentation-langchain, traceloop @tool, OpenInference TOOL spans and// Vercel ai.toolCall.* through the span mapper.-// Envelopes unwrapped: LangChain's callback payloads, {input_str, tags, metadata, inputs, kwargs} and-// {output, kwargs} (openllmetry callback_handler.py on_tool_start/on_tool_end), and the traceloop-// decorator's {args, kwargs} (traceloop-sdk decorators/base.py _handle_span_input).+// Envelopes unwrapped: LangChain's on_tool_start and on_tool_end payloads, {input_str, tags, metadata,+// inputs, kwargs} and {output, kwargs}:+// https://github.com/traceloop/openllmetry/blob/93429cfb9767e6b51db6cb35f6b70f758117669a/packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py#L837+// The traceloop decorator's {args, kwargs}:+// https://github.com/traceloop/openllmetry/blob/93429cfb9767e6b51db6cb35f6b70f758117669a/packages/traceloop-sdk/traceloop/sdk/decorators/base.py#L169// tool renders the call as an assistant tool_call and the result as a tool tool_call_response, both// carrying gen_ai.tool.call.id so the pair can be matched.diff --git a/pkg/types/aiobservabilitytypes/message_format_tool_test.go b/pkg/types/aiobservabilitytypes/message_format_tool_test.goindex c5eb2553e6..64432e843f 100644--- a/pkg/types/aiobservabilitytypes/message_format_tool_test.go+++ b/pkg/types/aiobservabilitytypes/message_format_tool_test.go@@ -7,8 +7,9 @@ import "testing"func TestFormat_Tool(t *testing.T) {runFormatCases(t, []formatCase{{- // langchain capture, execute_tool get_weather span; opentelemetry-instrumentation-langchain- // callback_handler.py on_tool_start/on_tool_end envelopes+ // gen_ai.tool.call.arguments and gen_ai.tool.call.result written by the langchain instrumentation itself,+ // wrapped in its on_tool_start and on_tool_end payloads:+ // https://github.com/traceloop/openllmetry/blob/93429cfb9767e6b51db6cb35f6b70f758117669a/packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py#L837name: "LangChainEnvelopes_InputsAndOutputUnwrapped",attributes: map[string]any{GenAIToolName: "get_weather",@@ -19,8 +20,9 @@ func TestFormat_Tool(t *testing.T) {wantOutput: `[{"role": "tool", "parts": [{"type": "tool_call_response", "response": {"city": "Bengaluru", "temp_c": 18, "summary": "Clear"}}]}]`,},{- // openllmetry capture, get_weather.tool span; traceloop-sdk decorators/base.py- // _handle_span_input {args, kwargs} and the result encoded as a JSON string twice+ // traceloop.entity.input and traceloop.entity.output from the @tool decorator, renamed by the mapper;+ // the tool returned a JSON string, which json.dumps encoded again:+ // https://github.com/traceloop/openllmetry/blob/93429cfb9767e6b51db6cb35f6b70f758117669a/packages/traceloop-sdk/traceloop/sdk/decorators/base.py#L169name: "TraceloopDecorator_KwargsUnwrapped_ResultDecodedTwice",attributes: map[string]any{GenAIToolName: "get_weather",@@ -31,8 +33,8 @@ func TestFormat_Tool(t *testing.T) {wantOutput: `[{"role": "tool", "parts": [{"type": "tool_call_response", "response": {"city": "Bengaluru", "temp_c": 28, "summary": "Partly cloudy"}}]}]`,},{- // a decorated function returning None is json.dumps(None); the openllmetry capture shows it on- // workflow spans, with this positional-args input+ // traceloop.entity.output of a @tool returning None, json.dumps(None), renamed by the mapper:+ // https://github.com/traceloop/openllmetry/blob/93429cfb9767e6b51db6cb35f6b70f758117669a/packages/traceloop-sdk/traceloop/sdk/decorators/base.py#L185name: "TraceloopDecorator_PositionalArgsOnly_ListKept",attributes: map[string]any{GenAIToolName: "lookup",@@ -52,8 +54,8 @@ func TestFormat_Tool(t *testing.T) {wantOutput: `[]`,},{- // openinference-openai-agents capture, get_weather TOOL span: input.value and output.value- // copied by the mapper (Arize-ai/openinference@12f2cc03, spec/traces.md)+ // input.value and output.value of an OpenInference TOOL span, renamed by the mapper:+ // https://github.com/Arize-ai/openinference/blob/12f2cc035edfb00b60b656d977f07abfb7a69900/spec/traces.mdname: "OpenInferenceToolSpan_PlainJSONAndText",attributes: map[string]any{GenAIToolName: "get_weather",@@ -64,8 +66,8 @@ func TestFormat_Tool(t *testing.T) {wantOutput: `[{"role": "tool", "parts": [{"type": "tool_call_response", "response": "27C, partly cloudy, light breeze from the south."}]}]`,},{- // vercel capture, ai.toolCall span: ai.toolCall.{id,name,args,result} copied by the mapper- // (https://ai-sdk.dev/docs/ai-sdk-core/telemetry)+ // ai.toolCall.{id,name,args,result} of a Vercel ai.toolCall span, renamed by the mapper:+ // https://ai-sdk.dev/docs/ai-sdk-core/telemetryname: "VercelToolCall_IDOnBothParts",attributes: map[string]any{GenAIToolName: "get_current_weather",diff --git a/tests/integration/tests/tracedetail/02_thread.py b/tests/integration/tests/tracedetail/02_thread.pyindex 6e3439182c..fd0d0d7b15 100644--- a/tests/integration/tests/tracedetail/02_thread.py+++ b/tests/integration/tests/tracedetail/02_thread.py@@ -24,14 +24,22 @@ def test_thread_returns_gen_ai_spans_in_order(root_id, first_llm_id, tool_id, agent_id, second_llm_id, third_llm_id = (TraceIdGenerator.span_id() for _ in range(6))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"}}], "finish_reason": "tool_call"}])+ first_output = json.dumps([{"role": "assistant", "parts": [{"type": "tool_call", "id": "call_1", "name": "get_weather", "arguments": {"city": "Bangalore"}}]}])+ first_instructions = json.dumps([{"type": "text", "content": "Answer with the tool."}])second_input = json.dumps([{"role": "tool", "content": "sunny", "tool_call_id": "call_1"}])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, attribute_write_mode="json_only"),Traces(- timestamp=now - timedelta(seconds=8), trace_id=trace_id, span_id=first_llm_id, parent_span_id=root_id, name="chat gpt-4o", resources=resources, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.input.messages": first_input, "gen_ai.output.messages": first_output}, attribute_write_mode="json_only"+ timestamp=now - timedelta(seconds=8),+ trace_id=trace_id,+ span_id=first_llm_id,+ parent_span_id=root_id,+ name="chat gpt-4o",+ resources=resources,+ attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.system_instructions": first_instructions, "gen_ai.input.messages": first_input, "gen_ai.output.messages": first_output, "gen_ai.response.finish_reasons": json.dumps(["tool_calls"])},+ attribute_write_mode="json_only",),Traces(timestamp=now - timedelta(seconds=6),@@ -73,7 +81,7 @@ 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["formattedInput"] == [{"role": "user", "parts": [{"type": "text", "content": "weather in Bangalore?"}]}]+ assert first["formattedInput"] == [{"role": "system", "parts": [{"type": "text", "content": "Answer with the tool."}]}, {"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]}]