# Spans

## Create a span

`client.Spans.New(ctx, body) (*Span, error)`

**post** `/v5/spans`

Create a single span and return the persisted span.

Use this for one-off span ingestion; to write many spans in one request use
POST /v5/spans/batch. When `id` is omitted the server generates a UUID.
Depending on per-account server configuration the span is persisted to the
legacy trace store, to the tracing service, or both. `end_timestamp`
must not precede `start_timestamp`, which is rejected with a 422. When the
tracing service is the primary store, its 400, 413 and 422 rejections keep that
status and detail, as does a 403 when the request carried its own API key, and
every other failure returns a 503 with a Retry-After header. A span whose parent
belongs to another trace is rejected with 409 before either store is written. The
parent is looked up in Postgres, so that check ends once the account's spans stop
being written there. Which writes the tracing service rejects depends in part on
its storage engine: on Postgres deployments a NUL byte or invalid UTF-8 inside
`trace_id`, `id`, `parent_id` or `group_id` rejects the span with a 400
naming the field, because replacing the byte would change the identity the
response echoes; a NUL byte or invalid UTF-8 in any other field is replaced with
U+FFFD and the span is persisted. ClickHouse deployments store the bytes verbatim.

Credential redaction: values in the free-form `input`, `output`, `metadata`,
and `expected` objects, and in `name`, that are credential-shaped (bearer/JWT,
API keys, connection-string passwords) or under a credential-named key are replaced
with `[REDACTED:credential]` before the span is persisted, so the stored and
returned span reflects the redacted value (EY 12.3).

### Parameters

- `body SpanNewParams`

  - `SpanCreate param.Field[SpanCreate]`

### Returns

- `type Span struct{…}`

  - `ID string`

  - `AccountID string`

  - `Name string`

  - `StartTimestamp Time`

  - `TraceID string`

    id for grouping traces together, uuid is recommended

  - `ApplicationInteractionID string`

    The interaction ID this span belongs to

  - `ApplicationVariantID string`

    The id of the application variant this span belongs to

  - `CreatedBy Identity`

    The identity that created the entity.

    - `ID string`

    - `Type IdentityType`

      - `const IdentityTypeUser IdentityType = "user"`

      - `const IdentityTypeServiceAccount IdentityType = "service_account"`

    - `Object IdentityObject`

      - `const IdentityObjectIdentity IdentityObject = "identity"`

  - `EndTimestamp Time`

  - `Expected map[string, any]`

  - `GroupID string`

    Reference to a group_id

  - `Input map[string, any]`

  - `InputTokens int64`

    Prompt tokens the producer reported for this span, absent when it reported none. Same quantity the input_tokens sort orders by.

  - `Metadata map[string, any]`

  - `Object SpanObject`

    - `const SpanObjectSpan SpanObject = "span"`

  - `ObsSpanID string`

    W3C span id of the observability span this span executed in.

  - `ObsTraceID string`

    W3C trace id of the observability trace this span executed in. Null for spans written without the edge, and for accounts still served by the legacy trace store.

  - `Output map[string, any]`

  - `OutputTokens int64`

    Completion tokens the producer reported for this span, absent when it reported none. Same quantity the output_tokens sort orders by.

  - `ParentID string`

    Reference to a parent span_id

  - `Status SpanStatus`

    - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

    - `const SpanStatusError SpanStatus = "ERROR"`

    - `const SpanStatusCanceled SpanStatus = "CANCELED"`

  - `Type SpanType`

    - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

    - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

    - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

    - `const SpanTypeCompletion SpanType = "COMPLETION"`

    - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

    - `const SpanTypeKBInput SpanType = "KB_INPUT"`

    - `const SpanTypeReranking SpanType = "RERANKING"`

    - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

    - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

    - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

    - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

    - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

    - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

    - `const SpanTypeCustom SpanType = "CUSTOM"`

    - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

    - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

    - `const SpanTypeEvaluation SpanType = "EVALUATION"`

    - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

    - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

    - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

    - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

    - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

    - `const SpanTypeTracer SpanType = "TRACER"`

    - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

    - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

    - `const SpanTypeStandalone SpanType = "STANDALONE"`

### Example

```go
package main

import (
  "context"
  "fmt"
  "time"

  "github.com/scaleapi/sgp-dev-go"
  "github.com/scaleapi/sgp-dev-go/option"
)

func main() {
  client := sgpdev.NewClient(
    option.WithAPIKey("My API Key"),
    option.WithAccountID("My Account ID"),
  )
  span, err := client.Spans.New(context.TODO(), sgpdev.SpanNewParams{
    SpanCreate: sgpdev.SpanCreateParam{
      Name: "name",
      StartTimestamp: time.Now(),
      TraceID: "trace_id",
    },
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", span.ID)
}
```

#### Response

```json
{
  "id": "id",
  "account_id": "account_id",
  "name": "name",
  "start_timestamp": "2019-12-27T18:11:19.117Z",
  "trace_id": "trace_id",
  "application_interaction_id": "application_interaction_id",
  "application_variant_id": "application_variant_id",
  "created_by": {
    "id": "id",
    "type": "user",
    "object": "identity"
  },
  "end_timestamp": "2019-12-27T18:11:19.117Z",
  "expected": {
    "foo": "bar"
  },
  "group_id": "group_id",
  "input": {
    "foo": "bar"
  },
  "input_tokens": 0,
  "metadata": {
    "foo": "bar"
  },
  "object": "span",
  "obs_span_id": "obs_span_id",
  "obs_trace_id": "obs_trace_id",
  "output": {
    "foo": "bar"
  },
  "output_tokens": 0,
  "parent_id": "parent_id",
  "status": "SUCCESS",
  "type": "TEXT_INPUT"
}
```

## Get a span

`client.Spans.Get(ctx, spanID) (*Span, error)`

**get** `/v5/spans/{span_id}`

Retrieve a single span by its id.

The span is read from the legacy trace store or, for accounts migrated to the
tracing service, from that service — with automatic fallback to the legacy
trace store on error unless the account is in strict mode, where a
tracing-service failure surfaces as a 503. Access is authorized against the
span's parent trace, so a span in a trace the caller cannot read is rejected;
an unknown id returns 404. `input_tokens` and `output_tokens` carry the token usage the
span's producer reported at ingest, and are absent both for a span that reported none and for
every span served from the legacy trace store, which keeps no token counts.

### Parameters

- `spanID string`

### Returns

