-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathspan.go
More file actions
2167 lines (1945 loc) · 64.3 KB
/
Copy pathspan.go
File metadata and controls
2167 lines (1945 loc) · 64.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package request // import "go.opentelemetry.io/obi/pkg/appolly/app/request"
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
"time"
"unicode/utf8"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.38.0"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/obi/pkg/appolly/app"
"go.opentelemetry.io/obi/pkg/appolly/app/svc"
"go.opentelemetry.io/obi/pkg/ebpf/timing"
attr "go.opentelemetry.io/obi/pkg/export/attributes/names"
)
type EventType uint8
// The following consts need to coincide with some C identifiers:
// EVENT_HTTP_REQUEST, EVENT_GRPC_REQUEST, EVENT_HTTP_CLIENT, EVENT_GRPC_CLIENT, EVENT_SQL_CLIENT
const (
// EventTypeProcessAlive is an internal signal. It will be ignored by the metrics exporters.
EventTypeProcessAlive EventType = iota
EventTypeHTTP
EventTypeGRPC
EventTypeHTTPClient
EventTypeGRPCClient
EventTypeSQLClient
EventTypeRedisClient
EventTypeKafkaClient
EventTypeMQTTClient
EventTypeRedisServer
EventTypeKafkaServer
EventTypeMQTTServer
EventTypeMongoClient
EventTypeManualSpan
EventTypeGPUCudaKernelLaunch
EventTypeGPUCudaGraphLaunch
EventTypeGPUCudaMalloc
EventTypeGPUCudaMemcpy
EventTypeFailedConnect
EventTypeDNS
EventTypeCouchbaseClient
EventTypeMemcachedClient
EventTypeMemcachedServer
EventTypeSQLServer
EventTypeNATSClient
EventTypeNATSServer
EventTypeAMQPClient
)
const (
envOTLPProtocol = "OTEL_EXPORTER_OTLP_PROTOCOL"
envOTLPTracesProtocol = "OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"
envOTLPMetricsProtocol = "OTEL_EXPORTER_OTLP_METRICS_PROTOCOL"
envOTLPEndpoint = "OTEL_EXPORTER_OTLP_ENDPOINT"
envOTLPTracesEndpoint = "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"
envOTLPMetricsEndpoint = "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
otlpGrpcProtocol = "grpc"
)
const (
metricsDetectPattern = "/v1/metrics"
grpcMetricsDetectPattern = "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export"
tracesDetectPattern = "/v1/traces"
grpcTracesDetectPattern = "/opentelemetry.proto.collector.trace.v1.TraceService/Export"
)
const (
SchemeHostSeparator = ";"
)
type SQLKind uint8
const (
DBGeneric SQLKind = iota + 1
DBPostgres
DBMySQL
DBMSSQL
)
const (
HTTPSubtypeNone = 0 // http
HTTPSubtypeGraphQL = 1 // http + graphql
HTTPSubtypeElasticsearch = 2 // http + elasticsearch
HTTPSubtypeAWSS3 = 3 // http + aws s3
HTTPSubtypeAWSSQS = 4 // http + aws sqs
HTTPSubtypeSQLPP = 5 // http + sql++ (couchbase, etc.)
HTTPSubtypeOpenAI = 6 // http + OpenAI
HTTPSubtypeAnthropic = 7 // http + Anthropic
HTTPSubtypeGemini = 8 // http + Google AI Studio (Gemini)
HTTPSubtypeJSONRPC = 9 // http + JSON-RPC
HTTPSubtypeAWSBedrock = 10 // http + AWS Bedrock
HTTPSubtypeQwen = 11 // http + Qwen (DashScope)
HTTPSubtypeMCP = 12 // http + Model Context Protocol
HTTPSubtypeEmbedding = 13 // http + generic embedding provider (Voyage, Cohere, Jina)
HTTPSubtypeRerank = 14 // http + Rerank (Cohere, Jina, Voyage, etc.)
HTTPSubtypeRetrieval = 15 // http + vector retrieval (Pinecone, Qdrant, Milvus, Chroma, Weaviate, etc.)
)
func IsGenAISubtype(subtype int) bool {
return subtype == HTTPSubtypeOpenAI ||
subtype == HTTPSubtypeAnthropic ||
subtype == HTTPSubtypeGemini ||
subtype == HTTPSubtypeQwen ||
subtype == HTTPSubtypeAWSBedrock ||
subtype == HTTPSubtypeMCP ||
subtype == HTTPSubtypeEmbedding ||
subtype == HTTPSubtypeRerank ||
subtype == HTTPSubtypeRetrieval
}
//nolint:cyclop
func (t EventType) String() string {
switch t {
case EventTypeProcessAlive:
return "ProcessAlive"
case EventTypeHTTP:
return "HTTP"
case EventTypeGRPC:
return "GRPC"
case EventTypeHTTPClient:
return "HTTPClient"
case EventTypeGRPCClient:
return "GRPCClient"
case EventTypeSQLClient:
return "SQLClient"
case EventTypeSQLServer:
return "SQLServer"
case EventTypeRedisClient:
return "RedisClient"
case EventTypeKafkaClient:
return "KafkaClient"
case EventTypeMQTTClient:
return "MQTTClient"
case EventTypeNATSClient:
return "NATSClient"
case EventTypeAMQPClient:
return "AMQPClient"
case EventTypeRedisServer:
return "RedisServer"
case EventTypeKafkaServer:
return "KafkaServer"
case EventTypeMQTTServer:
return "MQTTServer"
case EventTypeNATSServer:
return "NATSServer"
case EventTypeGPUCudaKernelLaunch:
return "CUDALaunchKernel"
case EventTypeGPUCudaGraphLaunch:
return "CUDALaunchGraph"
case EventTypeGPUCudaMalloc:
return "CUDAMalloc"
case EventTypeGPUCudaMemcpy:
return "CUDAMemcpy"
case EventTypeMongoClient:
return "MongoClient"
case EventTypeManualSpan:
return "CUSTOM"
case EventTypeFailedConnect:
return "CONNECTION ERR"
case EventTypeDNS:
return "DNS"
case EventTypeCouchbaseClient:
return "CouchbaseClient"
case EventTypeMemcachedClient:
return "MemcachedClient"
case EventTypeMemcachedServer:
return "MemcachedServer"
default:
return fmt.Sprintf("UNKNOWN (%d)", t)
}
}
func (t EventType) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
const (
MessagingPublish = "publish"
MessagingProcess = "process"
)
type converter struct {
clock func() time.Time
monoClock func() time.Duration
}
var clocks = converter{monoClock: timing.MonoTimeNow, clock: time.Now}
// PidInfo stores different views of the PID of the process that generated the span
type PidInfo struct {
// HostPID is the PID as seen by the host (root cgroup)
HostPID app.PID
// UserID is the PID as seen by the user space.
// Might differ from HostPID if the process is in a different namespace/cgroup/container/etc.
UserPID app.PID
// Namespace for the PIDs
Namespace uint32
}
type DBError struct {
ErrorCode string
Description string
}
type SQLError struct {
Code uint16 `json:"code"`
SQLState string `json:"sqlState"`
Message string `json:"message"`
}
type MessagingInfo struct {
Offset int64 `json:"offset"`
Partition int `json:"partition"`
}
type GraphQL struct {
Document string `json:"document"`
OperationName string `json:"operationName"`
OperationType string `json:"operationType"`
}
type Elasticsearch struct {
DBCollectionName string `json:"dbCollectionName"`
NodeName string `json:"nodeName"`
DBOperationName string `json:"dbOperationName"`
DBQueryText string `json:"dbQueryText"`
DBSystemName string `json:"dbSystemName"`
}
type AWS struct {
// https://opentelemetry.io/docs/specs/semconv/object-stores/s3/
S3 AWSS3 `json:"s3"`
// https://opentelemetry.io/docs/specs/semconv/messaging/sqs/
SQS AWSSQS `json:"sqs"`
}
type AWSMeta struct {
RequestID string `json:"requestId"`
ExtendedRequestID string `json:"extendedRequestId"`
Region string `json:"region"`
}
type AWSS3 struct {
Meta AWSMeta `json:"meta"`
Method string `json:"method"`
Bucket string `json:"bucket"`
Key string `json:"key"`
}
type AWSSQS struct {
Meta AWSMeta `json:"meta"`
OperationName string `json:"operationName"`
OperationType string `json:"operationType"`
Destination string `json:"destination"`
QueueURL string `json:"queueUrl"`
MessageID string `json:"messageId"`
}
type GenAI struct {
OpenAI *VendorOpenAI
Anthropic *VendorAnthropic
Gemini *VendorGemini
// Qwen reuses VendorOpenAI because DashScope's compatible-mode API
// returns the same JSON structure as OpenAI. The native generation
// API uses slightly different field names (request_id, output,
// input_tokens/output_tokens) but VendorOpenAI already accommodates
// both via GetInputTokens()/GetOutputTokens() and the Output field.
// A separate field (rather than sharing OpenAI) keeps provider
// routing explicit and allows future divergence without refactoring.
Qwen *VendorOpenAI
Bedrock *VendorBedrock
MCP *MCPCall
Embedding *VendorEmbedding
Rerank *VendorRerank
Retrieval *VendorRetrieval
}
type OpenAIPromptTokensDetails struct {
CachedTokens int `json:"cached_tokens,omitempty"`
CacheCreationTokens int `json:"cache_creation_tokens,omitempty"`
}
type OpenAIUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
TotalTokens int `json:"total_tokens"`
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
CompletionDetails *OpenAICompletionDetails `json:"completion_tokens_details,omitempty"`
PromptTokensDetails *OpenAIPromptTokensDetails `json:"prompt_tokens_details,omitempty"`
}
type OpenAICompletionDetails struct {
ReasoningTokens int `json:"reasoning_tokens,omitempty"`
}
func (u *OpenAIUsage) GetInputTokens() int {
if u.InputTokens > 0 {
return u.InputTokens
}
return u.PromptTokens
}
func (u *OpenAIUsage) GetOutputTokens() int {
if u.OutputTokens > 0 {
return u.OutputTokens
}
if u.CompletionTokens > 0 {
return u.CompletionTokens
}
// Embedding responses only report prompt_tokens and total_tokens.
// Derive output tokens from the difference.
if u.TotalTokens > 0 && u.PromptTokens > 0 {
return u.TotalTokens - u.PromptTokens
}
return 0
}
type OpenAIError struct {
Message string `json:"message"`
Type string `json:"type"`
}
// ToolCall represents a tool invocation requested by an LLM.
type ToolCall struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
}
type VendorOpenAI struct {
OperationName string `json:"object"`
ResponseModel string `json:"model"`
Error OpenAIError `json:"error"`
ID string `json:"id"`
FrequencyPenalty float64 `json:"frequency_penalty"`
Temperature float64 `json:"temperature"`
TopP float64 `json:"top_p"`
Usage OpenAIUsage `json:"usage"`
Output json.RawMessage `json:"output"`
Request OpenAIInput
Choices json.RawMessage `json:"choices"`
Items json.RawMessage `json:"items"`
Metadata json.RawMessage `json:"metadata"`
Data json.RawMessage `json:"data"`
ServiceTier string `json:"service_tier,omitempty"`
SystemFingerprint string `json:"system_fingerprint,omitempty"`
APIType string `json:"-"`
ToolCalls []ToolCall `json:"-"`
}
func (ai *VendorOpenAI) GetFinishReasons() []string {
if len(ai.Choices) == 0 {
return nil
}
var choices []struct {
FinishReason string `json:"finish_reason"`
}
if err := json.Unmarshal(ai.Choices, &choices); err != nil {
return nil
}
var reasons []string
for _, c := range choices {
if c.FinishReason != "" {
reasons = append(reasons, c.FinishReason)
}
}
return reasons
}
func (ai *VendorOpenAI) GetOutput() string {
return normalizeOpenAIOutput(ai)
}
type OpenAIInput struct {
Input string `json:"input"`
Prompt string `json:"prompt"`
Model string `json:"model"`
Instructions string `json:"instructions"`
Messages json.RawMessage `json:"messages"`
Items json.RawMessage `json:"items"`
Temperature float64 `json:"temperature"`
Dimensions int `json:"dimensions,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
N int `json:"n,omitempty"`
Stop json.RawMessage `json:"stop,omitempty"`
PresencePenalty float64 `json:"presence_penalty,omitempty"`
Stream bool `json:"stream,omitempty"`
EncodingFormat string `json:"encoding_format,omitempty"`
Seed *int `json:"seed,omitempty"`
Tools json.RawMessage `json:"tools,omitempty"`
ServiceTier string `json:"service_tier,omitempty"`
}
func (air *OpenAIInput) GetStopSequences() []string {
if len(air.Stop) == 0 {
return nil
}
var arr []string
if err := json.Unmarshal(air.Stop, &arr); err == nil {
return arr
}
var s string
if err := json.Unmarshal(air.Stop, &s); err == nil {
return []string{s}
}
return nil
}
func (air *OpenAIInput) GetInput() string {
if len(air.Input) > 0 {
return wrapTextAsInputMessage(air.Input)
}
if len(air.Prompt) > 0 {
return wrapTextAsInputMessage(air.Prompt)
}
if len(air.Items) > 0 {
return string(air.Items)
}
return normalizeOpenAIMessages(air.Messages)
}
type VendorAnthropic struct {
Input AnthropicRequest
Output AnthropicResponse
ToolCalls []ToolCall `json:"-"`
}
type AnthropicRequest struct {
MaxTokens int `json:"max_tokens"`
Messages json.RawMessage `json:"messages"`
Model string `json:"model"`
Stream bool `json:"stream"`
System string `json:"system"`
Tools json.RawMessage `json:"tools"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
TopK int `json:"top_k,omitempty"`
StopSequences []string `json:"stop_sequences,omitempty"`
}
type AnthropicResponse struct {
Model string `json:"model"`
ID string `json:"id"`
Type string `json:"type"`
Role string `json:"role"`
Content json.RawMessage `json:"content"`
StopReason string `json:"stop_reason"`
StopSequence *string `json:"stop_sequence"`
Usage AnthropicUsage `json:"usage"`
Error *AnthropicError `json:"error,omitempty"`
RequestID string `json:"request_id"`
}
type AnthropicUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`
ReasoningOutputTokens int `json:"reasoning_output_tokens,omitempty"`
ServiceTier string `json:"service_tier"`
InferenceGeo string `json:"inference_geo"`
}
type AnthropicError struct {
Type string `json:"type"`
Message string `json:"message"`
}
// Google AI Studio (Gemini) types
// DefaultGeminiOperation is the fallback operation name when no operation
// can be extracted from the URL path.
const DefaultGeminiOperation = "generate_content"
type VendorGemini struct {
Input GeminiRequest
Output GeminiResponse
Model string
Operation string
IsStream bool
ToolCalls []ToolCall `json:"-"`
}
type GeminiRequest struct {
Contents json.RawMessage `json:"contents"`
SystemInstruction *GeminiContent `json:"systemInstruction,omitempty"`
Tools json.RawMessage `json:"tools,omitempty"`
GenerationConfig *GeminiGenCfg `json:"generationConfig,omitempty"`
}
type GeminiContent struct {
Parts json.RawMessage `json:"parts"`
Role string `json:"role"`
}
type GeminiGenCfg struct {
Temperature float64 `json:"temperature"`
TopP float64 `json:"topP"`
TopK int `json:"topK"`
MaxOutputTokens int `json:"maxOutputTokens"`
FrequencyPenalty float64 `json:"frequencyPenalty"`
PresencePenalty float64 `json:"presencePenalty"`
StopSequences []string `json:"stopSequences,omitempty"`
Seed *int `json:"seed,omitempty"`
CandidateCount int `json:"candidateCount"`
ResponseMimeType string `json:"responseMimeType,omitempty"`
}
type GeminiResponse struct {
Candidates []GeminiCandidate `json:"candidates"`
UsageMetadata GeminiUsage `json:"usageMetadata"`
ModelVersion string `json:"modelVersion"`
ResponseID string `json:"responseId"`
Error *GeminiError `json:"error,omitempty"`
}
type GeminiCandidate struct {
Content *GeminiContent `json:"content"`
FinishReason string `json:"finishReason"`
SafetyRatings json.RawMessage `json:"safetyRatings,omitempty"`
}
type GeminiUsage struct {
PromptTokenCount int `json:"promptTokenCount"`
CandidatesTokenCount int `json:"candidatesTokenCount"`
TotalTokenCount int `json:"totalTokenCount"`
}
type GeminiError struct {
Code int `json:"code"`
Message string `json:"message"`
Status string `json:"status"`
}
func (g *VendorGemini) GetFinishReasons() []string {
var reasons []string
for _, c := range g.Output.Candidates {
if c.FinishReason != "" {
reasons = append(reasons, c.FinishReason)
}
}
return reasons
}
// OperationName returns the Gemini API operation name.
// It falls back to DefaultGeminiOperation when no operation was extracted from the URL.
func (g *VendorGemini) OperationName() string {
if g.Operation != "" {
return g.Operation
}
return DefaultGeminiOperation
}
func (g *VendorGemini) GetOutput() string {
return normalizeGeminiOutput(&g.Output)
}
func (g *VendorGemini) GetInput() string {
return normalizeGeminiInput(g.Input.Contents)
}
func (g *VendorGemini) GetSystemInstruction() string {
if g.Input.SystemInstruction != nil {
return normalizeGeminiParts(g.Input.SystemInstruction.Parts)
}
return ""
}
// AWS Bedrock types
// Bedrock is a multi-model gateway; request/response shape varies by model family.
// We capture the unified superset using omitempty and RawMessage for variable fields.
type VendorBedrock struct {
Input BedrockRequest
Output BedrockResponse
Model string // extracted from URL path: /model/{modelId}/invoke
IsStream bool
GuardrailID string
}
// BedrockRequest covers the common fields across all model families.
// The messages/prompt/inputText fields differ per model family,
// so we capture them as raw JSON where needed.
type BedrockRequest struct {
// Anthropic Claude / Amazon Nova format
Messages json.RawMessage `json:"messages,omitempty"`
System string `json:"system,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
Temperature float64 `json:"temperature,omitempty"`
TopP float64 `json:"top_p,omitempty"`
TopK int `json:"top_k,omitempty"`
// Amazon Titan format
InputText string `json:"inputText,omitempty"`
TextGenerationConfig *TitanGenConfig `json:"textGenerationConfig,omitempty"`
// Meta Llama format
Prompt string `json:"prompt,omitempty"`
MaxGenLen int `json:"max_gen_len,omitempty"`
// Tool use (Claude / Nova)
Tools json.RawMessage `json:"tools,omitempty"`
StopSequences []string `json:"stop_sequences,omitempty"`
}
type TitanGenConfig struct {
MaxTokenCount int `json:"maxTokenCount,omitempty"`
Temperature float64 `json:"temperature,omitempty"`
TopP float64 `json:"topP,omitempty"`
}
// BedrockResponse covers the common response fields across all model families.
// Token counts are read from response headers (more reliable than body) and stored here.
type BedrockResponse struct {
// Anthropic Claude format
Content json.RawMessage `json:"content,omitempty"`
StopReason string `json:"stop_reason,omitempty"`
Usage *BedrockUsage `json:"usage,omitempty"`
// Amazon Nova format
Output *NovaOutput `json:"output,omitempty"`
StopReasonNova string `json:"stopReason,omitempty"`
// Meta Llama format
Generation string `json:"generation,omitempty"`
PromptTokenCount int `json:"prompt_token_count,omitempty"`
GenerationTokenCount int `json:"generation_token_count,omitempty"`
// Amazon Titan format
Results []TitanResult `json:"results,omitempty"`
// Error fields appear at the top level of the Bedrock error response body
ErrorType string `json:"__type,omitempty"`
ErrorMessage string `json:"message,omitempty"`
// Token counts extracted from response headers (not JSON-unmarshalled, set programmatically)
InputTokens int `json:"-"`
OutputTokens int `json:"-"`
}
type BedrockUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
}
type NovaOutput struct {
Message *NovaMessage `json:"message,omitempty"`
}
type NovaMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content,omitempty"`
}
type TitanResult struct {
OutputText string `json:"outputText"`
CompletionReason string `json:"completionReason,omitempty"`
}
func (b *VendorBedrock) GetInput() string {
if len(b.Input.Messages) > 0 {
return NormalizeAnthropicInput(b.Input.Messages)
}
if b.Input.Prompt != "" {
return wrapTextAsInputMessage(b.Input.Prompt)
}
if b.Input.InputText != "" {
return wrapTextAsInputMessage(b.Input.InputText)
}
return ""
}
func (b *VendorBedrock) GetOutput() string {
// Anthropic Claude: content array (normalized via NormalizeBedrockOutput in tracesgen)
if len(b.Output.Content) > 0 {
return string(b.Output.Content)
}
// Amazon Nova: output.message.content
if b.Output.Output != nil && b.Output.Output.Message != nil && len(b.Output.Output.Message.Content) > 0 {
return wrapTextAsOutputMessage(
b.Output.Output.Message.Role,
string(b.Output.Output.Message.Content),
b.Output.StopReasonNova,
)
}
// Meta Llama: generation
if b.Output.Generation != "" {
return wrapTextAsOutputMessage("assistant", b.Output.Generation, b.GetStopReason())
}
// Amazon Titan: results[0].outputText
if len(b.Output.Results) > 0 {
return wrapTextAsOutputMessage("assistant", b.Output.Results[0].OutputText, b.Output.Results[0].CompletionReason)
}
return ""
}
func (b *VendorBedrock) GetSystemInstruction() string {
return NormalizeSystemInstructions(b.Input.System)
}
func (b *VendorBedrock) GetStopReason() string {
if b.Output.StopReason != "" {
return b.Output.StopReason
}
if b.Output.StopReasonNova != "" {
return b.Output.StopReasonNova
}
return ""
}
// MCPCall holds parsed data from a Model Context Protocol request/response.
type MCPCall struct {
Method string `json:"method"`
ToolName string `json:"toolName,omitempty"`
ResourceURI string `json:"resourceUri,omitempty"`
PromptName string `json:"promptName,omitempty"`
SessionID string `json:"sessionId,omitempty"`
ProtocolVer string `json:"protocolVer,omitempty"`
RequestID string `json:"requestId,omitempty"`
ErrorCode int `json:"errorCode,omitempty"`
ErrorMessage string `json:"errorMessage,omitempty"`
}
// OperationName returns the GenAI operation name for the MCP method.
// tools/call maps to execute_tool; other methods return the method name as-is.
func (m *MCPCall) OperationName() string {
if m.Method == "tools/call" {
return "execute_tool"
}
return m.Method
}
type JSONRPC struct {
Method string `json:"method"`
Version string `json:"version"`
RequestID string `json:"requestId"`
ErrorCode int `json:"errorCode,omitempty"`
ErrorMessage string `json:"errorMessage,omitempty"`
}
// Generic embedding provider types (Voyage AI, Cohere, Jina AI)
// GenAI operation name constants aligned with OTel semantic conventions.
const (
ChatOperationName = "chat"
CompletionOperationName = "text_completion"
GenerationOperationName = "generation"
InvokeModelOperationName = "invoke_model"
EmbeddingOperationName = "embeddings"
)
// VendorEmbedding represents a generic embedding API provider such as
// Voyage AI, Cohere, or Jina AI.
type VendorEmbedding struct {
Provider string
Model string
Input EmbeddingRequest
Output EmbeddingResponse
}
// OperationName returns the canonical embedding operation name.
func (e *VendorEmbedding) OperationName() string {
return EmbeddingOperationName
}
// EmbeddingRequest captures the common fields from embedding API requests.
type EmbeddingRequest struct {
Model string `json:"model"`
Input json.RawMessage `json:"input"`
Dimensions int `json:"dimensions,omitempty"`
// Cohere uses "texts" instead of "input"
Texts json.RawMessage `json:"texts,omitempty"`
}
// InputCount returns the number of input texts in the request.
// It handles both single-string and array-of-strings formats.
func (r *EmbeddingRequest) InputCount() int {
raw := r.Input
if len(raw) == 0 {
raw = r.Texts
}
if len(raw) == 0 {
return 0
}
// Array of strings: count elements
var arr []json.RawMessage
if json.Unmarshal(raw, &arr) == nil {
return len(arr)
}
// Single string
return 1
}
// EmbeddingResponse captures the common fields from embedding API responses.
type EmbeddingResponse struct {
Model string `json:"model"`
Usage EmbeddingUsage `json:"usage"`
// Cohere uses meta.billed_units for token counts
Meta *CohereResponseMeta `json:"meta,omitempty"`
}
// EmbeddingUsage captures token usage in embedding responses.
type EmbeddingUsage struct {
PromptTokens int `json:"prompt_tokens"`
TotalTokens int `json:"total_tokens"`
}
// CohereResponseMeta captures Cohere-specific response metadata.
type CohereResponseMeta struct {
BilledUnits *CohereBilledUnits `json:"billed_units,omitempty"`
}
// CohereBilledUnits captures Cohere token billing information.
type CohereBilledUnits struct {
InputTokens int `json:"input_tokens"`
}
// GetInputTokens returns the input token count, handling provider-specific formats.
func (e *VendorEmbedding) GetInputTokens() int {
if e.Output.Usage.PromptTokens > 0 {
return e.Output.Usage.PromptTokens
}
if e.Output.Usage.TotalTokens > 0 {
return e.Output.Usage.TotalTokens
}
if e.Output.Meta != nil && e.Output.Meta.BilledUnits != nil {
return e.Output.Meta.BilledUnits.InputTokens
}
return 0
}
// GetOutputTokens returns the output token count for embedding requests,
// derived as total_tokens - prompt_tokens.
func (e *VendorEmbedding) GetOutputTokens() int {
if e.Output.Usage.TotalTokens > 0 && e.Output.Usage.PromptTokens > 0 {
return e.Output.Usage.TotalTokens - e.Output.Usage.PromptTokens
}
return 0
}
// VendorRerank holds parsed data from a rerank API request/response.
// Reranking services (Cohere, Jina AI, Voyage AI, etc.) share a similar
// REST API shape: POST /v1/rerank with a JSON body containing model,
// query, and documents. The provider is identified from the request
// hostname.
type VendorRerank struct {
Input RerankRequest
Output RerankResponse
Provider string
}
type RerankRequest struct {
Model string `json:"model"`
Query string `json:"query"`
TopN int `json:"top_n"`
Documents json.RawMessage `json:"documents"`
}
type RerankResponse struct {
ID string `json:"id"`
Model string `json:"model"`
Results json.RawMessage `json:"results"`
Usage RerankUsage `json:"usage"`
Meta *RerankMeta `json:"meta,omitempty"`
Error *RerankError `json:"error,omitempty"`
}
// RerankMeta represents Cohere-style metadata in the rerank response.
type RerankMeta struct {
BilledUnits *RerankBilledUnits `json:"billed_units,omitempty"`
Tokens *RerankMetaTokens `json:"tokens,omitempty"`
}
type RerankBilledUnits struct {
SearchUnits float64 `json:"search_units"`
}
type RerankMetaTokens struct {
InputTokens int `json:"input_tokens"`
}
type RerankUsage struct {
TotalTokens int `json:"total_tokens"`
PromptTokens int `json:"prompt_tokens"`
SearchUnits int `json:"search_units"`
}
func (u *RerankUsage) GetInputTokens() int {
if u.PromptTokens > 0 {
return u.PromptTokens
}
return u.TotalTokens
}
// GetTotalTokens returns the total token count from any supported response
// format. It checks usage.total_tokens (Jina/Voyage), then
// usage.prompt_tokens, and finally falls back to meta.tokens.input_tokens
// (Cohere).
func (r *RerankResponse) GetTotalTokens() int {
if r.Usage.TotalTokens > 0 {
return r.Usage.TotalTokens
}
if r.Usage.PromptTokens > 0 {
return r.Usage.PromptTokens
}
if r.Meta != nil && r.Meta.Tokens != nil && r.Meta.Tokens.InputTokens > 0 {
return r.Meta.Tokens.InputTokens
}
return 0
}
type RerankError struct {
Type string `json:"type"`
Message string `json:"message"`
}
// Vector retrieval provider types (Pinecone, Qdrant, Milvus, Chroma, Weaviate, etc.)
// RetrievalOperationName is the canonical operation name for vector
// retrieval spans, aligned with the OpenTelemetry GenAI semantic
// conventions (gen_ai.operation.name = "retrieval").
const RetrievalOperationName = "retrieval"
// VendorRetrieval holds parsed data from a vector database retrieval
// (similarity search) request/response. Vector stores differ significantly
// in their request/response shape, so both Input and Output keep only the
// fields that are common or easy to recover across providers.
type VendorRetrieval struct {
Provider string
Input RetrievalRequest
Output RetrievalResponse
}
// OperationName returns the canonical retrieval operation name.
func (r *VendorRetrieval) OperationName() string {
return RetrievalOperationName
}
// GetCollection returns the collection / index / namespace name, checking
// the provider-specific aliases in order.
func (r *VendorRetrieval) GetCollection() string {
if r.Input.Collection != "" {
return r.Input.Collection
}
if r.Input.CollectionName != "" {
return r.Input.CollectionName
}
if r.Input.CollectionSnake != "" {
return r.Input.CollectionSnake
}
return r.Input.Namespace
}
// RetrievalRequest captures the common fields from vector search request
// bodies across Pinecone, Qdrant, Milvus, Chroma and Weaviate. Unknown
// fields are ignored; missing fields are harmless.
type RetrievalRequest struct {
// Model is the embedding model used, when reported by the request body
// (rarely present; most vector stores do not require a model).
Model string `json:"model,omitempty"`
// Collection / index name when the provider places it in the body
// (Pinecone uses namespace, Milvus uses collectionName, Chroma uses collection).
Collection string `json:"collection,omitempty"`
CollectionName string `json:"collectionName,omitempty"`
CollectionSnake string `json:"collection_name,omitempty"`
Namespace string `json:"namespace,omitempty"`
}
// RetrievalResponse captures the common fields from vector search response
// bodies.
type RetrievalResponse struct {
ID string `json:"id,omitempty"`
Model string `json:"model,omitempty"`
Usage RetrievalUsage `json:"usage,omitempty"`
}
// RetrievalUsage captures optional token usage information returned by
// embedding-aware vector stores.
type RetrievalUsage struct {
TotalTokens int `json:"total_tokens,omitempty"`
PromptTokens int `json:"prompt_tokens,omitempty"`
}
// GetInputTokens returns the input token count, preferring prompt_tokens
// and falling back to total_tokens. Returns zero when not reported.
func (r *VendorRetrieval) GetInputTokens() int {
if r.Output.Usage.PromptTokens > 0 {
return r.Output.Usage.PromptTokens
}
return r.Output.Usage.TotalTokens