- `type Span struct{…}`

  - `ID string`

  - `AccountID string`

  - `Name string`

  - `StartTimestamp Time`

  - `TraceID string`

    id for grouping traces together, uuid is recommended

  - `ApplicationInteractionID string`

    The interaction ID this span belongs to

  - `ApplicationVariantID string`

    The id of the application variant this span belongs to

  - `CreatedBy Identity`

    The identity that created the entity.

    - `ID string`

    - `Type IdentityType`

      - `const IdentityTypeUser IdentityType = "user"`

      - `const IdentityTypeServiceAccount IdentityType = "service_account"`

    - `Object IdentityObject`

      - `const IdentityObjectIdentity IdentityObject = "identity"`

  - `EndTimestamp Time`

  - `Expected map[string, any]`

  - `GroupID string`

    Reference to a group_id

  - `Input map[string, any]`

  - `InputTokens int64`

    Prompt tokens the producer reported for this span, absent when it reported none. Same quantity the input_tokens sort orders by.

  - `Metadata map[string, any]`

  - `Object SpanObject`

    - `const SpanObjectSpan SpanObject = "span"`

  - `ObsSpanID string`

    W3C span id of the observability span this span executed in.

  - `ObsTraceID string`

    W3C trace id of the observability trace this span executed in. Null for spans written without the edge, and for accounts still served by the legacy trace store.

  - `Output map[string, any]`

  - `OutputTokens int64`

    Completion tokens the producer reported for this span, absent when it reported none. Same quantity the output_tokens sort orders by.

  - `ParentID string`

    Reference to a parent span_id

  - `Status SpanStatus`

    - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

    - `const SpanStatusError SpanStatus = "ERROR"`

    - `const SpanStatusCanceled SpanStatus = "CANCELED"`

  - `Type SpanType`

    - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

    - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

    - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

    - `const SpanTypeCompletion SpanType = "COMPLETION"`

    - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

    - `const SpanTypeKBInput SpanType = "KB_INPUT"`

    - `const SpanTypeReranking SpanType = "RERANKING"`

    - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

    - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

    - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

    - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

    - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

    - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

    - `const SpanTypeCustom SpanType = "CUSTOM"`

    - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

    - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

    - `const SpanTypeEvaluation SpanType = "EVALUATION"`

    - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

    - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

    - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

    - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

    - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

    - `const SpanTypeTracer SpanType = "TRACER"`

    - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

    - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

    - `const SpanTypeStandalone SpanType = "STANDALONE"`

### Example

```go
package main

import (
  "context"
  "fmt"

  "github.com/scaleapi/sgp-dev-go"
  "github.com/scaleapi/sgp-dev-go/option"
)

func main() {
  client := sgpdev.NewClient(
    option.WithAPIKey("My API Key"),
    option.WithAccountID("My Account ID"),
  )
  span, err := client.Spans.Get(context.TODO(), "span_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", span.ID)
}
```

#### Response

```json
{
  "id": "id",
  "account_id": "account_id",
  "name": "name",
  "start_timestamp": "2019-12-27T18:11:19.117Z",
  "trace_id": "trace_id",
  "application_interaction_id": "application_interaction_id",
  "application_variant_id": "application_variant_id",
  "created_by": {
    "id": "id",
    "type": "user",
    "object": "identity"
  },
  "end_timestamp": "2019-12-27T18:11:19.117Z",
  "expected": {
    "foo": "bar"
  },
  "group_id": "group_id",
  "input": {
    "foo": "bar"
  },
  "input_tokens": 0,
  "metadata": {
    "foo": "bar"
  },
  "object": "span",
  "obs_span_id": "obs_span_id",
  "obs_trace_id": "obs_trace_id",
  "output": {
    "foo": "bar"
  },
  "output_tokens": 0,
  "parent_id": "parent_id",
  "status": "SUCCESS",
  "type": "TEXT_INPUT"
}
```

## Update a span

`client.Spans.Update(ctx, spanID, body) (*Span, error)`

**patch** `/v5/spans/{span_id}`

Partially update a span's mutable fields and return the updated span.

Only the provided fields among name, end timestamp, output, metadata, and
status are changed. This endpoint is available only for accounts still served
solely by the legacy trace store: once an account begins dual-writing to the
tracing service — which is upsert-only and has no partial-update operation —
PATCH returns 501 and PUT /v5/spans/batch must be used instead. Updates are
authorized against the span's parent trace, and an unknown id returns 404.

Credential redaction: values in the free-form `input`, `output`, `metadata`,
and `expected` objects, and in `name`, that are credential-shaped (bearer/JWT,
API keys, connection-string passwords) or under a credential-named key are replaced
with `[REDACTED:credential]` before the span is persisted, so the stored and
returned span reflects the redacted value (EY 12.3).

### Parameters

- `spanID string`

- `body SpanUpdateParams`

  - `EndTimestamp param.Field[Time]`

  - `Metadata param.Field[map[string, any]]`

  - `Name param.Field[string]`

  - `Output param.Field[map[string, any]]`

  - `Status param.Field[SpanStatus]`

### Returns

- `type Span struct{…}`

  - `ID string`

  - `AccountID string`

  - `Name string`

  - `StartTimestamp Time`

  - `TraceID string`

    id for grouping traces together, uuid is recommended

  - `ApplicationInteractionID string`

    The interaction ID this span belongs to

  - `ApplicationVariantID string`

    The id of the application variant this span belongs to

  - `CreatedBy Identity`

    The identity that created the entity.

    - `ID string`

    - `Type IdentityType`

      - `const IdentityTypeUser IdentityType = "user"`

      - `const IdentityTypeServiceAccount IdentityType = "service_account"`

    - `Object IdentityObject`

      - `const IdentityObjectIdentity IdentityObject = "identity"`

  - `EndTimestamp Time`

  - `Expected map[string, any]`

  - `GroupID string`

    Reference to a group_id

  - `Input map[string, any]`

  - `InputTokens int64`

    Prompt tokens the producer reported for this span, absent when it reported none. Same quantity the input_tokens sort orders by.

  - `Metadata map[string, any]`

  - `Object SpanObject`

    - `const SpanObjectSpan SpanObject = "span"`

  - `ObsSpanID string`

    W3C span id of the observability span this span executed in.

  - `ObsTraceID string`

    W3C trace id of the observability trace this span executed in. Null for spans written without the edge, and for accounts still served by the legacy trace store.

  - `Output map[string, any]`

  - `OutputTokens int64`

    Completion tokens the producer reported for this span, absent when it reported none. Same quantity the output_tokens sort orders by.

  - `ParentID string`

    Reference to a parent span_id

  - `Status SpanStatus`

    - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

    - `const SpanStatusError SpanStatus = "ERROR"`

    - `const SpanStatusCanceled SpanStatus = "CANCELED"`

  - `Type SpanType`

    - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

    - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

    - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

    - `const SpanTypeCompletion SpanType = "COMPLETION"`

    - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

    - `const SpanTypeKBInput SpanType = "KB_INPUT"`

    - `const SpanTypeReranking SpanType = "RERANKING"`

    - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

    - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

    - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

    - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

    - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

    - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

    - `const SpanTypeCustom SpanType = "CUSTOM"`

    - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

    - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

    - `const SpanTypeEvaluation SpanType = "EVALUATION"`

    - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

    - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

    - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

    - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

    - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

    - `const SpanTypeTracer SpanType = "TRACER"`

    - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

    - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

    - `const SpanTypeStandalone SpanType = "STANDALONE"`

### Example

```go
package main

import (
  "context"
  "fmt"

  "github.com/scaleapi/sgp-dev-go"
  "github.com/scaleapi/sgp-dev-go/option"
)

func main() {
  client := sgpdev.NewClient(
    option.WithAPIKey("My API Key"),
    option.WithAccountID("My Account ID"),
  )
  span, err := client.Spans.Update(
    context.TODO(),
    "span_id",
    sgpdev.SpanUpdateParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", span.ID)
}
```

#### Response

```json
{
  "id": "id",
  "account_id": "account_id",
  "name": "name",
  "start_timestamp": "2019-12-27T18:11:19.117Z",
  "trace_id": "trace_id",
  "application_interaction_id": "application_interaction_id",
  "application_variant_id": "application_variant_id",
  "created_by": {
    "id": "id",
    "type": "user",
    "object": "identity"
  },
  "end_timestamp": "2019-12-27T18:11:19.117Z",
  "expected": {
    "foo": "bar"
  },
  "group_id": "group_id",
  "input": {
    "foo": "bar"
  },
  "input_tokens": 0,
  "metadata": {
    "foo": "bar"
  },
  "object": "span",
  "obs_span_id": "obs_span_id",
  "obs_trace_id": "obs_trace_id",
  "output": {
    "foo": "bar"
  },
  "output_tokens": 0,
  "parent_id": "parent_id",
  "status": "SUCCESS",
  "type": "TEXT_INPUT"
}
```

## Create spans in a batch

`client.Spans.Batch(ctx, body) (*APIListSpan, error)`

**post** `/v5/spans/batch`

Create multiple spans (up to 1000) in a single request and return the created spans.

Prefer this over repeated POST /v5/spans calls when ingesting many spans at
once; use PUT /v5/spans/batch instead when a span with the same `id` may
already exist, since this endpoint inserts new spans rather than overwriting.
A batch larger than 1000 spans is rejected with a validation error. Each item
follows the same id-generation and per-account dual-write rules as the
single-span create, including that `end_timestamp` must not precede
`start_timestamp`, which rejects the request with a 422. When the tracing
service is the primary store, its 400, 413 and 422 rejections keep that status
and detail, as does a 403 when the request carried its own API key, and every
other failure returns a 503 with a Retry-After header. A batch that forms a cycle,
or a span whose parent belongs to another trace, is rejected with 409 before either
store is written. A parent outside the batch is looked up in Postgres, so that part
of the check ends once the account's spans stop being written there. Postgres
rejects an `id` that already exists, while the tracing service treats the write
as an upsert. Which writes the tracing service rejects depends in part on its
storage engine: on Postgres deployments a NUL byte or invalid UTF-8 inside
`trace_id`, `id`, `parent_id` or `group_id` fails the whole batch with a 400
naming the field, because replacing the byte would change the identity the
response echoes; a NUL byte or invalid UTF-8 in any other field is replaced with
U+FFFD and the span is persisted. ClickHouse deployments store the bytes verbatim.

Credential redaction: values in the free-form `input`, `output`, `metadata`,
and `expected` objects, and in `name`, that are credential-shaped (bearer/JWT,
API keys, connection-string passwords) or under a credential-named key are replaced
with `[REDACTED:credential]` before the span is persisted, so the stored and
returned span reflects the redacted value (EY 12.3).

### Parameters

- `body SpanBatchParams`

  - `SpanBatchCreate param.Field[SpanBatchCreate]`

### Returns

- `type APIListSpan struct{…}`

  - `Items []Span`

    - `ID string`

    - `AccountID string`

    - `Name string`

    - `StartTimestamp Time`

    - `TraceID string`

      id for grouping traces together, uuid is recommended

    - `ApplicationInteractionID string`

      The interaction ID this span belongs to

    - `ApplicationVariantID string`

      The id of the application variant this span belongs to

    - `CreatedBy Identity`

      The identity that created the entity.

      - `ID string`

      - `Type IdentityType`

        - `const IdentityTypeUser IdentityType = "user"`

        - `const IdentityTypeServiceAccount IdentityType = "service_account"`

      - `Object IdentityObject`

        - `const IdentityObjectIdentity IdentityObject = "identity"`

    - `EndTimestamp Time`

    - `Expected map[string, any]`

    - `GroupID string`

      Reference to a group_id

    - `Input map[string, any]`

    - `InputTokens int64`

      Prompt tokens the producer reported for this span, absent when it reported none. Same quantity the input_tokens sort orders by.

    - `Metadata map[string, any]`

    - `Object SpanObject`

      - `const SpanObjectSpan SpanObject = "span"`

    - `ObsSpanID string`

      W3C span id of the observability span this span executed in.

    - `ObsTraceID string`

      W3C trace id of the observability trace this span executed in. Null for spans written without the edge, and for accounts still served by the legacy trace store.

    - `Output map[string, any]`

    - `OutputTokens int64`

      Completion tokens the producer reported for this span, absent when it reported none. Same quantity the output_tokens sort orders by.

    - `ParentID string`

      Reference to a parent span_id

    - `Status SpanStatus`

      - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

      - `const SpanStatusError SpanStatus = "ERROR"`

      - `const SpanStatusCanceled SpanStatus = "CANCELED"`

    - `Type SpanType`

      - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

      - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

      - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

      - `const SpanTypeCompletion SpanType = "COMPLETION"`

      - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

      - `const SpanTypeKBInput SpanType = "KB_INPUT"`

      - `const SpanTypeReranking SpanType = "RERANKING"`

      - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

      - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

      - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

      - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

      - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

      - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

      - `const SpanTypeCustom SpanType = "CUSTOM"`

      - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

      - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

      - `const SpanTypeEvaluation SpanType = "EVALUATION"`

      - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

      - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

      - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

      - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

      - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

      - `const SpanTypeTracer SpanType = "TRACER"`

      - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

      - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

      - `const SpanTypeStandalone SpanType = "STANDALONE"`

  - `Object APIListSpanObject`

    - `const APIListSpanObjectList APIListSpanObject = "list"`

### Example

```go
package main

import (
  "context"
  "fmt"
  "time"

  "github.com/scaleapi/sgp-dev-go"
  "github.com/scaleapi/sgp-dev-go/option"
)

func main() {
  client := sgpdev.NewClient(
    option.WithAPIKey("My API Key"),
    option.WithAccountID("My Account ID"),
  )
  apiListSpan, err := client.Spans.Batch(context.TODO(), sgpdev.SpanBatchParams{
    SpanBatchCreate: sgpdev.SpanBatchCreateParam{
      Items: []sgpdev.SpanCreateParam{sgpdev.SpanCreateParam{
        Name: "name",
        StartTimestamp: time.Now(),
        TraceID: "trace_id",
      }},
    },
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", apiListSpan.Items)
}
```

#### Response

```json
{
  "items": [
    {
      "id": "id",
      "account_id": "account_id",
      "name": "name",
      "start_timestamp": "2019-12-27T18:11:19.117Z",
      "trace_id": "trace_id",
      "application_interaction_id": "application_interaction_id",
      "application_variant_id": "application_variant_id",
      "created_by": {
        "id": "id",
        "type": "user",
        "object": "identity"
      },
      "end_timestamp": "2019-12-27T18:11:19.117Z",
      "expected": {
        "foo": "bar"
      },
      "group_id": "group_id",
      "input": {
        "foo": "bar"
      },
      "input_tokens": 0,
      "metadata": {
        "foo": "bar"
      },
      "object": "span",
      "obs_span_id": "obs_span_id",
      "obs_trace_id": "obs_trace_id",
      "output": {
        "foo": "bar"
      },
      "output_tokens": 0,
      "parent_id": "parent_id",
      "status": "SUCCESS",
      "type": "TEXT_INPUT"
    }
  ],
  "object": "list"
}
```

## Upsert spans in a batch

`client.Spans.UpsertBatch(ctx, body) (*APIListSpan, error)`

**put** `/v5/spans/batch`

Insert or replace multiple spans (up to 1000) in a single request.

Use this for idempotent ingestion when spans may already exist, unlike POST
/v5/spans/batch, which only inserts. Items without an `id` are assigned a
generated UUID. The legacy trace store treats `id` as global and collapses
repeated `id`s to the last occurrence. The tracing service keys spans by
`trace_id` and `id`; it retains cross-trace ID collisions, and for a repeated
pair keeps a completed span over an in-progress one, otherwise the later
occurrence wins. In dual-write phases each store applies its own rule, and the
primary store determines the returned list. A batch larger than 1000 spans is
rejected with a validation error, as is any item whose `end_timestamp` precedes
its `start_timestamp`, which returns a 422. When the tracing service is the
primary store, its 400, 413 and 422 rejections keep that status and detail, as does
a 403 when the request carried its own API key, and every other failure returns a
503 with a Retry-After header. A batch that forms a cycle, or a span whose parent
belongs to another trace, is rejected with 409 before either store is written. A
parent outside the batch is looked up in Postgres, so that part of the check ends
once the account's spans stop being written there. Which writes the tracing
service rejects depends in part on its storage engine: on Postgres deployments a
NUL byte or invalid UTF-8 inside `trace_id`, `id`, `parent_id` or `group_id`
fails the whole batch with a 400 naming the field, because replacing the byte would
change the identity the response echoes; a NUL byte or invalid UTF-8 in any other
field is replaced with U+FFFD and the span is persisted. ClickHouse deployments
store the bytes verbatim.

Credential redaction: values in the free-form `input`, `output`, `metadata`,
and `expected` objects, and in `name`, that are credential-shaped (bearer/JWT,
API keys, connection-string passwords) or under a credential-named key are replaced
with `[REDACTED:credential]` before the span is persisted, so the stored and
returned span reflects the redacted value (EY 12.3).

### Parameters

- `body SpanUpsertBatchParams`

  - `SpanBatchCreate param.Field[SpanBatchCreate]`

### Returns

- `type APIListSpan struct{…}`

  - `Items []Span`

    - `ID string`

    - `AccountID string`

    - `Name string`

    - `StartTimestamp Time`

    - `TraceID string`

      id for grouping traces together, uuid is recommended

    - `ApplicationInteractionID string`

      The interaction ID this span belongs to

    - `ApplicationVariantID string`

      The id of the application variant this span belongs to

    - `CreatedBy Identity`

      The identity that created the entity.

      - `ID string`

      - `Type IdentityType`

        - `const IdentityTypeUser IdentityType = "user"`

        - `const IdentityTypeServiceAccount IdentityType = "service_account"`

      - `Object IdentityObject`

        - `const IdentityObjectIdentity IdentityObject = "identity"`

    - `EndTimestamp Time`

    - `Expected map[string, any]`

    - `GroupID string`

      Reference to a group_id

    - `Input map[string, any]`

    - `InputTokens int64`

      Prompt tokens the producer reported for this span, absent when it reported none. Same quantity the input_tokens sort orders by.

    - `Metadata map[string, any]`

    - `Object SpanObject`

      - `const SpanObjectSpan SpanObject = "span"`

    - `ObsSpanID string`

      W3C span id of the observability span this span executed in.

    - `ObsTraceID string`

      W3C trace id of the observability trace this span executed in. Null for spans written without the edge, and for accounts still served by the legacy trace store.

    - `Output map[string, any]`

    - `OutputTokens int64`

      Completion tokens the producer reported for this span, absent when it reported none. Same quantity the output_tokens sort orders by.

    - `ParentID string`

      Reference to a parent span_id

    - `Status SpanStatus`

      - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

      - `const SpanStatusError SpanStatus = "ERROR"`

      - `const SpanStatusCanceled SpanStatus = "CANCELED"`

    - `Type SpanType`

      - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

      - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

      - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

      - `const SpanTypeCompletion SpanType = "COMPLETION"`

      - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

      - `const SpanTypeKBInput SpanType = "KB_INPUT"`

      - `const SpanTypeReranking SpanType = "RERANKING"`

      - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

      - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

      - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

      - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

      - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

      - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

      - `const SpanTypeCustom SpanType = "CUSTOM"`

      - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

      - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

      - `const SpanTypeEvaluation SpanType = "EVALUATION"`

      - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

      - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

      - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

      - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

      - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

      - `const SpanTypeTracer SpanType = "TRACER"`

      - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

      - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

      - `const SpanTypeStandalone SpanType = "STANDALONE"`

  - `Object APIListSpanObject`

    - `const APIListSpanObjectList APIListSpanObject = "list"`

### Example

```go
package main

import (
  "context"
  "fmt"
  "time"

  "github.com/scaleapi/sgp-dev-go"
  "github.com/scaleapi/sgp-dev-go/option"
)

func main() {
  client := sgpdev.NewClient(
    option.WithAPIKey("My API Key"),
    option.WithAccountID("My Account ID"),
  )
  apiListSpan, err := client.Spans.UpsertBatch(context.TODO(), sgpdev.SpanUpsertBatchParams{
    SpanBatchCreate: sgpdev.SpanBatchCreateParam{
      Items: []sgpdev.SpanCreateParam{sgpdev.SpanCreateParam{
        Name: "name",
        StartTimestamp: time.Now(),
        TraceID: "trace_id",
      }},
    },
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", apiListSpan.Items)
}
```

#### Response

```json
{
  "items": [
    {
      "id": "id",
      "account_id": "account_id",
      "name": "name",
      "start_timestamp": "2019-12-27T18:11:19.117Z",
      "trace_id": "trace_id",
      "application_interaction_id": "application_interaction_id",
      "application_variant_id": "application_variant_id",
      "created_by": {
        "id": "id",
        "type": "user",
        "object": "identity"
      },
      "end_timestamp": "2019-12-27T18:11:19.117Z",
      "expected": {
        "foo": "bar"
      },
      "group_id": "group_id",
      "input": {
        "foo": "bar"
      },
      "input_tokens": 0,
      "metadata": {
        "foo": "bar"
      },
      "object": "span",
      "obs_span_id": "obs_span_id",
      "obs_trace_id": "obs_trace_id",
      "output": {
        "foo": "bar"
      },
      "output_tokens": 0,
      "parent_id": "parent_id",
      "status": "SUCCESS",
      "type": "TEXT_INPUT"
    }
  ],
  "object": "list"
}
```

## Search spans

`client.Spans.Search(ctx, params) (*CursorPage[Span], error)`

**post** `/v5/spans/search`

Search and list spans matching a set of filters, returning a keyset-paginated page.

Filters in the request body include trace and span ids, names, statuses,
types, free-text search, metadata, duration bounds, and more, scoped to an
optional time window. Results are keyset-paginated on indexed columns rather
than offset-paginated, and `total` is not computed (it is always 0); use the
pagination cursors to page through results. Reads route to the legacy trace
store or the tracing service per account (with fallback to the legacy trace
store outside strict mode), and results are narrowed to traces the caller is authorized to
read — a filter that resolves to no authorized traces yields an empty page
rather than an error. A reversed time window (`from_ts` after `to_ts`) is
rejected with 422, as is a request whose combined `trace_ids`, `span_ids`,
`excluded_span_ids`, `excluded_trace_ids`, and `parent_ids` count exceeds
10000. `sort_by` accepts `start_timestamp`, `duration_ms`,
`input_tokens` and `output_tokens`; the token counts are read from usage
reported at ingest, and a span whose producer reported none sorts as zero, so
it lands last descending and first ascending. The two token sorts are rejected
for an account still served by the legacy trace store, which keeps no token count
to order by. Any other unsupported sort falls back to timestamp order there.
Spans sharing a sort key are ordered by `trace_id` and `id` bytewise on both
tracing-service engines. Text search tokenization, indexed-prefix, word-length,
locale and metadata-bytes behavior differs between Postgres and ClickHouse
deployments of the tracing service as the `search_texts` field describes.

`x-project-id` narrows the result to traces whose root span carries that project,
when `PROJECT_SCOPED_SPAN_LISTING` is on for the account. An account the tracing service
serves holds no project placement, so a request carrying the header is rejected with
422 there.

### Parameters

- `params SpanSearchParams`

  - `AllowShortPages param.Field[bool]`

    Query param: Return however many spans fit the server byte budget instead of a 400 SEARCH_RESULT_TOO_LARGE, reporting the rest through has_more plus next_cursor going forward or prev_cursor going back. Send it only if the client reads has_more, because under it a page shorter than limit no longer means the end of the list. Honored by the tracing service on either of its storage engines. Accounts still served by the legacy trace store ignore it and page by item count, where a short page still means the end of the list.

  - `EndingBefore param.Field[string]`

    Query param

  - `FromTs param.Field[Time]`

    Query param: The starting (oldest) timestamp in ISO format.

  - `Limit param.Field[int64]`

    Query param

  - `SortBy param.Field[string]`

    Query param

  - `SortOrder param.Field[SortOrder]`

    Query param

  - `StartingAfter param.Field[string]`

    Query param

  - `ToTs param.Field[Time]`

    Query param: The ending (most recent) timestamp in ISO format.

  - `AcpTypes param.Field[[]string]`

    Body param: Filter by ACP types

  - `AgentexAgentIDs param.Field[[]string]`

    Body param: Filter by Agentex agent IDs

  - `AgentexAgentNames param.Field[[]string]`

    Body param: Filter by Agentex agent names

  - `ApplicationVariantIDs param.Field[[]string]`

    Body param: Filter by application variant IDs

  - `AssessmentTypes param.Field[[]string]`

    Body param: Filter to spans that have at least one assessment of these types

  - `ExcludedSpanIDs param.Field[[]string]`

    Body param: List of span IDs to exclude from results

  - `ExcludedSpans param.Field[[]SpanSearchParamsExcludedSpan]`

    Body param: List of (trace_id, span_id) identities to exclude from results. Unlike excluded_span_ids, a pair never excludes a same-id span from another trace. Takes precedence over excluded_span_ids when both are set.

    - `SpanID string`

      Span ID of the referenced span

    - `TraceID string`

      Trace ID of the referenced span

  - `ExcludedTraceIDs param.Field[[]string]`

    Body param: List of trace IDs to exclude from results

  - `ExtraMetadata param.Field[map[string, any]]`

    Body param: Filter on custom metadata: each key must equal its value, or any value of an array, and keys are ANDed. On the ClickHouse read path `$or` and `$and` also compose nested groups of predicates. On Postgres a `$`-prefixed key is an ordinary metadata key matched literally. Array values match element-wise; a negative zero inside an array equals zero on Postgres-served accounts and not on ClickHouse-served ones.

  - `GroupID param.Field[string]`

    Body param: Filter by group ID

  - `MaxDurationMs param.Field[int64]`

    Body param: Maximum span duration in milliseconds (inclusive). Matched on completed duration, so a span with no end time is never returned: fetch it by its own id or in its trace's span list.

  - `MinDurationMs param.Field[int64]`

    Body param: Minimum span duration in milliseconds (inclusive). Matched on completed duration, so a span with no end time is not reliably returned: fetch it by its own id or in its trace's span list.

  - `Names param.Field[[]string]`

    Body param: Filter by trace/span name

  - `ObsSpanIDs param.Field[[]string]`

    Body param: Filter to the business spans that executed in any of these observability spans. Each id must be 16 lowercase hex characters. A W3C span id is unique per trace only, so combine with obs_trace_ids for exact identity, the same looseness span_ids carries versus the spans pair filter. ANDs with obs_trace_ids when both are set. Served only by the sgp-traces service, so a request using this filter against an account still on the legacy store returns 422 rather than silently ignoring it.

  - `ObsTraceIDs param.Field[[]string]`

    Body param: Filter to the business spans that executed in any of these observability traces (the obs-to-business reverse lookup). Each id must be 32 lowercase hex characters. Served only by the sgp-traces service, so a request using this filter against an account still on the legacy store returns 422 rather than silently ignoring it.

  - `ParentIDs param.Field[[]string]`

    Body param: Filter to the direct children of any of these parent span IDs

  - `ParentsOnly param.Field[bool]`

    Body param: Only fetch spans that are the top-level (ie. have no parent_id)

  - `SearchTexts param.Field[[]string]`

    Body param: Case-insensitive text search across span name, input, output, and metadata. A single-word term of ASCII letters and digits matches as a whole word in input, output, and metadata, and as a substring of the name. A term of up to 8 such words matches as a contiguous phrase whose words each appear as whole words. All other terms (punctuated, non-ASCII, longer) match as substrings, where mid-word fragments match and an inflected form such as a plural matches only where it appears literally. Wrapping a term in double quotes makes it a phrase: the quotes mark the phrase and are never matched, a backslash escapes a quote or a backslash inside them, the phrase must appear contiguously inside one searched value (the input, the output, or the metadata), a phrase of up to 8 ASCII letter-and-digit words additionally requires each of those words to appear there as a whole word, and a UUID-shaped phrase stays a text search. A term whose quote is unterminated or left unescaped mid-term is matched literally, quotes included. Multiple terms are ANDed, and UUID-shaped terms match trace IDs instead. A span must match every non-UUID term, and each term may match any of the searched fields. UUID matches are ORed onto the text match. Each term must be at least 2 characters, measured between the quotes and ignoring outer whitespace for a phrase, and at most 10 terms are supported. For exact trace ID lookup, use the `trace_ids` filter. The tracing service runs on either ClickHouse or Postgres, and the two engines match differently. On Postgres deployments the whole-word match uses the simple text-search parser, which keeps hosts, e-mail addresses, file paths, version strings, hyphenated compounds, URLs and query strings as single words (https://x.com/path?q=1 yields x.com/path?q=1, x.com and /path?q=1, never path, q or 1; user@example.com and v1.2.3 are one word each; gpt-4o yields the compound and its parts), whereas ClickHouse deployments split on every non-alphanumeric ASCII byte. A single word inside such a value is a whole-word hit on ClickHouse and a miss on Postgres; the substring forms behave identically on both. On Postgres deployments a value over 80000 bytes has only its first 20000 characters indexed for whole-word matching; text past that is reachable only by the substring forms. Words longer than 2047 bytes are matched as substrings, never as whole words. Case folding of non-ASCII text follows the database's LC_CTYPE on Postgres deployments, for the whole-word index, the quoted-phrase and substring forms and the word-boundary check alike; under a C-locale database non-ASCII letters are not folded. ASCII folds everywhere. Input and output behave identically on both engines. A substring-form term, or a text-filtered metrics request, reads every row of the time window that survives the other filters. A term that matches too many rows in the window is refused by the tracing service as QUERY_TOO_BROAD, at an engine-specific threshold; whether this API relays that refusal as a 400 or answers the page from the legacy trace store follows its read-routing rules, and an export's refusal is reported as the failed export's reason on the export status, not on the POST. On Postgres deployments each term is counted on its own, in every class (whole word, phrase and substring alike) and on every read that carries text, and is refused when it alone matches more than 50000 rows of the window that survive the other filters, with or without assessment_types. On ClickHouse deployments the refusal is the candidate-set cap, a deployment-configured limit counted over the matches of all terms together: a search page bounds its candidates to the page, so there the cap is a backstop rather than a limit a common term meets; metrics and by-span resolve every match and can trip it; and an export runs under its own 2000000-row set cap on every request, assessment_types included. Accounts still served by the legacy trace store match differently until migrated: every term matches as stemmed whole words (so inflected forms match and multi-word terms match word-adjacent), only input and output are searched, the 2-character minimum is not enforced, quoting a term changes nothing (the quotes are stripped and a multi-word term is already matched word-adjacent), and characters like `:`, `|`, or `!` inside a term may be interpreted as query operators or cause an error.

  - `SpanIDs param.Field[[]string]`

    Body param: Filter by span IDs

  - `Spans param.Field[[]SpanSearchParamsSpan]`

    Body param: Filter by exact (trace_id, span_id) identity. Unlike span_ids, a pair never matches a same-id span from another trace. ANDs with span_ids when both are set.

    - `SpanID string`

      Span ID of the referenced span

    - `TraceID string`

      Trace ID of the referenced span

  - `Statuses param.Field[[]SpanStatus]`

    Body param: Filter on span status

    - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

    - `const SpanStatusError SpanStatus = "ERROR"`

    - `const SpanStatusCanceled SpanStatus = "CANCELED"`

  - `TraceIDs param.Field[[]string]`

    Body param: Filter by trace IDs. The combined count of trace_ids, span_ids, excluded_span_ids, excluded_trace_ids, parent_ids, and (trace_id, span_id) pairs (each pair counting 2) may not exceed 10000. A request over that returns 422.

  - `Types param.Field[[]SpanType]`

    Body param

    - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

    - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

    - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

    - `const SpanTypeCompletion SpanType = "COMPLETION"`

    - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

    - `const SpanTypeKBInput SpanType = "KB_INPUT"`

    - `const SpanTypeReranking SpanType = "RERANKING"`

    - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

    - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

    - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

    - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

    - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

    - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

    - `const SpanTypeCustom SpanType = "CUSTOM"`

    - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

    - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

    - `const SpanTypeEvaluation SpanType = "EVALUATION"`

    - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

    - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

    - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

    - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

    - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

    - `const SpanTypeTracer SpanType = "TRACER"`

    - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

    - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

    - `const SpanTypeStandalone SpanType = "STANDALONE"`

  - `XProjectID param.Field[string]`

    Header param

### Returns

- `type Span struct{…}`

  - `ID string`

  - `AccountID string`

  - `Name string`

  - `StartTimestamp Time`

  - `TraceID string`

    id for grouping traces together, uuid is recommended

  - `ApplicationInteractionID string`

    The interaction ID this span belongs to

  - `ApplicationVariantID string`

    The id of the application variant this span belongs to

  - `CreatedBy Identity`

    The identity that created the entity.

    - `ID string`

    - `Type IdentityType`

      - `const IdentityTypeUser IdentityType = "user"`

      - `const IdentityTypeServiceAccount IdentityType = "service_account"`

    - `Object IdentityObject`

      - `const IdentityObjectIdentity IdentityObject = "identity"`

  - `EndTimestamp Time`

  - `Expected map[string, any]`

  - `GroupID string`

    Reference to a group_id

  - `Input map[string, any]`

  - `InputTokens int64`

    Prompt tokens the producer reported for this span, absent when it reported none. Same quantity the input_tokens sort orders by.

  - `Metadata map[string, any]`

  - `Object SpanObject`

    - `const SpanObjectSpan SpanObject = "span"`

  - `ObsSpanID string`

    W3C span id of the observability span this span executed in.

  - `ObsTraceID string`

    W3C trace id of the observability trace this span executed in. Null for spans written without the edge, and for accounts still served by the legacy trace store.

  - `Output map[string, any]`

  - `OutputTokens int64`

    Completion tokens the producer reported for this span, absent when it reported none. Same quantity the output_tokens sort orders by.

  - `ParentID string`

    Reference to a parent span_id

  - `Status SpanStatus`

    - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

    - `const SpanStatusError SpanStatus = "ERROR"`

    - `const SpanStatusCanceled SpanStatus = "CANCELED"`

  - `Type SpanType`

    - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

    - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

    - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

    - `const SpanTypeCompletion SpanType = "COMPLETION"`

    - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

    - `const SpanTypeKBInput SpanType = "KB_INPUT"`

    - `const SpanTypeReranking SpanType = "RERANKING"`

    - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

    - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

    - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

    - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

    - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

    - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

    - `const SpanTypeCustom SpanType = "CUSTOM"`

    - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

    - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

    - `const SpanTypeEvaluation SpanType = "EVALUATION"`

    - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

    - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

    - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

    - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

    - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

    - `const SpanTypeTracer SpanType = "TRACER"`

    - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

    - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

    - `const SpanTypeStandalone SpanType = "STANDALONE"`

### Example

```go
package main

import (
  "context"
  "fmt"

  "github.com/scaleapi/sgp-dev-go"
  "github.com/scaleapi/sgp-dev-go/option"
)

func main() {
  client := sgpdev.NewClient(
    option.WithAPIKey("My API Key"),
    option.WithAccountID("My Account ID"),
  )
  page, err := client.Spans.Search(context.TODO(), sgpdev.SpanSearchParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}
```

#### Response

```json
{
  "has_more": true,
  "items": [
    {
      "id": "id",
      "account_id": "account_id",
      "name": "name",
      "start_timestamp": "2019-12-27T18:11:19.117Z",
      "trace_id": "trace_id",
      "application_interaction_id": "application_interaction_id",
      "application_variant_id": "application_variant_id",
      "created_by": {
        "id": "id",
        "type": "user",
        "object": "identity"
      },
      "end_timestamp": "2019-12-27T18:11:19.117Z",
      "expected": {
        "foo": "bar"
      },
      "group_id": "group_id",
      "input": {
        "foo": "bar"
      },
      "input_tokens": 0,
      "metadata": {
        "foo": "bar"
      },
      "object": "span",
      "obs_span_id": "obs_span_id",
      "obs_trace_id": "obs_trace_id",
      "output": {
        "foo": "bar"
      },
      "output_tokens": 0,
      "parent_id": "parent_id",
      "status": "SUCCESS",
      "type": "TEXT_INPUT"
    }
  ],
  "total": 0,
  "effective_from_ts": "2019-12-27T18:11:19.117Z",
  "effective_to_ts": "2019-12-27T18:11:19.117Z",
  "limit": 0,
  "next_cursor": "next_cursor",
  "object": "list",
  "prev_cursor": "prev_cursor",
  "window_truncated": true
}
```

## Domain Types

### API List Span

- `type APIListSpan struct{…}`

  - `Items []Span`

    - `ID string`

    - `AccountID string`

    - `Name string`

    - `StartTimestamp Time`

    - `TraceID string`

      id for grouping traces together, uuid is recommended

    - `ApplicationInteractionID string`

      The interaction ID this span belongs to

    - `ApplicationVariantID string`

      The id of the application variant this span belongs to

    - `CreatedBy Identity`

      The identity that created the entity.

      - `ID string`

      - `Type IdentityType`

        - `const IdentityTypeUser IdentityType = "user"`

        - `const IdentityTypeServiceAccount IdentityType = "service_account"`

      - `Object IdentityObject`

        - `const IdentityObjectIdentity IdentityObject = "identity"`

    - `EndTimestamp Time`

    - `Expected map[string, any]`

    - `GroupID string`

      Reference to a group_id

    - `Input map[string, any]`

    - `InputTokens int64`

      Prompt tokens the producer reported for this span, absent when it reported none. Same quantity the input_tokens sort orders by.

    - `Metadata map[string, any]`

    - `Object SpanObject`

      - `const SpanObjectSpan SpanObject = "span"`

    - `ObsSpanID string`

      W3C span id of the observability span this span executed in.

    - `ObsTraceID string`

      W3C trace id of the observability trace this span executed in. Null for spans written without the edge, and for accounts still served by the legacy trace store.

    - `Output map[string, any]`

    - `OutputTokens int64`

      Completion tokens the producer reported for this span, absent when it reported none. Same quantity the output_tokens sort orders by.

    - `ParentID string`

      Reference to a parent span_id

    - `Status SpanStatus`

      - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

      - `const SpanStatusError SpanStatus = "ERROR"`

      - `const SpanStatusCanceled SpanStatus = "CANCELED"`

    - `Type SpanType`

      - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

      - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

      - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

      - `const SpanTypeCompletion SpanType = "COMPLETION"`

      - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

      - `const SpanTypeKBInput SpanType = "KB_INPUT"`

      - `const SpanTypeReranking SpanType = "RERANKING"`

      - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

      - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

      - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

      - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

      - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

      - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

      - `const SpanTypeCustom SpanType = "CUSTOM"`

      - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

      - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

      - `const SpanTypeEvaluation SpanType = "EVALUATION"`

      - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

      - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

      - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

      - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

      - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

      - `const SpanTypeTracer SpanType = "TRACER"`

      - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

      - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

      - `const SpanTypeStandalone SpanType = "STANDALONE"`

  - `Object APIListSpanObject`

    - `const APIListSpanObjectList APIListSpanObject = "list"`

### Span

- `type Span struct{…}`

  - `ID string`

  - `AccountID string`

  - `Name string`

  - `StartTimestamp Time`

  - `TraceID string`

    id for grouping traces together, uuid is recommended

  - `ApplicationInteractionID string`

    The interaction ID this span belongs to

  - `ApplicationVariantID string`

    The id of the application variant this span belongs to

  - `CreatedBy Identity`

    The identity that created the entity.

    - `ID string`

    - `Type IdentityType`

      - `const IdentityTypeUser IdentityType = "user"`

      - `const IdentityTypeServiceAccount IdentityType = "service_account"`

    - `Object IdentityObject`

      - `const IdentityObjectIdentity IdentityObject = "identity"`

  - `EndTimestamp Time`

  - `Expected map[string, any]`

  - `GroupID string`

    Reference to a group_id

  - `Input map[string, any]`

  - `InputTokens int64`

    Prompt tokens the producer reported for this span, absent when it reported none. Same quantity the input_tokens sort orders by.

  - `Metadata map[string, any]`

  - `Object SpanObject`

    - `const SpanObjectSpan SpanObject = "span"`

  - `ObsSpanID string`

    W3C span id of the observability span this span executed in.

  - `ObsTraceID string`

    W3C trace id of the observability trace this span executed in. Null for spans written without the edge, and for accounts still served by the legacy trace store.

  - `Output map[string, any]`

  - `OutputTokens int64`

    Completion tokens the producer reported for this span, absent when it reported none. Same quantity the output_tokens sort orders by.

  - `ParentID string`

    Reference to a parent span_id

  - `Status SpanStatus`

    - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

    - `const SpanStatusError SpanStatus = "ERROR"`

    - `const SpanStatusCanceled SpanStatus = "CANCELED"`

  - `Type SpanType`

    - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

    - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

    - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

    - `const SpanTypeCompletion SpanType = "COMPLETION"`

    - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

    - `const SpanTypeKBInput SpanType = "KB_INPUT"`

    - `const SpanTypeReranking SpanType = "RERANKING"`

    - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

    - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

    - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

    - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

    - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

    - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

    - `const SpanTypeCustom SpanType = "CUSTOM"`

    - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

    - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

    - `const SpanTypeEvaluation SpanType = "EVALUATION"`

    - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

    - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

    - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

    - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

    - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

    - `const SpanTypeTracer SpanType = "TRACER"`

    - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

    - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

    - `const SpanTypeStandalone SpanType = "STANDALONE"`

### Span Batch Create

- `type SpanBatchCreate struct{…}`

  - `Items []SpanCreate`

    - `Name string`

    - `StartTimestamp Time`

      When the span started. With trace_id and id it forms the span's storage identity, so a span re-sent with a start_timestamp on another UTC day is stored as a second row that the store never collapses. Get span and trace detail return the newest version. Search returns the newest version whose start_timestamp falls in the queried window. Export, metrics and facets count both rows until the trace is deleted and re-sent.

    - `TraceID string`

      id for grouping traces together, uuid is recommended

    - `ID string`

      The id of the span, at most 256 bytes. A value longer than 256 characters is refused here with a 422 before it is forwarded; a value within that count whose UTF-8 form exceeds 256 bytes is refused with a 400 naming the field once the tracing service is the account's primary store, and accepted for accounts still written primarily to the legacy trace store.

    - `ApplicationInteractionID string`

      The optional application interaction ID this span belongs to

    - `ApplicationVariantID string`

      The optional application variant ID this span belongs to

    - `EndTimestamp Time`

    - `Expected map[string, any]`

    - `GroupID string`

      Reference to a group_id, at most 256 bytes. A value longer than 256 characters is refused here with a 422 before it is forwarded; a value within that count whose UTF-8 form exceeds 256 bytes is refused with a 400 naming the field once the tracing service is the account's primary store, and accepted for accounts still written primarily to the legacy trace store.

    - `Input map[string, any]`

    - `Metadata map[string, any]`

    - `ObsSpanID string`

      W3C span id (16 lowercase hex chars) of the observability span this span executed in. Requires obs_trace_id.

    - `ObsTraceID string`

      W3C trace id (32 lowercase hex chars) of the observability trace this span executed in, for correlating a business span with the infrastructure work it caused. Stored only by the sgp-traces service, so accounts still served by the legacy store accept the field and read it back as null.

    - `Output map[string, any]`

    - `ParentID string`

      Reference to a parent span_id

    - `Status SpanStatus`

      - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

      - `const SpanStatusError SpanStatus = "ERROR"`

      - `const SpanStatusCanceled SpanStatus = "CANCELED"`

    - `Type SpanType`

      - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

      - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

      - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

      - `const SpanTypeCompletion SpanType = "COMPLETION"`

      - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

      - `const SpanTypeKBInput SpanType = "KB_INPUT"`

      - `const SpanTypeReranking SpanType = "RERANKING"`

      - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

      - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

      - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

      - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

      - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

      - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

      - `const SpanTypeCustom SpanType = "CUSTOM"`

      - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

      - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

      - `const SpanTypeEvaluation SpanType = "EVALUATION"`

      - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

      - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

      - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

      - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

      - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

      - `const SpanTypeTracer SpanType = "TRACER"`

      - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

      - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

      - `const SpanTypeStandalone SpanType = "STANDALONE"`

### Span Create

- `type SpanCreate struct{…}`

  - `Name string`

  - `StartTimestamp Time`

    When the span started. With trace_id and id it forms the span's storage identity, so a span re-sent with a start_timestamp on another UTC day is stored as a second row that the store never collapses. Get span and trace detail return the newest version. Search returns the newest version whose start_timestamp falls in the queried window. Export, metrics and facets count both rows until the trace is deleted and re-sent.

  - `TraceID string`

    id for grouping traces together, uuid is recommended

  - `ID string`

    The id of the span, at most 256 bytes. A value longer than 256 characters is refused here with a 422 before it is forwarded; a value within that count whose UTF-8 form exceeds 256 bytes is refused with a 400 naming the field once the tracing service is the account's primary store, and accepted for accounts still written primarily to the legacy trace store.

  - `ApplicationInteractionID string`

    The optional application interaction ID this span belongs to

  - `ApplicationVariantID string`

    The optional application variant ID this span belongs to

  - `EndTimestamp Time`

  - `Expected map[string, any]`

  - `GroupID string`

    Reference to a group_id, at most 256 bytes. A value longer than 256 characters is refused here with a 422 before it is forwarded; a value within that count whose UTF-8 form exceeds 256 bytes is refused with a 400 naming the field once the tracing service is the account's primary store, and accepted for accounts still written primarily to the legacy trace store.

  - `Input map[string, any]`

  - `Metadata map[string, any]`

  - `ObsSpanID string`

    W3C span id (16 lowercase hex chars) of the observability span this span executed in. Requires obs_trace_id.

  - `ObsTraceID string`

    W3C trace id (32 lowercase hex chars) of the observability trace this span executed in, for correlating a business span with the infrastructure work it caused. Stored only by the sgp-traces service, so accounts still served by the legacy store accept the field and read it back as null.

  - `Output map[string, any]`

  - `ParentID string`

    Reference to a parent span_id

  - `Status SpanStatus`

    - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

    - `const SpanStatusError SpanStatus = "ERROR"`

    - `const SpanStatusCanceled SpanStatus = "CANCELED"`

  - `Type SpanType`

    - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

    - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

    - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

    - `const SpanTypeCompletion SpanType = "COMPLETION"`

    - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

    - `const SpanTypeKBInput SpanType = "KB_INPUT"`

    - `const SpanTypeReranking SpanType = "RERANKING"`

    - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

    - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

    - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

    - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

    - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

    - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

    - `const SpanTypeCustom SpanType = "CUSTOM"`

    - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

    - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

    - `const SpanTypeEvaluation SpanType = "EVALUATION"`

    - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

    - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

    - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

    - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

    - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

    - `const SpanTypeTracer SpanType = "TRACER"`

    - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

    - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

    - `const SpanTypeStandalone SpanType = "STANDALONE"`

### Span Status

- `type SpanStatus string`

  - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

  - `const SpanStatusError SpanStatus = "ERROR"`

  - `const SpanStatusCanceled SpanStatus = "CANCELED"`

### Span Type

- `type SpanType string`

  - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

  - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

  - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

  - `const SpanTypeCompletion SpanType = "COMPLETION"`

  - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

  - `const SpanTypeKBInput SpanType = "KB_INPUT"`

  - `const SpanTypeReranking SpanType = "RERANKING"`

  - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

  - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

  - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

  - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

  - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

  - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

  - `const SpanTypeCustom SpanType = "CUSTOM"`

  - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

  - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

  - `const SpanTypeEvaluation SpanType = "EVALUATION"`

  - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

  - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

  - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

  - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

  - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

  - `const SpanTypeTracer SpanType = "TRACER"`

  - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

  - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

  - `const SpanTypeStandalone SpanType = "STANDALONE"`
