bem

package module
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

README

Bem Go API Library

Go Reference

The Bem Go library provides convenient access to the Bem REST API from applications written in Go.

It is generated with Stainless.

MCP Server

Use the Bem MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.

Add to Cursor Install in VS Code

Note: You may need to set environment variables in your MCP client.

Installation

import (
	"github.com/bem-team/bem-go-sdk" // imported as bem
)

Or to pin the version:

go get -u 'github.com/bem-team/bem-go-sdk@v0.13.0'

Requirements

This library requires Go 1.22+.

Usage

The full API of this library can be found in api.md.

package main

import (
	"context"
	"fmt"

	"github.com/bem-team/bem-go-sdk"
	"github.com/bem-team/bem-go-sdk/option"
)

func main() {
	client := bem.NewClient(
		option.WithAPIKey("My API Key"), // defaults to os.LookupEnv("BEM_API_KEY")
	)
	functionResponse, err := client.Functions.New(context.TODO(), bem.FunctionNewParams{
		CreateFunction: bem.CreateFunctionUnionParam{
			OfExtract: &bem.CreateFunctionExtractParam{
				FunctionName: "functionName",
			},
		},
	})
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("%+v\n", functionResponse.Function)
}

Request fields

The bem library uses the omitzero semantics from the Go 1.24+ encoding/json release for request fields.

Required primitive fields (int64, string, etc.) feature the tag `api:"required"`. These fields are always serialized, even their zero values.

Optional primitive types are wrapped in a param.Opt[T]. These fields can be set with the provided constructors, bem.String(string), bem.Int(int64), etc.

Any param.Opt[T], map, slice, struct or string enum uses the tag `json:"...,omitzero"`. Its zero value is considered omitted.

The param.IsOmitted(any) function can confirm the presence of any omitzero field.

p := bem.ExampleParams{
	ID:   "id_xxx",          // required property
	Name: bem.String("..."), // optional property

	Point: bem.Point{
		X: 0,          // required field will serialize as 0
		Y: bem.Int(1), // optional field will serialize as 1
		// ... omitted non-required fields will not be serialized
	},

	Origin: bem.Origin{}, // the zero value of [Origin] is considered omitted
}

To send null instead of a param.Opt[T], use param.Null[T](). To send null instead of a struct T, use param.NullStruct[T]().

p.Name = param.Null[string]()       // 'null' instead of string
p.Point = param.NullStruct[Point]() // 'null' instead of struct

param.IsNull(p.Name)  // true
param.IsNull(p.Point) // true

Request structs contain a .SetExtraFields(map[string]any) method which can send non-conforming fields in the request body. Extra fields overwrite any struct fields with a matching key. For security reasons, only use SetExtraFields with trusted data.

To send a custom value instead of a struct, use param.Override[T](value).

// In cases where the API specifies a given type,
// but you want to send something else, use [SetExtraFields]:
p.SetExtraFields(map[string]any{
	"x": 0.01, // send "x" as a float instead of int
})

// Send a number instead of an object
custom := param.Override[bem.FooParams](12)
Request unions

Unions are represented as a struct with fields prefixed by "Of" for each of its variants, only one field can be non-zero. The non-zero field will be serialized.

Sub-properties of the union can be accessed via methods on the union struct. These methods return a mutable pointer to the underlying data, if present.

// Only one field can be non-zero, use param.IsOmitted() to check if a field is set
type AnimalUnionParam struct {
	OfCat *Cat `json:",omitzero,inline`
	OfDog *Dog `json:",omitzero,inline`
}

animal := AnimalUnionParam{
	OfCat: &Cat{
		Name: "Whiskers",
		Owner: PersonParam{
			Address: AddressParam{Street: "3333 Coyote Hill Rd", Zip: 0},
		},
	},
}

// Mutating a field
if address := animal.GetOwner().GetAddress(); address != nil {
	address.ZipCode = 94304
}
Response objects

All fields in response structs are ordinary value types (not pointers or wrappers). Response structs also include a special JSON field containing metadata about each property.

type Animal struct {
	Name   string `json:"name,nullable"`
	Owners int    `json:"owners"`
	Age    int    `json:"age"`
	JSON   struct {
		Name        respjson.Field
		Owner       respjson.Field
		Age         respjson.Field
		ExtraFields map[string]respjson.Field
	} `json:"-"`
}

To handle optional data, use the .Valid() method on the JSON field. .Valid() returns true if a field is not null, not present, or couldn't be marshaled.

If .Valid() is false, the corresponding field will simply be its zero value.

raw := `{"owners": 1, "name": null}`

var res Animal
json.Unmarshal([]byte(raw), &res)

// Accessing regular fields

res.Owners // 1
res.Name   // ""
res.Age    // 0

// Optional field checks

res.JSON.Owners.Valid() // true
res.JSON.Name.Valid()   // false
res.JSON.Age.Valid()    // false

// Raw JSON values

res.JSON.Owners.Raw()                  // "1"
res.JSON.Name.Raw() == "null"          // true
res.JSON.Name.Raw() == respjson.Null   // true
res.JSON.Age.Raw() == ""               // true
res.JSON.Age.Raw() == respjson.Omitted // true

These .JSON structs also include an ExtraFields map containing any properties in the json response that were not specified in the struct. This can be useful for API features not yet present in the SDK.

body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
Response Unions

In responses, unions are represented by a flattened struct containing all possible fields from each of the object variants. To convert it to a variant use the .AsFooVariant() method or the .AsAny() method if present.

If a response value union contains primitive values, primitive fields will be alongside the properties but prefixed with Of and feature the tag json:"...,inline".

type AnimalUnion struct {
	// From variants [Dog], [Cat]
	Owner Person `json:"owner"`
	// From variant [Dog]
	DogBreed string `json:"dog_breed"`
	// From variant [Cat]
	CatBreed string `json:"cat_breed"`
	// ...

	JSON struct {
		Owner respjson.Field
		// ...
	} `json:"-"`
}

// If animal variant
if animal.Owner.Address.ZipCode == "" {
	panic("missing zip code")
}

// Switch on the variant
switch variant := animal.AsAny().(type) {
case Dog:
case Cat:
default:
	panic("unexpected type")
}
RequestOptions

This library uses the functional options pattern. Functions defined in the option package return a RequestOption, which is a closure that mutates a RequestConfig. These options can be supplied to the client or at individual requests. For example:

client := bem.NewClient(
	// Adds a header to every request made by the client
	option.WithHeader("X-Some-Header", "custom_header_info"),
)

client.Functions.New(context.TODO(), ...,
	// Override the header
	option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
	// Add an undocumented field to the request body, using sjson syntax
	option.WithJSONSet("some.json.path", map[string]string{"my": "object"}),
)

The request option option.WithDebugLog(nil) may be helpful while debugging.

See the full list of request options.

Pagination

This library provides some conveniences for working with paginated list endpoints.

You can use .ListAutoPaging() methods to iterate through items across all pages:

iter := client.Functions.ListAutoPaging(context.TODO(), bem.FunctionListParams{})
// Automatically fetches more pages as needed.
for iter.Next() {
	function := iter.Current()
	fmt.Printf("%+v\n", function)
}
if err := iter.Err(); err != nil {
	panic(err.Error())
}

Or you can use simple .List() methods to fetch a single page and receive a standard response object with additional helper methods like .GetNextPage(), e.g.:

page, err := client.Functions.List(context.TODO(), bem.FunctionListParams{})
for page != nil {
	for _, function := range page.Functions {
		fmt.Printf("%+v\n", function)
	}
	page, err = page.GetNextPage()
}
if err != nil {
	panic(err.Error())
}
Errors

When the API returns a non-success status code, we return an error with type *bem.Error. This contains the StatusCode, *http.Request, and *http.Response values of the request, as well as the JSON of the error body (much like other response objects in the SDK).

To handle errors, we recommend that you use the errors.As pattern:

_, err := client.Functions.New(context.TODO(), bem.FunctionNewParams{
	CreateFunction: bem.CreateFunctionUnionParam{
		OfExtract: &bem.CreateFunctionExtractParam{
			FunctionName: "functionName",
		},
	},
})
if err != nil {
	var apierr *bem.Error
	if errors.As(err, &apierr) {
		println(string(apierr.DumpRequest(true)))  // Prints the serialized HTTP request
		println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response
	}
	panic(err.Error()) // GET "/v3/functions": 400 Bad Request { ... }
}

When other errors occur, they are returned unwrapped; for example, if HTTP transport fails, you might receive *url.Error wrapping *net.OpError.

Timeouts

Requests do not time out by default; use context to configure a timeout for a request lifecycle.

Note that if a request is retried, the context timeout does not start over. To set a per-retry timeout, use option.WithRequestTimeout().

// This sets the timeout for the request, including all the retries.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
client.Functions.New(
	ctx,
	bem.FunctionNewParams{
		CreateFunction: bem.CreateFunctionUnionParam{
			OfExtract: &bem.CreateFunctionExtractParam{
				FunctionName: "functionName",
			},
		},
	},
	// This sets the per-retry timeout
	option.WithRequestTimeout(20*time.Second),
)
File uploads

Request parameters that correspond to file uploads in multipart requests are typed as io.Reader. The contents of the io.Reader will by default be sent as a multipart form part with the file name of "anonymous_file" and content-type of "application/octet-stream".

The file name and content-type can be customized by implementing Name() string or ContentType() string on the run-time type of io.Reader. Note that os.File implements Name() string, so a file returned by os.Open will be sent with the file name on disk.

We also provide a helper bem.File(reader io.Reader, filename string, contentType string) which can be used to wrap any io.Reader with the appropriate file name and content type.

Retries

Certain errors will be automatically retried 2 times by default, with a short exponential backoff. We retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors.

You can use the WithMaxRetries option to configure or disable this:

// Configure the default for all requests:
client := bem.NewClient(
	option.WithMaxRetries(0), // default is 2
)

// Override per-request:
client.Functions.New(
	context.TODO(),
	bem.FunctionNewParams{
		CreateFunction: bem.CreateFunctionUnionParam{
			OfExtract: &bem.CreateFunctionExtractParam{
				FunctionName: "functionName",
			},
		},
	},
	option.WithMaxRetries(5),
)
Accessing raw response data (e.g. response headers)

You can access the raw HTTP response data by using the option.WithResponseInto() request option. This is useful when you need to examine response headers, status codes, or other details.

// Create a variable to store the HTTP response
var response *http.Response
functionResponse, err := client.Functions.New(
	context.TODO(),
	bem.FunctionNewParams{
		CreateFunction: bem.CreateFunctionUnionParam{
			OfExtract: &bem.CreateFunctionExtractParam{
				FunctionName: "functionName",
			},
		},
	},
	option.WithResponseInto(&response),
)
if err != nil {
	// handle error
}
fmt.Printf("%+v\n", functionResponse)

fmt.Printf("Status Code: %d\n", response.StatusCode)
fmt.Printf("Headers: %+#v\n", response.Header)
Making custom/undocumented requests

This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, you can use client.Get, client.Post, and other HTTP verbs. RequestOptions on the client, such as retries, will be respected when making these requests.

var (
    // params can be an io.Reader, a []byte, an encoding/json serializable object,
    // or a "…Params" struct defined in this library.
    params map[string]any

    // result can be an []byte, *http.Response, a encoding/json deserializable object,
    // or a model defined in this library.
    result *http.Response
)
err := client.Post(context.Background(), "/unspecified", params, &result)
if err != nil {
    …
}
Undocumented request params

To make requests using undocumented parameters, you may use either the option.WithQuerySet() or the option.WithJSONSet() methods.

params := FooNewParams{
    ID:   "id_xxxx",
    Data: FooNewParamsData{
        FirstName: bem.String("John"),
    },
}
client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe"))
Undocumented response properties

To access undocumented response properties, you may either access the raw JSON of the response as a string with result.JSON.RawJSON(), or get the raw JSON of a particular field on the result with result.JSON.Foo.Raw().

Any fields that are not present on the response struct will be saved and can be accessed by result.JSON.ExtraFields() which returns the extra fields as a map[string]Field.

Middleware

We provide option.WithMiddleware which applies the given middleware to requests.

func Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) {
	// Before the request
	start := time.Now()
	LogReq(req)

	// Forward the request to the next handler
	res, err = next(req)

	// Handle stuff after the request
	end := time.Now()
	LogRes(res, err, start - end)

    return res, err
}

client := bem.NewClient(
	option.WithMiddleware(Logger),
)

When multiple middlewares are provided as variadic arguments, the middlewares are applied left to right. If option.WithMiddleware is given multiple times, for example first in the client then the method, the middleware in the client will run first and the middleware given in the method will run next.

You may also replace the default http.Client with option.WithHTTPClient(client). Only one http client is accepted (this overwrites any previous client) and receives requests after any middleware has been applied.

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
  2. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Contributing

See the contributing documentation.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(b bool) param.Opt[bool]

func BoolPtr

func BoolPtr(v bool) *bool

func DefaultClientOptions

func DefaultClientOptions() []option.RequestOption

DefaultClientOptions read from the environment (BEM_API_KEY, BEM_BASE_URL). This should be used to initialize new clients.

func File

func File(rdr io.Reader, filename string, contentType string) file

func Float

func Float(f float64) param.Opt[float64]

func FloatPtr

func FloatPtr(v float64) *float64

func Int

func Int(i int64) param.Opt[int64]

func IntPtr

func IntPtr(v int64) *int64

func Opt

func Opt[T comparable](v T) param.Opt[T]

func Ptr

func Ptr[T any](v T) *T

func String

func String(s string) param.Opt[string]

func StringPtr

func StringPtr(v string) *string

func Time

func Time(t time.Time) param.Opt[time.Time]

func TimePtr

func TimePtr(v time.Time) *time.Time

Types

type AnyTypeUnion

type AnyTypeUnion struct {
	// This field will be present if the value is a [[]any] instead of an object.
	OfAnyArray []any `json:",inline"`
	// This field will be present if the value is a [string] instead of an object.
	OfString string `json:",inline"`
	// This field will be present if the value is a [float64] instead of an object.
	OfFloat float64 `json:",inline"`
	// This field will be present if the value is a [bool] instead of an object.
	OfBool bool `json:",inline"`
	JSON   struct {
		OfAnyArray respjson.Field
		OfString   respjson.Field
		OfFloat    respjson.Field
		OfBool     respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

AnyTypeUnion contains all possible properties and values from [[]any], [string], [float64], [bool].

Use the methods beginning with 'As' to cast the union to one of its variants.

If the underlying value is not a json object, one of the following properties will be valid: OfAnyArray OfString OfFloat OfBool]

func (AnyTypeUnion) AsAnyArray

func (u AnyTypeUnion) AsAnyArray() (v []any)

func (AnyTypeUnion) AsBool

func (u AnyTypeUnion) AsBool() (v bool)

func (AnyTypeUnion) AsFloat

func (u AnyTypeUnion) AsFloat() (v float64)

func (AnyTypeUnion) AsString

func (u AnyTypeUnion) AsString() (v string)

func (AnyTypeUnion) RawJSON

func (u AnyTypeUnion) RawJSON() string

Returns the unmodified JSON received from the API

func (*AnyTypeUnion) UnmarshalJSON

func (r *AnyTypeUnion) UnmarshalJSON(data []byte) error

type Call

type Call struct {
	// Unique identifier of the call.
	CallID string `json:"callID" api:"required"`
	// The date and time the call was created.
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// Terminal error events of this call. Workflow calls are not atomic — `errors` and
	// `outputs` may both be non-empty if some enclosed function calls succeeded and
	// others failed.
	//
	// Retrieve individual errors via `GET /v3/errors/{eventID}`.
	Errors []ErrorEvent `json:"errors" api:"required"`
	// Terminal non-error outputs of this call: primary events (non-split-collection)
	// that did not trigger any downstream function calls. Workflow calls are not
	// atomic — `outputs` and `errors` may both be non-empty if some enclosed function
	// calls succeeded and others failed.
	//
	// Each element is a polymorphic event object; inspect `eventType` to determine the
	// type. Retrieve individual outputs via `GET /v3/outputs/{eventID}`.
	Outputs []EventUnion `json:"outputs" api:"required"`
	// Hint URL for the full execution trace: `GET /v3/calls/{callID}/trace`.
	TraceURL string `json:"traceUrl" api:"required"`
	// Hint URL for retrieving this call: `GET /v3/calls/{callID}`.
	URL string `json:"url" api:"required"`
	// Your reference ID for this call, propagated from the original request.
	CallReferenceID string `json:"callReferenceID"`
	// The date and time the call finished. Only set once status is `completed` or
	// `failed`.
	FinishedAt time.Time `json:"finishedAt" format:"date-time"`
	// Input to the main function call.
	Input CallInput `json:"input"`
	// Status of call.
	//
	// Any of "pending", "running", "completed", "failed".
	Status CallStatus `json:"status"`
	// Unique identifier of the workflow.
	WorkflowID string `json:"workflowID"`
	// Name of the workflow.
	WorkflowName string `json:"workflowName"`
	// Version number of the workflow.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CallID             respjson.Field
		CreatedAt          respjson.Field
		Errors             respjson.Field
		Outputs            respjson.Field
		TraceURL           respjson.Field
		URL                respjson.Field
		CallReferenceID    respjson.Field
		FinishedAt         respjson.Field
		Input              respjson.Field
		Status             respjson.Field
		WorkflowID         respjson.Field
		WorkflowName       respjson.Field
		WorkflowVersionNum respjson.Field
		ExtraFields        map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A workflow call returned by the V3 API.

Compared to the V2 `Call` model:

  • Terminal outputs are split into `outputs` (non-error events) and `errors` (error events)
  • `callType` and function-scoped fields are removed — V3 calls are always workflow calls
  • The deprecated `functionCalls` field is removed (use `GET /v3/calls/{callID}/trace`)
  • `url` and `traceUrl` hint fields are included for resource discovery

func (Call) RawJSON

func (r Call) RawJSON() string

Returns the unmodified JSON received from the API

func (*Call) UnmarshalJSON

func (r *Call) UnmarshalJSON(data []byte) error

type CallGetResponse

type CallGetResponse struct {
	// A workflow call returned by the V3 API.
	//
	// Compared to the V2 `Call` model:
	//
	//   - Terminal outputs are split into `outputs` (non-error events) and `errors`
	//     (error events)
	//   - `callType` and function-scoped fields are removed — V3 calls are always
	//     workflow calls
	//   - The deprecated `functionCalls` field is removed (use
	//     `GET /v3/calls/{callID}/trace`)
	//   - `url` and `traceUrl` hint fields are included for resource discovery
	Call Call `json:"call"`
	// Error message if the call retrieval failed, or if the call itself failed when
	// using `wait=true`.
	Error string `json:"error"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Call        respjson.Field
		Error       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CallGetResponse) RawJSON

func (r CallGetResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CallGetResponse) UnmarshalJSON

func (r *CallGetResponse) UnmarshalJSON(data []byte) error

type CallGetTraceResponse added in v0.9.0

type CallGetTraceResponse struct {
	// Error message if trace retrieval failed.
	Error string `json:"error"`
	// Full execution DAG of a call as flat arrays. Reconstruct the graph using
	// FunctionCallResponseBase.sourceEventID and each event's functionCallID.
	Trace CallGetTraceResponseTrace `json:"trace"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Error       respjson.Field
		Trace       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Response from `GET /v3/calls/{callID}/trace`.

Contains the full execution DAG as flat arrays of function calls and events. Reconstruct the graph using `FunctionCallResponseBase.sourceEventID` (the event that spawned each function call) and each event's `functionCallID` (the function call that emitted it).

func (CallGetTraceResponse) RawJSON added in v0.9.0

func (r CallGetTraceResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CallGetTraceResponse) UnmarshalJSON added in v0.9.0

func (r *CallGetTraceResponse) UnmarshalJSON(data []byte) error

type CallGetTraceResponseTrace added in v0.9.0

type CallGetTraceResponseTrace struct {
	// All events emitted within this call, polymorphic by eventType.
	Events []any `json:"events" api:"required"`
	// All function calls executed within this call.
	FunctionCalls []CallGetTraceResponseTraceFunctionCall `json:"functionCalls" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Events        respjson.Field
		FunctionCalls respjson.Field
		ExtraFields   map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Full execution DAG of a call as flat arrays. Reconstruct the graph using FunctionCallResponseBase.sourceEventID and each event's functionCallID.

func (CallGetTraceResponseTrace) RawJSON added in v0.9.0

func (r CallGetTraceResponseTrace) RawJSON() string

Returns the unmodified JSON received from the API

func (*CallGetTraceResponseTrace) UnmarshalJSON added in v0.9.0

func (r *CallGetTraceResponseTrace) UnmarshalJSON(data []byte) error

type CallGetTraceResponseTraceFunctionCall added in v0.9.0

type CallGetTraceResponseTraceFunctionCall struct {
	// Unique identifier for this function call
	FunctionCallID string `json:"functionCallID" api:"required"`
	// ID of the function that was called
	FunctionID string `json:"functionID" api:"required"`
	// Name of the function that was called
	FunctionName string `json:"functionName" api:"required"`
	// User-provided reference ID for tracking
	ReferenceID string `json:"referenceID" api:"required"`
	// The date and time this function call started.
	StartedAt time.Time `json:"startedAt" api:"required" format:"date-time"`
	// The status of the action.
	//
	// Any of "pending", "running", "completed", "failed".
	Status string `json:"status" api:"required"`
	// The type of the function.
	//
	// Any of "transform", "extract", "route", "classify", "send", "split", "join",
	// "analyze", "payload_shaping", "enrich", "parse".
	Type FunctionType `json:"type" api:"required"`
	// Array of activity steps for this function call
	Activity []CallGetTraceResponseTraceFunctionCallActivity `json:"activity"`
	// The date and time this function call finished. Absent while still running.
	FinishedAt time.Time `json:"finishedAt" format:"date-time"`
	// Version number of the function
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// The labelled outlet on the upstream node that routed execution to this call.
	// Absent for root calls, unlabelled edges, and pre-migration rows.
	IncomingDestinationName string `json:"incomingDestinationName"`
	// Array of all file inputs with their S3 URLs
	Inputs []CallGetTraceResponseTraceFunctionCallInput `json:"inputs"`
	// Input type for single file input (set when there's exactly one file input)
	InputType string `json:"inputType"`
	// Presigned S3 URL for single file input (set when there's exactly one file input)
	S3URL string `json:"s3URL"`
	// ID of the event that spawned this function call (for DAG reconstruction). Nil
	// for the root function call.
	SourceEventID string `json:"sourceEventID"`
	// ID of the function call that spawned this function call (for DAG reconstruction)
	SourceFunctionCallID string `json:"sourceFunctionCallID"`
	// ID of the workflow call this function call belongs to (top-level execution
	// context)
	WorkflowCallID string `json:"workflowCallID"`
	// Name of the workflow DAG call-site node this function call is executing. Absent
	// for non-workflow calls and pre-migration rows.
	WorkflowNodeName string `json:"workflowNodeName"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		FunctionCallID          respjson.Field
		FunctionID              respjson.Field
		FunctionName            respjson.Field
		ReferenceID             respjson.Field
		StartedAt               respjson.Field
		Status                  respjson.Field
		Type                    respjson.Field
		Activity                respjson.Field
		FinishedAt              respjson.Field
		FunctionVersionNum      respjson.Field
		IncomingDestinationName respjson.Field
		Inputs                  respjson.Field
		InputType               respjson.Field
		S3URL                   respjson.Field
		SourceEventID           respjson.Field
		SourceFunctionCallID    respjson.Field
		WorkflowCallID          respjson.Field
		WorkflowNodeName        respjson.Field
		ExtraFields             map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CallGetTraceResponseTraceFunctionCall) RawJSON added in v0.9.0

Returns the unmodified JSON received from the API

func (*CallGetTraceResponseTraceFunctionCall) UnmarshalJSON added in v0.9.0

func (r *CallGetTraceResponseTraceFunctionCall) UnmarshalJSON(data []byte) error

type CallGetTraceResponseTraceFunctionCallActivity added in v0.9.0

type CallGetTraceResponseTraceFunctionCallActivity struct {
	DisplayName string `json:"displayName"`
	// Any of "pending", "running", "completed", "failed".
	Status string `json:"status"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DisplayName respjson.Field
		Status      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CallGetTraceResponseTraceFunctionCallActivity) RawJSON added in v0.9.0

Returns the unmodified JSON received from the API

func (*CallGetTraceResponseTraceFunctionCallActivity) UnmarshalJSON added in v0.9.0

func (r *CallGetTraceResponseTraceFunctionCallActivity) UnmarshalJSON(data []byte) error

type CallGetTraceResponseTraceFunctionCallInput added in v0.9.0

type CallGetTraceResponseTraceFunctionCallInput struct {
	// Input type of the file
	InputType string `json:"inputType"`
	// Item reference ID for batch inputs
	ItemReferenceID string `json:"itemReferenceID"`
	// Presigned S3 URL for the file input
	S3URL string `json:"s3URL"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		InputType       respjson.Field
		ItemReferenceID respjson.Field
		S3URL           respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CallGetTraceResponseTraceFunctionCallInput) RawJSON added in v0.9.0

Returns the unmodified JSON received from the API

func (*CallGetTraceResponseTraceFunctionCallInput) UnmarshalJSON added in v0.9.0

func (r *CallGetTraceResponseTraceFunctionCallInput) UnmarshalJSON(data []byte) error

type CallInput

type CallInput struct {
	BatchFiles CallInputBatchFiles `json:"batchFiles"`
	SingleFile CallInputSingleFile `json:"singleFile"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		BatchFiles  respjson.Field
		SingleFile  respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Input to the main function call.

func (CallInput) RawJSON

func (r CallInput) RawJSON() string

Returns the unmodified JSON received from the API

func (*CallInput) UnmarshalJSON

func (r *CallInput) UnmarshalJSON(data []byte) error

type CallInputBatchFiles

type CallInputBatchFiles struct {
	Inputs []CallInputBatchFilesInput `json:"inputs"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Inputs      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CallInputBatchFiles) RawJSON

func (r CallInputBatchFiles) RawJSON() string

Returns the unmodified JSON received from the API

func (*CallInputBatchFiles) UnmarshalJSON

func (r *CallInputBatchFiles) UnmarshalJSON(data []byte) error

type CallInputBatchFilesInput

type CallInputBatchFilesInput struct {
	// Input type of the file
	InputType string `json:"inputType"`
	// Item reference ID
	ItemReferenceID string `json:"itemReferenceID"`
	// Presigned S3 URL for the file
	S3URL string `json:"s3URL"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		InputType       respjson.Field
		ItemReferenceID respjson.Field
		S3URL           respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CallInputBatchFilesInput) RawJSON

func (r CallInputBatchFilesInput) RawJSON() string

Returns the unmodified JSON received from the API

func (*CallInputBatchFilesInput) UnmarshalJSON

func (r *CallInputBatchFilesInput) UnmarshalJSON(data []byte) error

type CallInputSingleFile

type CallInputSingleFile struct {
	// Input type of the file
	InputType string `json:"inputType"`
	// Presigned S3 URL for the file
	S3URL string `json:"s3URL"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		InputType   respjson.Field
		S3URL       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CallInputSingleFile) RawJSON

func (r CallInputSingleFile) RawJSON() string

Returns the unmodified JSON received from the API

func (*CallInputSingleFile) UnmarshalJSON

func (r *CallInputSingleFile) UnmarshalJSON(data []byte) error

type CallListParams

type CallListParams struct {
	EndingBefore param.Opt[string] `query:"endingBefore,omitzero" json:"-"`
	Limit        param.Opt[int64]  `query:"limit,omitzero" json:"-"`
	// Case-insensitive substring match against `callReferenceID`.
	ReferenceIDSubstring param.Opt[string] `query:"referenceIDSubstring,omitzero" json:"-"`
	StartingAfter        param.Opt[string] `query:"startingAfter,omitzero" json:"-"`
	CallIDs              []string          `query:"callIDs,omitzero" json:"-"`
	ReferenceIDs         []string          `query:"referenceIDs,omitzero" json:"-"`
	// Any of "asc", "desc".
	SortOrder CallListParamsSortOrder `query:"sortOrder,omitzero" json:"-"`
	// Filter by one or more statuses.
	//
	// Any of "pending", "running", "completed", "failed".
	Statuses      []string `query:"statuses,omitzero" json:"-"`
	WorkflowIDs   []string `query:"workflowIDs,omitzero" json:"-"`
	WorkflowNames []string `query:"workflowNames,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (CallListParams) URLQuery

func (r CallListParams) URLQuery() (v url.Values, err error)

URLQuery serializes CallListParams's query parameters as `url.Values`.

type CallListParamsSortOrder

type CallListParamsSortOrder string
const (
	CallListParamsSortOrderAsc  CallListParamsSortOrder = "asc"
	CallListParamsSortOrderDesc CallListParamsSortOrder = "desc"
)

type CallService

type CallService struct {
	// contains filtered or unexported fields
}

The Calls API provides a unified interface for invoking both **Workflows** and **Functions**.

Use this API when you want to:

- Execute a complete workflow that chains multiple functions together - Call a single function directly without defining a workflow - Submit batch requests with multiple inputs in a single API call - Track execution status using call reference IDs

**Key Difference**: Calls vs Function Calls

  • **Calls API** (`/v3/calls`): High-level API for invoking workflows or functions by name/ID. Supports batch processing and workflow orchestration.
  • **Function Calls API** (`/v3/functions/{functionName}/call`): Direct function invocation with function-type-specific arguments. Better for granular control over individual function calls.

CallService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCallService method instead.

func NewCallService

func NewCallService(opts ...option.RequestOption) (r CallService)

NewCallService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CallService) Get

func (r *CallService) Get(ctx context.Context, callID string, opts ...option.RequestOption) (res *CallGetResponse, err error)

**Retrieve a workflow call by ID.**

Returns the full call object including status, workflow details, terminal outputs, and terminal errors. `outputs` and `errors` are both populated once the call finishes — they are not mutually exclusive (a partially-completed workflow may have both).

## Status

| Status | Description | | ----------- | ----------------------------------------------------------- | | `pending` | Queued, not yet started | | `running` | Currently executing | | `completed` | All enclosed function calls finished without errors | | `failed` | One or more enclosed function calls produced an error event |

Poll this endpoint or configure a webhook subscription to detect completion.

func (*CallService) GetTrace added in v0.9.0

func (r *CallService) GetTrace(ctx context.Context, callID string, opts ...option.RequestOption) (res *CallGetTraceResponse, err error)

**Retrieve the full execution trace of a workflow call.**

Returns all function calls and events emitted during the call as flat arrays. The DAG can be reconstructed using `FunctionCallResponseBase.sourceEventID` (the event that spawned each function call) and each event's `functionCallID` (the function call that emitted it).

## Graph structure

  • A function call with no `sourceEventID` is the root.
  • An event's `functionCallID` points to the function call that emitted it.
  • A function call's `sourceEventID` points to the event that triggered it.
  • `workflowNodeName` identifies the DAG node; `incomingDestinationName` identifies the labelled outlet used to reach this call (absent for unlabelled edges and root calls).

The trace is available as soon as the call exists and grows as execution proceeds.

func (*CallService) List

func (r *CallService) List(ctx context.Context, query CallListParams, opts ...option.RequestOption) (res *pagination.CallsPage[Call], err error)

**List workflow calls with filtering and pagination.**

Returns calls created via `POST /v3/workflows/{workflowName}/call`.

## Filtering

- `callIDs`: Specific call identifiers - `referenceIDs`: Your custom reference IDs - `workflowIDs` / `workflowNames`: Filter by workflow

## Pagination

Use `startingAfter` and `endingBefore` cursors with a default limit of 50.

func (*CallService) ListAutoPaging

**List workflow calls with filtering and pagination.**

Returns calls created via `POST /v3/workflows/{workflowName}/call`.

## Filtering

- `callIDs`: Specific call identifiers - `referenceIDs`: Your custom reference IDs - `workflowIDs` / `workflowNames`: Filter by workflow

## Pagination

Use `startingAfter` and `endingBefore` cursors with a default limit of 50.

type CallStatus

type CallStatus string

Status of call.

const (
	CallStatusPending   CallStatus = "pending"
	CallStatusRunning   CallStatus = "running"
	CallStatusCompleted CallStatus = "completed"
	CallStatusFailed    CallStatus = "failed"
)

type ClassificationListItem added in v0.7.0

type ClassificationListItem struct {
	Name            string                       `json:"name" api:"required"`
	Description     string                       `json:"description"`
	FunctionID      string                       `json:"functionID"`
	FunctionName    string                       `json:"functionName"`
	IsErrorFallback bool                         `json:"isErrorFallback"`
	Origin          ClassificationListItemOrigin `json:"origin"`
	Regex           ClassificationListItemRegex  `json:"regex"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Name            respjson.Field
		Description     respjson.Field
		FunctionID      respjson.Field
		FunctionName    respjson.Field
		IsErrorFallback respjson.Field
		Origin          respjson.Field
		Regex           respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ClassificationListItem) RawJSON added in v0.7.0

func (r ClassificationListItem) RawJSON() string

Returns the unmodified JSON received from the API

func (ClassificationListItem) ToParam added in v0.7.0

ToParam converts this ClassificationListItem to a ClassificationListItemParam.

Warning: the fields of the param type will not be present. ToParam should only be used at the last possible moment before sending a request. Test for this with ClassificationListItemParam.Overrides()

func (*ClassificationListItem) UnmarshalJSON added in v0.7.0

func (r *ClassificationListItem) UnmarshalJSON(data []byte) error

type ClassificationListItemOrigin added in v0.7.0

type ClassificationListItemOrigin struct {
	Email ClassificationListItemOriginEmail `json:"email"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Email       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ClassificationListItemOrigin) RawJSON added in v0.7.0

Returns the unmodified JSON received from the API

func (*ClassificationListItemOrigin) UnmarshalJSON added in v0.7.0

func (r *ClassificationListItemOrigin) UnmarshalJSON(data []byte) error

type ClassificationListItemOriginEmail added in v0.7.0

type ClassificationListItemOriginEmail struct {
	Patterns []string `json:"patterns"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Patterns    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ClassificationListItemOriginEmail) RawJSON added in v0.7.0

Returns the unmodified JSON received from the API

func (*ClassificationListItemOriginEmail) UnmarshalJSON added in v0.7.0

func (r *ClassificationListItemOriginEmail) UnmarshalJSON(data []byte) error

type ClassificationListItemOriginEmailParam added in v0.7.0

type ClassificationListItemOriginEmailParam struct {
	Patterns []string `json:"patterns,omitzero"`
	// contains filtered or unexported fields
}

func (ClassificationListItemOriginEmailParam) MarshalJSON added in v0.7.0

func (r ClassificationListItemOriginEmailParam) MarshalJSON() (data []byte, err error)

func (*ClassificationListItemOriginEmailParam) UnmarshalJSON added in v0.7.0

func (r *ClassificationListItemOriginEmailParam) UnmarshalJSON(data []byte) error

type ClassificationListItemOriginParam added in v0.7.0

type ClassificationListItemOriginParam struct {
	Email ClassificationListItemOriginEmailParam `json:"email,omitzero"`
	// contains filtered or unexported fields
}

func (ClassificationListItemOriginParam) MarshalJSON added in v0.7.0

func (r ClassificationListItemOriginParam) MarshalJSON() (data []byte, err error)

func (*ClassificationListItemOriginParam) UnmarshalJSON added in v0.7.0

func (r *ClassificationListItemOriginParam) UnmarshalJSON(data []byte) error

type ClassificationListItemParam added in v0.7.0

type ClassificationListItemParam struct {
	Name            string                            `json:"name" api:"required"`
	Description     param.Opt[string]                 `json:"description,omitzero"`
	FunctionID      param.Opt[string]                 `json:"functionID,omitzero"`
	FunctionName    param.Opt[string]                 `json:"functionName,omitzero"`
	IsErrorFallback param.Opt[bool]                   `json:"isErrorFallback,omitzero"`
	Origin          ClassificationListItemOriginParam `json:"origin,omitzero"`
	Regex           ClassificationListItemRegexParam  `json:"regex,omitzero"`
	// contains filtered or unexported fields
}

The property Name is required.

func (ClassificationListItemParam) MarshalJSON added in v0.7.0

func (r ClassificationListItemParam) MarshalJSON() (data []byte, err error)

func (*ClassificationListItemParam) UnmarshalJSON added in v0.7.0

func (r *ClassificationListItemParam) UnmarshalJSON(data []byte) error

type ClassificationListItemRegex added in v0.7.0

type ClassificationListItemRegex struct {
	Patterns []string `json:"patterns"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Patterns    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ClassificationListItemRegex) RawJSON added in v0.7.0

func (r ClassificationListItemRegex) RawJSON() string

Returns the unmodified JSON received from the API

func (*ClassificationListItemRegex) UnmarshalJSON added in v0.7.0

func (r *ClassificationListItemRegex) UnmarshalJSON(data []byte) error

type ClassificationListItemRegexParam added in v0.7.0

type ClassificationListItemRegexParam struct {
	Patterns []string `json:"patterns,omitzero"`
	// contains filtered or unexported fields
}

func (ClassificationListItemRegexParam) MarshalJSON added in v0.7.0

func (r ClassificationListItemRegexParam) MarshalJSON() (data []byte, err error)

func (*ClassificationListItemRegexParam) UnmarshalJSON added in v0.7.0

func (r *ClassificationListItemRegexParam) UnmarshalJSON(data []byte) error

type Client

type Client struct {

	// Functions are the core building blocks of data transformation in Bem. Each
	// function type serves a specific purpose:
	//
	//   - **Extract**: Extract structured JSON data from unstructured documents (PDFs,
	//     emails, images, spreadsheets), with optional layout-aware bounding-box
	//     extraction
	//   - **Route**: Direct data to different processing paths based on conditions
	//   - **Split**: Break multi-page documents into individual pages for parallel
	//     processing
	//   - **Join**: Combine outputs from multiple function calls into a single result
	//   - **Parse**: Render documents into a navigable structure of page-aware sections,
	//     named entities, and relationships — designed to be walked by an LLM agent via
	//     the [File System API](/api/v3/file-system) (`POST /v3/fs`). Two toggles, both
	//     `true` by default: `extractEntities` controls per-document entity and
	//     relationship extraction; `linkAcrossDocuments` merges entities into one
	//     canonical record per real-world thing across the environment, populating
	//     cross-document memory.
	//   - **Payload Shaping**: Transform and restructure data using JMESPath expressions
	//   - **Enrich**: Enhance data with semantic search against collections
	//   - **Send**: Deliver workflow outputs to downstream destinations
	//
	// Use these endpoints to create, update, list, and manage your functions.
	Functions FunctionService
	// The Calls API provides a unified interface for invoking both **Workflows** and
	// **Functions**.
	//
	// Use this API when you want to:
	//
	// - Execute a complete workflow that chains multiple functions together
	// - Call a single function directly without defining a workflow
	// - Submit batch requests with multiple inputs in a single API call
	// - Track execution status using call reference IDs
	//
	// **Key Difference**: Calls vs Function Calls
	//
	//   - **Calls API** (`/v3/calls`): High-level API for invoking workflows or
	//     functions by name/ID. Supports batch processing and workflow orchestration.
	//   - **Function Calls API** (`/v3/functions/{functionName}/call`): Direct function
	//     invocation with function-type-specific arguments. Better for granular control
	//     over individual function calls.
	Calls CallService
	// Retrieve terminal error events from workflow calls.
	//
	// Errors are events produced by function steps that failed during processing. A
	// single workflow call may produce multiple error events if several steps fail
	// independently.
	//
	// Errors and outputs from the same call are not mutually exclusive: a
	// partially-completed workflow may have both.
	//
	// Use `GET /v3/errors` to list errors across calls, or `GET /v3/errors/{eventID}`
	// to retrieve a specific error. To get errors scoped to a single call, filter by
	// `callIDs`.
	Errors ErrorService
	// Retrieve terminal non-error output events from workflow calls.
	//
	// Outputs are events produced by successful terminal function steps — steps that
	// completed without errors and did not spawn further downstream function calls. A
	// single workflow call may produce multiple outputs (e.g. from a
	// split-then-transform pipeline).
	//
	// Outputs and errors from the same call are not mutually exclusive: a
	// partially-completed workflow may have both.
	//
	// Use `GET /v3/outputs` to list outputs across calls, or
	// `GET /v3/outputs/{eventID}` to retrieve a specific output. To get outputs scoped
	// to a single call, filter by `callIDs`.
	Outputs OutputService
	// Workflows orchestrate one or more functions into a directed acyclic graph (DAG)
	// for document processing.
	//
	// Use these endpoints to create, update, list, and manage workflows, and to invoke
	// them with file input via `POST /v3/workflows/{workflowName}/call`.
	//
	// The call endpoint accepts files as either multipart form data or JSON with
	// base64-encoded content. In the Bem CLI, use `@path/to/file` inside JSON values
	// to automatically read and encode files:
	//
	// “`
	//
	//	bem workflows call --workflow-name my-workflow \
	//	  --input.single-file '{"inputContent": "@file.pdf", "inputType": "pdf"}' \
	//	  --wait
	//
	// “`
	Workflows WorkflowService
	// Infer JSON Schemas from uploaded documents using AI.
	//
	// Upload a file (PDF, image, spreadsheet, email, etc.) and receive a
	// general-purpose JSON Schema that captures the document's structure. The inferred
	// schema can be used directly as the `outputSchema` when creating Extract
	// functions.
	//
	// The schema is designed to be broadly applicable to documents of the same type,
	// not just the specific file uploaded.
	InferSchema InferSchemaService
	// Collections are named groups of embedded items used by Enrich functions for
	// semantic search.
	//
	// Each collection is referenced by a `collectionName`, which supports dot notation
	// for hierarchical paths (e.g. `customers.premium.vip`). Names must contain only
	// letters, digits, underscores, and dots, and each segment must start with a
	// letter or underscore.
	//
	// ## Items
	//
	// Items carry either a string or a JSON object in their `data` field. When items
	// are added or updated, their `data` is embedded asynchronously —
	// `POST /v3/collections/items` and `PUT /v3/collections/items` return immediately
	// with a `pending` status and an `eventID` that can be correlated with webhook
	// notifications once processing completes.
	//
	// ## Listing and hierarchy
	//
	// Use `GET /v3/collections` with `parentCollectionName` to list collections under
	// a path, or `collectionNameSearch` for a case-insensitive substring match.
	// `GET /v3/collections/items` retrieves a specific collection's items; pass
	// `includeSubcollections=true` to fold in items from all descendant collections.
	//
	// ## Token counting
	//
	// Use `POST /v3/collections/token-count` to check whether texts fit within the
	// embedding model's 8,192-token-per-text limit before submitting them for
	// embedding.
	Collections CollectionService
	// Submit training corrections for `extract`, `classify`, and `join` events.
	//
	// Feedback is event-centric — each correction is attached to an event by its
	// `eventID`, and the server resolves the correct underlying storage (extract/join
	// transformations or classify route events) from the event's function type.
	//
	// Split and enrich function types do not support feedback.
	Events EventService
	// Manage the webhook signing secret used to authenticate outbound webhook
	// deliveries.
	//
	// When a signing secret is active, every webhook delivery includes a
	// `bem-signature` header in the format `t={unix_timestamp},v1={hex_hmac_sha256}`.
	// The signature covers `{timestamp}.{raw_request_body}` and can be verified using
	// HMAC-SHA256 with your secret.
	//
	// Rotate the secret at any time with `POST /v3/webhook-secret`. To avoid downtime
	// during rotation, update your verification logic to accept both the old and new
	// secret briefly before revoking the old one.
	WebhookSecret WebhookSecretService
	// Trigger and retrieve evaluations for completed transformations.
	//
	// Evaluations run asynchronously and score each transformation's output against
	// the function's schema for confidence, per-field hallucination detection, and
	// relevance. Evaluations are supported for `extract`, `transform`, `analyze`, and
	// `join` events.
	//
	// ## Lifecycle
	//
	//  1. **Trigger** — `POST /v3/eval` queues jobs for a batch of transformation IDs
	//     and returns immediately with `queued` / `skipped` counts plus per-ID errors.
	//  2. **Poll** — `POST /v3/eval/results` (body) or `GET /v3/eval/results` (query)
	//     returns the current state of each requested transformation, partitioned into
	//     `results` (completed), `pending` (still running), and `failed` (terminal
	//     failures or unknown transformation IDs).
	//
	// Up to 100 transformation IDs may be submitted per request.
	Eval EvalService
	// Unix-shell-style nav over parsed documents and the cross-doc memory store.
	//
	// `POST /v3/fs` is a single op-driven endpoint designed for LLM agents and
	// programmatic consumers that want to walk a corpus the way they'd walk a
	// filesystem.
	//
	// ## Doc-level ops (every parsed document)
	//
	// - `ls` — list parsed documents with rich per-doc metadata.
	// - `cat` — read one doc's parse JSON, sliced (`range`) or projected (`select`).
	// - `head` — first N sections of one doc.
	// - `grep` — substring or regex search; `scope`, `path`, `countOnly` available.
	// - `stat` — metadata only (page/section/entity counts, timestamps).
	//
	// ## Memory-level ops (require `linkAcrossDocuments: true` on the parse function)
	//
	// - `find` — list canonical entities across the corpus.
	// - `open` — entity + mentions.
	// - `xref` — for one entity, sections across docs that mention it (with content).
	//
	// Memory ops return an empty list with a `hint` when no docs in this environment
	// have been memory-linked.
	//
	// ## Pagination
	//
	// List ops paginate by cursor — pass the previous response's `nextCursor` back as
	// `cursor`; `hasMore: false` signals the last page. Same idiom as `/v3/calls` and
	// `/v3/outputs`.
	Fs FService
	// contains filtered or unexported fields
}

Client creates a struct with services and top level methods that help with interacting with the bem API. You should not instantiate this client directly, and instead use the NewClient method instead.

func NewClient

func NewClient(opts ...option.RequestOption) (r Client)

NewClient generates a new client with the default option read from the environment (BEM_API_KEY, BEM_BASE_URL). The option passed in as arguments are applied after these default arguments, and all option will be passed down to the services and requests that this client makes.

func (*Client) Delete

func (r *Client) Delete(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Delete makes a DELETE request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Execute

func (r *Client) Execute(ctx context.Context, method string, path string, params any, res any, opts ...option.RequestOption) error

Execute makes a request with the given context, method, URL, request params, response, and request options. This is useful for hitting undocumented endpoints while retaining the base URL, auth, retries, and other options from the client.

If a byte slice or an io.Reader is supplied to params, it will be used as-is for the request body.

The params is by default serialized into the body using encoding/json. If your type implements a MarshalJSON function, it will be used instead to serialize the request. If a URLQuery method is implemented, the returned url.Values will be used as query strings to the url.

If your params struct uses param.Field, you must provide either [MarshalJSON], [URLQuery], and/or [MarshalForm] functions. It is undefined behavior to use a struct uses param.Field without specifying how it is serialized.

Any "…Params" object defined in this library can be used as the request argument. Note that 'path' arguments will not be forwarded into the url.

The response body will be deserialized into the res variable, depending on its type:

  • A pointer to a *http.Response is populated by the raw response.
  • A pointer to a byte array will be populated with the contents of the request body.
  • A pointer to any other type uses this library's default JSON decoding, which respects UnmarshalJSON if it is defined on the type.
  • A nil value will not read the response body.

For even greater flexibility, see option.WithResponseInto and option.WithResponseBodyInto.

func (*Client) Get

func (r *Client) Get(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Get makes a GET request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Patch

func (r *Client) Patch(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Patch makes a PATCH request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Post

func (r *Client) Post(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Post makes a POST request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Put

func (r *Client) Put(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Put makes a PUT request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

type CollectionCountTokensParams added in v0.9.0

type CollectionCountTokensParams struct {
	// One or more texts to tokenize.
	Texts []string `json:"texts,omitzero" api:"required"`
	// contains filtered or unexported fields
}

func (CollectionCountTokensParams) MarshalJSON added in v0.9.0

func (r CollectionCountTokensParams) MarshalJSON() (data []byte, err error)

func (*CollectionCountTokensParams) UnmarshalJSON added in v0.9.0

func (r *CollectionCountTokensParams) UnmarshalJSON(data []byte) error

type CollectionCountTokensResponse added in v0.9.0

type CollectionCountTokensResponse struct {
	// Maximum tokens allowed per text by the embedding model.
	MaxTokenLimit int64 `json:"max_token_limit"`
	// Number of input texts that exceed `max_token_limit`.
	TextsExceedingLimit int64 `json:"texts_exceeding_limit"`
	// Per-text tokenization results in the same order as the request.
	TokenCounts []CollectionCountTokensResponseTokenCount `json:"token_counts"`
	// Sum of `token_count` across all texts.
	TotalTokens int64 `json:"total_tokens"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		MaxTokenLimit       respjson.Field
		TextsExceedingLimit respjson.Field
		TokenCounts         respjson.Field
		TotalTokens         respjson.Field
		ExtraFields         map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Response for the token count endpoint.

func (CollectionCountTokensResponse) RawJSON added in v0.9.0

Returns the unmodified JSON received from the API

func (*CollectionCountTokensResponse) UnmarshalJSON added in v0.9.0

func (r *CollectionCountTokensResponse) UnmarshalJSON(data []byte) error

type CollectionCountTokensResponseTokenCount added in v0.9.0

type CollectionCountTokensResponseTokenCount struct {
	// Character count of the input text.
	CharCount int64 `json:"char_count"`
	// True if `token_count` exceeds the embedding model's per-text limit.
	ExceedsLimit bool `json:"exceeds_limit"`
	// Zero-based position of this entry in the request `texts` array.
	Index int64 `json:"index"`
	// Number of tokens produced by the tokenizer.
	TokenCount int64 `json:"token_count"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CharCount    respjson.Field
		ExceedsLimit respjson.Field
		Index        respjson.Field
		TokenCount   respjson.Field
		ExtraFields  map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Per-text token count result.

func (CollectionCountTokensResponseTokenCount) RawJSON added in v0.9.0

Returns the unmodified JSON received from the API

func (*CollectionCountTokensResponseTokenCount) UnmarshalJSON added in v0.9.0

func (r *CollectionCountTokensResponseTokenCount) UnmarshalJSON(data []byte) error

type CollectionDeleteParams added in v0.9.0

type CollectionDeleteParams struct {
	// The name/path of the collection to delete. Must use only letters, digits,
	// underscores, and dots. Each segment must start with a letter or underscore.
	CollectionName string `query:"collectionName" api:"required" json:"-"`
	// contains filtered or unexported fields
}

func (CollectionDeleteParams) URLQuery added in v0.9.0

func (r CollectionDeleteParams) URLQuery() (v url.Values, err error)

URLQuery serializes CollectionDeleteParams's query parameters as `url.Values`.

type CollectionItemAddParams added in v0.9.0

type CollectionItemAddParams struct {
	// The name/path of the collection. Must use only letters, digits, underscores, and
	// dots. Each segment must start with a letter or underscore.
	CollectionName string `json:"collectionName" api:"required"`
	// Array of items to add (maximum 100 items per request)
	Items []CollectionItemAddParamsItem `json:"items,omitzero" api:"required"`
	// contains filtered or unexported fields
}

func (CollectionItemAddParams) MarshalJSON added in v0.9.0

func (r CollectionItemAddParams) MarshalJSON() (data []byte, err error)

func (*CollectionItemAddParams) UnmarshalJSON added in v0.9.0

func (r *CollectionItemAddParams) UnmarshalJSON(data []byte) error

type CollectionItemAddParamsItem added in v0.9.0

type CollectionItemAddParamsItem struct {
	// The data to be embedded and stored (string or JSON object)
	Data any `json:"data,omitzero" api:"required"`
	// contains filtered or unexported fields
}

Data for creating a new item in a collection

The property Data is required.

func (CollectionItemAddParamsItem) MarshalJSON added in v0.9.0

func (r CollectionItemAddParamsItem) MarshalJSON() (data []byte, err error)

func (*CollectionItemAddParamsItem) UnmarshalJSON added in v0.9.0

func (r *CollectionItemAddParamsItem) UnmarshalJSON(data []byte) error

type CollectionItemAddResponse added in v0.9.0

type CollectionItemAddResponse struct {
	// Event ID for tracking this operation. Use this to correlate with webhook
	// notifications.
	EventID string `json:"eventID" api:"required"`
	// Status message
	Message string `json:"message" api:"required"`
	// Processing status
	//
	// Any of "pending".
	Status CollectionItemAddResponseStatus `json:"status" api:"required"`
	// Number of new items added (only present in synchronous mode, deprecated)
	AddedCount int64 `json:"addedCount"`
	// Array of items that were added (only present in synchronous mode, deprecated)
	Items []CollectionItemAddResponseItem `json:"items"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EventID     respjson.Field
		Message     respjson.Field
		Status      respjson.Field
		AddedCount  respjson.Field
		Items       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Response after queuing items for async processing

func (CollectionItemAddResponse) RawJSON added in v0.9.0

func (r CollectionItemAddResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CollectionItemAddResponse) UnmarshalJSON added in v0.9.0

func (r *CollectionItemAddResponse) UnmarshalJSON(data []byte) error

type CollectionItemAddResponseItem added in v0.9.0

type CollectionItemAddResponseItem struct {
	// Unique identifier for the item
	CollectionItemID string `json:"collectionItemID" api:"required"`
	// When the item was created
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// The data stored in this item
	Data any `json:"data" api:"required"`
	// When the item was last updated
	UpdatedAt time.Time `json:"updatedAt" api:"required" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionItemID respjson.Field
		CreatedAt        respjson.Field
		Data             respjson.Field
		UpdatedAt        respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A single item in a collection

func (CollectionItemAddResponseItem) RawJSON added in v0.9.0

Returns the unmodified JSON received from the API

func (*CollectionItemAddResponseItem) UnmarshalJSON added in v0.9.0

func (r *CollectionItemAddResponseItem) UnmarshalJSON(data []byte) error

type CollectionItemAddResponseStatus added in v0.9.0

type CollectionItemAddResponseStatus string

Processing status

const (
	CollectionItemAddResponseStatusPending CollectionItemAddResponseStatus = "pending"
)

type CollectionItemDeleteParams added in v0.9.0

type CollectionItemDeleteParams struct {
	// The unique identifier of the item to delete
	CollectionItemID string `query:"collectionItemID" api:"required" json:"-"`
	// The name/path of the collection. Must use only letters, digits, underscores, and
	// dots. Each segment must start with a letter or underscore.
	CollectionName string `query:"collectionName" api:"required" json:"-"`
	// contains filtered or unexported fields
}

func (CollectionItemDeleteParams) URLQuery added in v0.9.0

func (r CollectionItemDeleteParams) URLQuery() (v url.Values, err error)

URLQuery serializes CollectionItemDeleteParams's query parameters as `url.Values`.

type CollectionItemGetParams added in v0.9.0

type CollectionItemGetParams struct {
	// The name/path of the collection. Must use only letters, digits, underscores, and
	// dots. Each segment must start with a letter or underscore.
	CollectionName string `query:"collectionName" api:"required" json:"-"`
	// When true, includes items from all subcollections under the specified collection
	// path. For example, querying "customers" with this flag will return items from
	// "customers", "customers.premium", "customers.premium.vip", etc.
	IncludeSubcollections param.Opt[bool] `query:"includeSubcollections,omitzero" json:"-"`
	// Number of items per page
	Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
	// Page number for pagination
	Page param.Opt[int64] `query:"page,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (CollectionItemGetParams) URLQuery added in v0.9.0

func (r CollectionItemGetParams) URLQuery() (v url.Values, err error)

URLQuery serializes CollectionItemGetParams's query parameters as `url.Values`.

type CollectionItemGetResponse added in v0.9.0

type CollectionItemGetResponse struct {
	// Unique identifier for the collection
	CollectionID string `json:"collectionID" api:"required"`
	// The collection name/path. Only letters, digits, underscores, and dots are
	// allowed.
	CollectionName string `json:"collectionName" api:"required"`
	// When the collection was created
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// Number of items in the collection
	ItemCount int64 `json:"itemCount" api:"required"`
	// List of items in the collection (when fetching collection details)
	Items []CollectionItemGetResponseItem `json:"items"`
	// Number of items per page
	Limit int64 `json:"limit"`
	// Current page number
	Page int64 `json:"page"`
	// Total number of pages
	TotalPages int64 `json:"totalPages"`
	// When the collection was last updated
	UpdatedAt time.Time `json:"updatedAt" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionID   respjson.Field
		CollectionName respjson.Field
		CreatedAt      respjson.Field
		ItemCount      respjson.Field
		Items          respjson.Field
		Limit          respjson.Field
		Page           respjson.Field
		TotalPages     respjson.Field
		UpdatedAt      respjson.Field
		ExtraFields    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Collection details

func (CollectionItemGetResponse) RawJSON added in v0.9.0

func (r CollectionItemGetResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CollectionItemGetResponse) UnmarshalJSON added in v0.9.0

func (r *CollectionItemGetResponse) UnmarshalJSON(data []byte) error

type CollectionItemGetResponseItem added in v0.9.0

type CollectionItemGetResponseItem struct {
	// Unique identifier for the item
	CollectionItemID string `json:"collectionItemID" api:"required"`
	// When the item was created
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// The data stored in this item
	Data any `json:"data" api:"required"`
	// When the item was last updated
	UpdatedAt time.Time `json:"updatedAt" api:"required" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionItemID respjson.Field
		CreatedAt        respjson.Field
		Data             respjson.Field
		UpdatedAt        respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A single item in a collection

func (CollectionItemGetResponseItem) RawJSON added in v0.9.0

Returns the unmodified JSON received from the API

func (*CollectionItemGetResponseItem) UnmarshalJSON added in v0.9.0

func (r *CollectionItemGetResponseItem) UnmarshalJSON(data []byte) error

type CollectionItemService added in v0.9.0

type CollectionItemService struct {
	// contains filtered or unexported fields
}

Collections are named groups of embedded items used by Enrich functions for semantic search.

Each collection is referenced by a `collectionName`, which supports dot notation for hierarchical paths (e.g. `customers.premium.vip`). Names must contain only letters, digits, underscores, and dots, and each segment must start with a letter or underscore.

## Items

Items carry either a string or a JSON object in their `data` field. When items are added or updated, their `data` is embedded asynchronously — `POST /v3/collections/items` and `PUT /v3/collections/items` return immediately with a `pending` status and an `eventID` that can be correlated with webhook notifications once processing completes.

## Listing and hierarchy

Use `GET /v3/collections` with `parentCollectionName` to list collections under a path, or `collectionNameSearch` for a case-insensitive substring match. `GET /v3/collections/items` retrieves a specific collection's items; pass `includeSubcollections=true` to fold in items from all descendant collections.

## Token counting

Use `POST /v3/collections/token-count` to check whether texts fit within the embedding model's 8,192-token-per-text limit before submitting them for embedding.

CollectionItemService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCollectionItemService method instead.

func NewCollectionItemService added in v0.9.0

func NewCollectionItemService(opts ...option.RequestOption) (r CollectionItemService)

NewCollectionItemService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CollectionItemService) Add added in v0.9.0

Add new items to a Collection

func (*CollectionItemService) Delete added in v0.9.0

Delete an item from a Collection

func (*CollectionItemService) Get added in v0.9.0

Get a Collection

func (*CollectionItemService) Update added in v0.9.0

Update existing items in a Collection

type CollectionItemUpdateParams added in v0.9.0

type CollectionItemUpdateParams struct {
	// The name/path of the collection. Must use only letters, digits, underscores, and
	// dots. Each segment must start with a letter or underscore.
	CollectionName string `json:"collectionName" api:"required"`
	// Array of items to update (maximum 100 items per request)
	Items []CollectionItemUpdateParamsItem `json:"items,omitzero" api:"required"`
	// contains filtered or unexported fields
}

func (CollectionItemUpdateParams) MarshalJSON added in v0.9.0

func (r CollectionItemUpdateParams) MarshalJSON() (data []byte, err error)

func (*CollectionItemUpdateParams) UnmarshalJSON added in v0.9.0

func (r *CollectionItemUpdateParams) UnmarshalJSON(data []byte) error

type CollectionItemUpdateParamsItem added in v0.9.0

type CollectionItemUpdateParamsItem struct {
	// Unique identifier for the item to update
	CollectionItemID string `json:"collectionItemID" api:"required"`
	// The updated data to be embedded and stored (string or JSON object)
	Data any `json:"data,omitzero" api:"required"`
	// contains filtered or unexported fields
}

Data for updating an existing item in a collection

The properties CollectionItemID, Data are required.

func (CollectionItemUpdateParamsItem) MarshalJSON added in v0.9.0

func (r CollectionItemUpdateParamsItem) MarshalJSON() (data []byte, err error)

func (*CollectionItemUpdateParamsItem) UnmarshalJSON added in v0.9.0

func (r *CollectionItemUpdateParamsItem) UnmarshalJSON(data []byte) error

type CollectionItemUpdateResponse added in v0.9.0

type CollectionItemUpdateResponse struct {
	// Event ID for tracking this operation. Use this to correlate with webhook
	// notifications.
	EventID string `json:"eventID" api:"required"`
	// Status message
	Message string `json:"message" api:"required"`
	// Processing status
	//
	// Any of "pending".
	Status CollectionItemUpdateResponseStatus `json:"status" api:"required"`
	// Array of items that were updated (only present in synchronous mode, deprecated)
	Items []CollectionItemUpdateResponseItem `json:"items"`
	// Number of items updated (only present in synchronous mode, deprecated)
	UpdatedCount int64 `json:"updatedCount"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EventID      respjson.Field
		Message      respjson.Field
		Status       respjson.Field
		Items        respjson.Field
		UpdatedCount respjson.Field
		ExtraFields  map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Response after queuing items for async update

func (CollectionItemUpdateResponse) RawJSON added in v0.9.0

Returns the unmodified JSON received from the API

func (*CollectionItemUpdateResponse) UnmarshalJSON added in v0.9.0

func (r *CollectionItemUpdateResponse) UnmarshalJSON(data []byte) error

type CollectionItemUpdateResponseItem added in v0.9.0

type CollectionItemUpdateResponseItem struct {
	// Unique identifier for the item
	CollectionItemID string `json:"collectionItemID" api:"required"`
	// When the item was created
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// The data stored in this item
	Data any `json:"data" api:"required"`
	// When the item was last updated
	UpdatedAt time.Time `json:"updatedAt" api:"required" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionItemID respjson.Field
		CreatedAt        respjson.Field
		Data             respjson.Field
		UpdatedAt        respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A single item in a collection

func (CollectionItemUpdateResponseItem) RawJSON added in v0.9.0

Returns the unmodified JSON received from the API

func (*CollectionItemUpdateResponseItem) UnmarshalJSON added in v0.9.0

func (r *CollectionItemUpdateResponseItem) UnmarshalJSON(data []byte) error

type CollectionItemUpdateResponseStatus added in v0.9.0

type CollectionItemUpdateResponseStatus string

Processing status

const (
	CollectionItemUpdateResponseStatusPending CollectionItemUpdateResponseStatus = "pending"
)

type CollectionListParams added in v0.9.0

type CollectionListParams struct {
	// Optional substring search filter for collection names (case-insensitive). For
	// example, "premium" will match "customers.premium", "products.premium", etc.
	CollectionNameSearch param.Opt[string] `query:"collectionNameSearch,omitzero" json:"-"`
	// Number of collections per page
	Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
	// Page number for pagination
	Page param.Opt[int64] `query:"page,omitzero" json:"-"`
	// Optional filter to list only collections under a specific parent collection
	// path. For example, "customers" will return "customers", "customers.premium",
	// "customers.premium.vip", etc.
	ParentCollectionName param.Opt[string] `query:"parentCollectionName,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (CollectionListParams) URLQuery added in v0.9.0

func (r CollectionListParams) URLQuery() (v url.Values, err error)

URLQuery serializes CollectionListParams's query parameters as `url.Values`.

type CollectionListResponse added in v0.9.0

type CollectionListResponse struct {
	// List of collections
	Collections []CollectionListResponseCollection `json:"collections" api:"required"`
	// Number of collections per page
	Limit int64 `json:"limit" api:"required"`
	// Current page number
	Page int64 `json:"page" api:"required"`
	// Total number of collections
	TotalCount int64 `json:"totalCount" api:"required"`
	// Total number of pages
	TotalPages int64 `json:"totalPages" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Collections respjson.Field
		Limit       respjson.Field
		Page        respjson.Field
		TotalCount  respjson.Field
		TotalPages  respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Response for listing collections

func (CollectionListResponse) RawJSON added in v0.9.0

func (r CollectionListResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CollectionListResponse) UnmarshalJSON added in v0.9.0

func (r *CollectionListResponse) UnmarshalJSON(data []byte) error

type CollectionListResponseCollection added in v0.9.0

type CollectionListResponseCollection struct {
	// Unique identifier for the collection
	CollectionID string `json:"collectionID" api:"required"`
	// The collection name/path. Only letters, digits, underscores, and dots are
	// allowed.
	CollectionName string `json:"collectionName" api:"required"`
	// When the collection was created
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// Number of items in the collection
	ItemCount int64 `json:"itemCount" api:"required"`
	// When the collection was last updated
	UpdatedAt time.Time `json:"updatedAt" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionID   respjson.Field
		CollectionName respjson.Field
		CreatedAt      respjson.Field
		ItemCount      respjson.Field
		UpdatedAt      respjson.Field
		ExtraFields    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Collection metadata without items

func (CollectionListResponseCollection) RawJSON added in v0.9.0

Returns the unmodified JSON received from the API

func (*CollectionListResponseCollection) UnmarshalJSON added in v0.9.0

func (r *CollectionListResponseCollection) UnmarshalJSON(data []byte) error

type CollectionNewParams added in v0.9.0

type CollectionNewParams struct {
	// Unique name/path for the collection. Supports dot notation for hierarchical
	// paths.
	//
	//   - Only letters (a-z, A-Z), digits (0-9), underscores (\_), and dots (.) are
	//     allowed
	//   - Each segment (between dots) must start with a letter or underscore (not a
	//     digit)
	//   - Segments cannot consist only of digits
	//   - Each segment must be 1-256 characters
	//   - No leading, trailing, or consecutive dots
	//   - Invalid names are rejected with a 400 Bad Request error
	//
	// **Valid Examples:**
	//
	// - 'product_catalog'
	// - 'orders.line_items.sku'
	// - 'customer_data'
	// - 'price_v2'
	//
	// **Invalid Examples:**
	//
	// - 'product-catalog' (contains hyphen)
	// - '123items' (starts with digit)
	// - 'items..data' (consecutive dots)
	// - 'order#123' (contains invalid character #)
	CollectionName string `json:"collectionName" api:"required"`
	// contains filtered or unexported fields
}

func (CollectionNewParams) MarshalJSON added in v0.9.0

func (r CollectionNewParams) MarshalJSON() (data []byte, err error)

func (*CollectionNewParams) UnmarshalJSON added in v0.9.0

func (r *CollectionNewParams) UnmarshalJSON(data []byte) error

type CollectionNewResponse added in v0.9.0

type CollectionNewResponse struct {
	// Unique identifier for the collection
	CollectionID string `json:"collectionID" api:"required"`
	// The collection name/path. Only letters, digits, underscores, and dots are
	// allowed.
	CollectionName string `json:"collectionName" api:"required"`
	// When the collection was created
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// Number of items in the collection
	ItemCount int64 `json:"itemCount" api:"required"`
	// List of items in the collection (when fetching collection details)
	Items []CollectionNewResponseItem `json:"items"`
	// Number of items per page
	Limit int64 `json:"limit"`
	// Current page number
	Page int64 `json:"page"`
	// Total number of pages
	TotalPages int64 `json:"totalPages"`
	// When the collection was last updated
	UpdatedAt time.Time `json:"updatedAt" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionID   respjson.Field
		CollectionName respjson.Field
		CreatedAt      respjson.Field
		ItemCount      respjson.Field
		Items          respjson.Field
		Limit          respjson.Field
		Page           respjson.Field
		TotalPages     respjson.Field
		UpdatedAt      respjson.Field
		ExtraFields    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Collection details

func (CollectionNewResponse) RawJSON added in v0.9.0

func (r CollectionNewResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CollectionNewResponse) UnmarshalJSON added in v0.9.0

func (r *CollectionNewResponse) UnmarshalJSON(data []byte) error

type CollectionNewResponseItem added in v0.9.0

type CollectionNewResponseItem struct {
	// Unique identifier for the item
	CollectionItemID string `json:"collectionItemID" api:"required"`
	// When the item was created
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// The data stored in this item
	Data any `json:"data" api:"required"`
	// When the item was last updated
	UpdatedAt time.Time `json:"updatedAt" api:"required" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionItemID respjson.Field
		CreatedAt        respjson.Field
		Data             respjson.Field
		UpdatedAt        respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A single item in a collection

func (CollectionNewResponseItem) RawJSON added in v0.9.0

func (r CollectionNewResponseItem) RawJSON() string

Returns the unmodified JSON received from the API

func (*CollectionNewResponseItem) UnmarshalJSON added in v0.9.0

func (r *CollectionNewResponseItem) UnmarshalJSON(data []byte) error

type CollectionService added in v0.9.0

type CollectionService struct {

	// Collections are named groups of embedded items used by Enrich functions for
	// semantic search.
	//
	// Each collection is referenced by a `collectionName`, which supports dot notation
	// for hierarchical paths (e.g. `customers.premium.vip`). Names must contain only
	// letters, digits, underscores, and dots, and each segment must start with a
	// letter or underscore.
	//
	// ## Items
	//
	// Items carry either a string or a JSON object in their `data` field. When items
	// are added or updated, their `data` is embedded asynchronously —
	// `POST /v3/collections/items` and `PUT /v3/collections/items` return immediately
	// with a `pending` status and an `eventID` that can be correlated with webhook
	// notifications once processing completes.
	//
	// ## Listing and hierarchy
	//
	// Use `GET /v3/collections` with `parentCollectionName` to list collections under
	// a path, or `collectionNameSearch` for a case-insensitive substring match.
	// `GET /v3/collections/items` retrieves a specific collection's items; pass
	// `includeSubcollections=true` to fold in items from all descendant collections.
	//
	// ## Token counting
	//
	// Use `POST /v3/collections/token-count` to check whether texts fit within the
	// embedding model's 8,192-token-per-text limit before submitting them for
	// embedding.
	Items CollectionItemService
	// contains filtered or unexported fields
}

Collections are named groups of embedded items used by Enrich functions for semantic search.

Each collection is referenced by a `collectionName`, which supports dot notation for hierarchical paths (e.g. `customers.premium.vip`). Names must contain only letters, digits, underscores, and dots, and each segment must start with a letter or underscore.

## Items

Items carry either a string or a JSON object in their `data` field. When items are added or updated, their `data` is embedded asynchronously — `POST /v3/collections/items` and `PUT /v3/collections/items` return immediately with a `pending` status and an `eventID` that can be correlated with webhook notifications once processing completes.

## Listing and hierarchy

Use `GET /v3/collections` with `parentCollectionName` to list collections under a path, or `collectionNameSearch` for a case-insensitive substring match. `GET /v3/collections/items` retrieves a specific collection's items; pass `includeSubcollections=true` to fold in items from all descendant collections.

## Token counting

Use `POST /v3/collections/token-count` to check whether texts fit within the embedding model's 8,192-token-per-text limit before submitting them for embedding.

CollectionService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCollectionService method instead.

func NewCollectionService added in v0.9.0

func NewCollectionService(opts ...option.RequestOption) (r CollectionService)

NewCollectionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CollectionService) CountTokens added in v0.9.0

Count the number of tokens in the provided texts using the BGE M3 tokenizer. This is useful for checking if texts will fit within the embedding model's token limit (8,192 tokens per text) before sending them for embedding.

func (*CollectionService) Delete added in v0.9.0

Delete a Collection

func (*CollectionService) List added in v0.9.0

List Collections

func (*CollectionService) New added in v0.9.0

Create a Collection

type CreateFunctionClassifyParam added in v0.7.0

type CreateFunctionClassifyParam struct {
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Description of classifier. Can be used to provide additional context on
	// classifier's purpose and expected inputs.
	Description param.Opt[string] `json:"description,omitzero"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// List of classifications a classify function can produce. Shares the underlying
	// route list shape.
	Classifications []ClassificationListItemParam `json:"classifications,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "classify".
	Type constant.Classify `json:"type" default:"classify"`
	// contains filtered or unexported fields
}

V3 wire form of the classify function create payload.

The properties FunctionName, Type are required.

func (CreateFunctionClassifyParam) MarshalJSON added in v0.7.0

func (r CreateFunctionClassifyParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionClassifyParam) UnmarshalJSON added in v0.7.0

func (r *CreateFunctionClassifyParam) UnmarshalJSON(data []byte) error

type CreateFunctionEnrichParam

type CreateFunctionEnrichParam struct {
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Configuration for enrich function with semantic search steps.
	//
	// **How Enrich Functions Work:**
	//
	// Enrich functions use semantic search to augment JSON data with relevant
	// information from collections. They take JSON input (typically from a transform
	// function), extract specified fields, perform vector-based semantic search
	// against collections, and inject the results back into the data.
	//
	// **Input Requirements:**
	//
	// - Must receive JSON input (typically uploaded to S3 from a previous function)
	// - Can be chained after transform or other functions that produce JSON output
	//
	// **Example Use Cases:**
	//
	// - Match product descriptions to SKU codes from a product catalog
	// - Enrich customer data with account information
	// - Link order line items to inventory records
	//
	// **Configuration:**
	//
	// - Define one or more enrichment steps
	// - Each step extracts values, searches a collection, and injects results
	// - Steps are executed sequentially
	Config EnrichConfigParam `json:"config,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "enrich".
	Type constant.Enrich `json:"type" default:"enrich"`
	// contains filtered or unexported fields
}

The properties FunctionName, Type are required.

func (CreateFunctionEnrichParam) MarshalJSON

func (r CreateFunctionEnrichParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionEnrichParam) UnmarshalJSON

func (r *CreateFunctionEnrichParam) UnmarshalJSON(data []byte) error

type CreateFunctionExtractParam added in v0.2.0

type CreateFunctionExtractParam struct {
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Whether bounding box extraction is enabled. Applies to vision input types (pdf,
	// png, jpeg, heic, heif, webp) that dispatch through the analyze path. When true,
	// the function returns the document regions (page, coordinates) from which each
	// field was extracted. Enabling this automatically configures the function to use
	// the bounding box model. Disabling resets to the default.
	EnableBoundingBoxes param.Opt[bool] `json:"enableBoundingBoxes,omitzero"`
	// Name of output schema object.
	OutputSchemaName param.Opt[string] `json:"outputSchemaName,omitzero"`
	// Reducing the risk of the model stopping early on long documents. Trade-off:
	// Increases total latency. Compatible with `enableBoundingBoxes`.
	PreCount param.Opt[bool] `json:"preCount,omitzero"`
	// Whether tabular chunking is enabled. When true, tables in CSV/Excel files are
	// processed in row batches rather than all at once.
	TabularChunkingEnabled param.Opt[bool] `json:"tabularChunkingEnabled,omitzero"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "extract".
	Type constant.Extract `json:"type" default:"extract"`
	// contains filtered or unexported fields
}

The properties FunctionName, Type are required.

func (CreateFunctionExtractParam) MarshalJSON added in v0.2.0

func (r CreateFunctionExtractParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionExtractParam) UnmarshalJSON added in v0.2.0

func (r *CreateFunctionExtractParam) UnmarshalJSON(data []byte) error

type CreateFunctionJoinParam

type CreateFunctionJoinParam struct {
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Description of join function.
	Description param.Opt[string] `json:"description,omitzero"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Name of output schema object.
	OutputSchemaName param.Opt[string] `json:"outputSchemaName,omitzero"`
	// The type of join to perform.
	//
	// Any of "standard".
	JoinType string `json:"joinType,omitzero"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "join".
	Type constant.Join `json:"type" default:"join"`
	// contains filtered or unexported fields
}

The properties FunctionName, Type are required.

func (CreateFunctionJoinParam) MarshalJSON

func (r CreateFunctionJoinParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionJoinParam) UnmarshalJSON

func (r *CreateFunctionJoinParam) UnmarshalJSON(data []byte) error

type CreateFunctionParseParam added in v0.10.0

type CreateFunctionParseParam struct {
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Per-version configuration for a Parse function.
	//
	// Parse renders document pages (PDF, image) via vision LLM and emits structured
	// JSON. The two toggles below independently control entity extraction (a per-call
	// output concern) and cross-document memory linking (an environment-wide concern).
	ParseConfig CreateFunctionParseParseConfigParam `json:"parseConfig,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "parse".
	Type constant.Parse `json:"type" default:"parse"`
	// contains filtered or unexported fields
}

The properties FunctionName, Type are required.

func (CreateFunctionParseParam) MarshalJSON added in v0.10.0

func (r CreateFunctionParseParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionParseParam) UnmarshalJSON added in v0.10.0

func (r *CreateFunctionParseParam) UnmarshalJSON(data []byte) error

type CreateFunctionParseParseConfigParam added in v0.10.0

type CreateFunctionParseParseConfigParam struct {
	// When true, extract named entities (people, organizations, products, studies,
	// identifiers, etc.) and the relationships between them, and dedupe by canonical
	// name within the document. When false, only `sections[]` is extracted;
	// `entities[]` and `relationships[]` come back empty in the parse output. Defaults
	// to true.
	ExtractEntities param.Opt[bool] `json:"extractEntities,omitzero"`
	// When true, link this document's entities to entities seen in earlier documents
	// in this environment, building one canonical record per real-world thing across
	// the corpus. Visible in the Memory tab and queryable via `POST /v3/fs` (op=find /
	// open / xref). Doesn't change this call's parse output. Requires
	// `extractEntities=true`. Defaults to true.
	LinkAcrossDocuments param.Opt[bool] `json:"linkAcrossDocuments,omitzero"`
	// Optional JSONSchema. When provided, each chunk performs schema-guided
	// extraction. When absent, chunks perform open-ended discovery and return
	// sections, entities, and relationships per the discovery schema.
	Schema any `json:"schema,omitzero"`
	// contains filtered or unexported fields
}

Per-version configuration for a Parse function.

Parse renders document pages (PDF, image) via vision LLM and emits structured JSON. The two toggles below independently control entity extraction (a per-call output concern) and cross-document memory linking (an environment-wide concern).

func (CreateFunctionParseParseConfigParam) MarshalJSON added in v0.10.0

func (r CreateFunctionParseParseConfigParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionParseParseConfigParam) UnmarshalJSON added in v0.10.0

func (r *CreateFunctionParseParseConfigParam) UnmarshalJSON(data []byte) error

type CreateFunctionPayloadShapingParam

type CreateFunctionPayloadShapingParam struct {
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// JMESPath expression that defines how to transform and customize the input
	// payload structure. Payload shaping allows you to extract, reshape, and
	// reorganize data from complex input payloads into a simplified, standardized
	// output format. Use JMESPath syntax to select specific fields, perform
	// calculations, and create new data structures tailored to your needs.
	ShapingSchema param.Opt[string] `json:"shapingSchema,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "payload_shaping".
	Type constant.PayloadShaping `json:"type" default:"payload_shaping"`
	// contains filtered or unexported fields
}

The properties FunctionName, Type are required.

func (CreateFunctionPayloadShapingParam) MarshalJSON

func (r CreateFunctionPayloadShapingParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionPayloadShapingParam) UnmarshalJSON

func (r *CreateFunctionPayloadShapingParam) UnmarshalJSON(data []byte) error

type CreateFunctionSendParam

type CreateFunctionSendParam struct {
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Google Drive folder ID. Required when destinationType is google_drive. Managed
	// via Paragon OAuth.
	GoogleDriveFolderID param.Opt[string] `json:"googleDriveFolderId,omitzero"`
	// S3 bucket to upload the payload to. Required when destinationType is s3.
	S3Bucket param.Opt[string] `json:"s3Bucket,omitzero"`
	// Optional S3 key prefix (folder path).
	S3Prefix param.Opt[string] `json:"s3Prefix,omitzero"`
	// Whether to sign webhook deliveries with an HMAC-SHA256 `bem-signature` header.
	// Defaults to `true` when omitted — signing is on by default for new send
	// functions. Set explicitly to `false` to disable.
	WebhookSigningEnabled param.Opt[bool] `json:"webhookSigningEnabled,omitzero"`
	// Webhook URL to POST the payload to. Required when destinationType is webhook.
	WebhookURL param.Opt[string] `json:"webhookUrl,omitzero"`
	// Destination type for a Send function.
	//
	// Any of "webhook", "s3", "google_drive".
	DestinationType string `json:"destinationType,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "send".
	Type constant.Send `json:"type" default:"send"`
	// contains filtered or unexported fields
}

The properties FunctionName, Type are required.

func (CreateFunctionSendParam) MarshalJSON

func (r CreateFunctionSendParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionSendParam) UnmarshalJSON

func (r *CreateFunctionSendParam) UnmarshalJSON(data []byte) error

type CreateFunctionSplitParam

type CreateFunctionSplitParam struct {
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName             param.Opt[string]                               `json:"displayName,omitzero"`
	PrintPageSplitConfig    CreateFunctionSplitPrintPageSplitConfigParam    `json:"printPageSplitConfig,omitzero"`
	SemanticPageSplitConfig CreateFunctionSplitSemanticPageSplitConfigParam `json:"semanticPageSplitConfig,omitzero"`
	// Any of "print_page", "semantic_page".
	SplitType string `json:"splitType,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "split".
	Type constant.Split `json:"type" default:"split"`
	// contains filtered or unexported fields
}

The properties FunctionName, Type are required.

func (CreateFunctionSplitParam) MarshalJSON

func (r CreateFunctionSplitParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionSplitParam) UnmarshalJSON

func (r *CreateFunctionSplitParam) UnmarshalJSON(data []byte) error

type CreateFunctionSplitPrintPageSplitConfigParam

type CreateFunctionSplitPrintPageSplitConfigParam struct {
	NextFunctionID   param.Opt[string] `json:"nextFunctionID,omitzero"`
	NextFunctionName param.Opt[string] `json:"nextFunctionName,omitzero"`
	// contains filtered or unexported fields
}

func (CreateFunctionSplitPrintPageSplitConfigParam) MarshalJSON

func (r CreateFunctionSplitPrintPageSplitConfigParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionSplitPrintPageSplitConfigParam) UnmarshalJSON

func (r *CreateFunctionSplitPrintPageSplitConfigParam) UnmarshalJSON(data []byte) error

type CreateFunctionSplitSemanticPageSplitConfigParam

type CreateFunctionSplitSemanticPageSplitConfigParam struct {
	ItemClasses []SplitFunctionSemanticPageItemClassParam `json:"itemClasses,omitzero"`
	// contains filtered or unexported fields
}

func (CreateFunctionSplitSemanticPageSplitConfigParam) MarshalJSON

func (r CreateFunctionSplitSemanticPageSplitConfigParam) MarshalJSON() (data []byte, err error)

func (*CreateFunctionSplitSemanticPageSplitConfigParam) UnmarshalJSON

type CreateFunctionUnionParam

type CreateFunctionUnionParam struct {
	OfExtract        *CreateFunctionExtractParam        `json:",omitzero,inline"`
	OfClassify       *CreateFunctionClassifyParam       `json:",omitzero,inline"`
	OfSend           *CreateFunctionSendParam           `json:",omitzero,inline"`
	OfSplit          *CreateFunctionSplitParam          `json:",omitzero,inline"`
	OfJoin           *CreateFunctionJoinParam           `json:",omitzero,inline"`
	OfPayloadShaping *CreateFunctionPayloadShapingParam `json:",omitzero,inline"`
	OfEnrich         *CreateFunctionEnrichParam         `json:",omitzero,inline"`
	OfParse          *CreateFunctionParseParam          `json:",omitzero,inline"`
	// contains filtered or unexported fields
}

Only one field can be non-zero.

Use param.IsOmitted to confirm if a field is set.

func CreateFunctionParamOfClassify added in v0.7.0

func CreateFunctionParamOfClassify(functionName string) CreateFunctionUnionParam

func CreateFunctionParamOfEnrich

func CreateFunctionParamOfEnrich(functionName string) CreateFunctionUnionParam

func CreateFunctionParamOfExtract added in v0.2.0

func CreateFunctionParamOfExtract(functionName string) CreateFunctionUnionParam

func CreateFunctionParamOfJoin

func CreateFunctionParamOfJoin(functionName string) CreateFunctionUnionParam

func CreateFunctionParamOfParse added in v0.10.0

func CreateFunctionParamOfParse(functionName string) CreateFunctionUnionParam

func CreateFunctionParamOfPayloadShaping

func CreateFunctionParamOfPayloadShaping(functionName string) CreateFunctionUnionParam

func CreateFunctionParamOfSend

func CreateFunctionParamOfSend(functionName string) CreateFunctionUnionParam

func CreateFunctionParamOfSplit

func CreateFunctionParamOfSplit(functionName string) CreateFunctionUnionParam

func (CreateFunctionUnionParam) MarshalJSON

func (u CreateFunctionUnionParam) MarshalJSON() ([]byte, error)

func (*CreateFunctionUnionParam) UnmarshalJSON

func (u *CreateFunctionUnionParam) UnmarshalJSON(data []byte) error

type EnrichConfig

type EnrichConfig struct {
	// Array of enrichment steps to execute sequentially
	Steps []EnrichStep `json:"steps" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Steps       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Configuration for enrich function with semantic search steps.

**How Enrich Functions Work:**

Enrich functions use semantic search to augment JSON data with relevant information from collections. They take JSON input (typically from a transform function), extract specified fields, perform vector-based semantic search against collections, and inject the results back into the data.

**Input Requirements:**

- Must receive JSON input (typically uploaded to S3 from a previous function) - Can be chained after transform or other functions that produce JSON output

**Example Use Cases:**

- Match product descriptions to SKU codes from a product catalog - Enrich customer data with account information - Link order line items to inventory records

**Configuration:**

- Define one or more enrichment steps - Each step extracts values, searches a collection, and injects results - Steps are executed sequentially

func (EnrichConfig) RawJSON

func (r EnrichConfig) RawJSON() string

Returns the unmodified JSON received from the API

func (EnrichConfig) ToParam

func (r EnrichConfig) ToParam() EnrichConfigParam

ToParam converts this EnrichConfig to a EnrichConfigParam.

Warning: the fields of the param type will not be present. ToParam should only be used at the last possible moment before sending a request. Test for this with EnrichConfigParam.Overrides()

func (*EnrichConfig) UnmarshalJSON

func (r *EnrichConfig) UnmarshalJSON(data []byte) error

type EnrichConfigParam

type EnrichConfigParam struct {
	// Array of enrichment steps to execute sequentially
	Steps []EnrichStepParam `json:"steps,omitzero" api:"required"`
	// contains filtered or unexported fields
}

Configuration for enrich function with semantic search steps.

**How Enrich Functions Work:**

Enrich functions use semantic search to augment JSON data with relevant information from collections. They take JSON input (typically from a transform function), extract specified fields, perform vector-based semantic search against collections, and inject the results back into the data.

**Input Requirements:**

- Must receive JSON input (typically uploaded to S3 from a previous function) - Can be chained after transform or other functions that produce JSON output

**Example Use Cases:**

- Match product descriptions to SKU codes from a product catalog - Enrich customer data with account information - Link order line items to inventory records

**Configuration:**

- Define one or more enrichment steps - Each step extracts values, searches a collection, and injects results - Steps are executed sequentially

The property Steps is required.

func (EnrichConfigParam) MarshalJSON

func (r EnrichConfigParam) MarshalJSON() (data []byte, err error)

func (*EnrichConfigParam) UnmarshalJSON

func (r *EnrichConfigParam) UnmarshalJSON(data []byte) error

type EnrichStep

type EnrichStep struct {
	// Name of the collection to search against. The collection must exist and contain
	// items. Supports hierarchical paths when used with `includeSubcollections`.
	CollectionName string `json:"collectionName" api:"required"`
	// JMESPath expression to extract source data for semantic search. Can extract
	// single values or arrays. All extracted values will be used for search.
	SourceField string `json:"sourceField" api:"required"`
	// Field path where enriched results should be placed. Use simple field names
	// (e.g., "enriched_products"). Results are always injected as an array (list),
	// regardless of topK value.
	TargetField string `json:"targetField" api:"required"`
	// Whether to include cosine distance scores in results. Cosine distance ranges
	// from 0.0 (perfect match) to 2.0 (completely dissimilar). Lower scores indicate
	// better semantic similarity.
	//
	// When enabled, each result includes a `cosine_distance` field (semantic mode) or
	// a `hybrid_score` field (hybrid mode).
	IncludeScore bool `json:"includeScore"`
	// When true, searches all collections under the hierarchical path. For example,
	// "customers" will match "customers", "customers.premium", etc.
	IncludeSubcollections bool `json:"includeSubcollections"`
	// Maximum cosine distance threshold for filtering results (default: 0.6). Results
	// with cosine distance above this threshold are excluded.
	//
	// **Only applies to `semantic` and `hybrid` search modes.** Exact search does not
	// use cosine distance and ignores this setting.
	//
	// Cosine distance ranges from 0.0 (identical) to 2.0 (opposite):
	//
	// - 0.0 - 0.3: Very similar (strict threshold, high-quality matches only)
	// - 0.3 - 0.6: Reasonably similar (moderate threshold)
	// - 0.6 - 1.0: Loosely related (lenient threshold)
	// - > 1.0: Rarely useful — allows nearly unrelated results
	//
	// For most semantic search use cases, good matches typically fall in the 0.2 - 0.5
	// range.
	ScoreThreshold float64 `json:"scoreThreshold"`
	// Search mode to use for enrichment (default: "semantic").
	//
	// **semantic**: Vector similarity search using dense embeddings. Best for finding
	// conceptually similar items.
	//
	// - Use for: Product descriptions, natural language content
	// - Example: "red sports car" matches "crimson convertible automobile"
	//
	// **exact**: Exact keyword matching using PostgreSQL text search. Best for exact
	// identifiers.
	//
	// - Use for: SKU numbers, routing numbers, account IDs, exact tags
	// - Example: "SKU-12345" only matches items containing that exact text
	//
	// **hybrid**: Combined search using 20% semantic + 80% sparse embeddings
	// (keyword-based).
	//
	// - Use for: Tags, categories, partial identifiers
	// - Example: Balances semantic meaning with exact keyword matching
	//
	// Any of "semantic", "exact", "hybrid".
	SearchMode EnrichStepSearchMode `json:"searchMode"`
	// Number of top matching results to return per query (default: 1). Results are
	// always returned as an array (list) and automatically sorted by cosine distance
	// (best match = lowest distance first).
	//
	// - 1: Returns array with single best match: `[{...}]`
	// - > 1: Returns array with multiple matches: `[{...}, {...}, ...]`
	TopK int64 `json:"topK"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionName        respjson.Field
		SourceField           respjson.Field
		TargetField           respjson.Field
		IncludeScore          respjson.Field
		IncludeSubcollections respjson.Field
		ScoreThreshold        respjson.Field
		SearchMode            respjson.Field
		TopK                  respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Single enrichment step configuration.

**Process Flow:**

  1. Extract values from `sourceField` using JMESPath
  2. Perform search against the specified collection (semantic, exact, or hybrid based on `searchMode`)
  3. Return top K matches sorted by relevance (best match first)
  4. Inject results into `targetField`

**Search Modes:**

  • `semantic` (default): Vector similarity search - best for natural language and conceptual matching
  • `exact`: Exact keyword matching - best for SKU numbers, IDs, routing numbers
  • `hybrid`: Combined semantic + keyword search - best for tags and categories

**Result Format:**

  • Results are always returned as an array (list), regardless of `topK` value
  • Array is sorted by relevance (best match first)
  • Each result contains `data` (the collection item) and optionally `cosineDistance`
  • With `topK=1`: Returns array with single best match: `[{data: {...}, cosineDistance: 0.15}]`
  • With `topK>1`: Returns array with multiple matches sorted by relevance

func (EnrichStep) RawJSON

func (r EnrichStep) RawJSON() string

Returns the unmodified JSON received from the API

func (EnrichStep) ToParam

func (r EnrichStep) ToParam() EnrichStepParam

ToParam converts this EnrichStep to a EnrichStepParam.

Warning: the fields of the param type will not be present. ToParam should only be used at the last possible moment before sending a request. Test for this with EnrichStepParam.Overrides()

func (*EnrichStep) UnmarshalJSON

func (r *EnrichStep) UnmarshalJSON(data []byte) error

type EnrichStepParam

type EnrichStepParam struct {
	// Name of the collection to search against. The collection must exist and contain
	// items. Supports hierarchical paths when used with `includeSubcollections`.
	CollectionName string `json:"collectionName" api:"required"`
	// JMESPath expression to extract source data for semantic search. Can extract
	// single values or arrays. All extracted values will be used for search.
	SourceField string `json:"sourceField" api:"required"`
	// Field path where enriched results should be placed. Use simple field names
	// (e.g., "enriched_products"). Results are always injected as an array (list),
	// regardless of topK value.
	TargetField string `json:"targetField" api:"required"`
	// Whether to include cosine distance scores in results. Cosine distance ranges
	// from 0.0 (perfect match) to 2.0 (completely dissimilar). Lower scores indicate
	// better semantic similarity.
	//
	// When enabled, each result includes a `cosine_distance` field (semantic mode) or
	// a `hybrid_score` field (hybrid mode).
	IncludeScore param.Opt[bool] `json:"includeScore,omitzero"`
	// When true, searches all collections under the hierarchical path. For example,
	// "customers" will match "customers", "customers.premium", etc.
	IncludeSubcollections param.Opt[bool] `json:"includeSubcollections,omitzero"`
	// Maximum cosine distance threshold for filtering results (default: 0.6). Results
	// with cosine distance above this threshold are excluded.
	//
	// **Only applies to `semantic` and `hybrid` search modes.** Exact search does not
	// use cosine distance and ignores this setting.
	//
	// Cosine distance ranges from 0.0 (identical) to 2.0 (opposite):
	//
	// - 0.0 - 0.3: Very similar (strict threshold, high-quality matches only)
	// - 0.3 - 0.6: Reasonably similar (moderate threshold)
	// - 0.6 - 1.0: Loosely related (lenient threshold)
	// - > 1.0: Rarely useful — allows nearly unrelated results
	//
	// For most semantic search use cases, good matches typically fall in the 0.2 - 0.5
	// range.
	ScoreThreshold param.Opt[float64] `json:"scoreThreshold,omitzero"`
	// Number of top matching results to return per query (default: 1). Results are
	// always returned as an array (list) and automatically sorted by cosine distance
	// (best match = lowest distance first).
	//
	// - 1: Returns array with single best match: `[{...}]`
	// - > 1: Returns array with multiple matches: `[{...}, {...}, ...]`
	TopK param.Opt[int64] `json:"topK,omitzero"`
	// Search mode to use for enrichment (default: "semantic").
	//
	// **semantic**: Vector similarity search using dense embeddings. Best for finding
	// conceptually similar items.
	//
	// - Use for: Product descriptions, natural language content
	// - Example: "red sports car" matches "crimson convertible automobile"
	//
	// **exact**: Exact keyword matching using PostgreSQL text search. Best for exact
	// identifiers.
	//
	// - Use for: SKU numbers, routing numbers, account IDs, exact tags
	// - Example: "SKU-12345" only matches items containing that exact text
	//
	// **hybrid**: Combined search using 20% semantic + 80% sparse embeddings
	// (keyword-based).
	//
	// - Use for: Tags, categories, partial identifiers
	// - Example: Balances semantic meaning with exact keyword matching
	//
	// Any of "semantic", "exact", "hybrid".
	SearchMode EnrichStepSearchMode `json:"searchMode,omitzero"`
	// contains filtered or unexported fields
}

Single enrichment step configuration.

**Process Flow:**

  1. Extract values from `sourceField` using JMESPath
  2. Perform search against the specified collection (semantic, exact, or hybrid based on `searchMode`)
  3. Return top K matches sorted by relevance (best match first)
  4. Inject results into `targetField`

**Search Modes:**

  • `semantic` (default): Vector similarity search - best for natural language and conceptual matching
  • `exact`: Exact keyword matching - best for SKU numbers, IDs, routing numbers
  • `hybrid`: Combined semantic + keyword search - best for tags and categories

**Result Format:**

  • Results are always returned as an array (list), regardless of `topK` value
  • Array is sorted by relevance (best match first)
  • Each result contains `data` (the collection item) and optionally `cosineDistance`
  • With `topK=1`: Returns array with single best match: `[{data: {...}, cosineDistance: 0.15}]`
  • With `topK>1`: Returns array with multiple matches sorted by relevance

The properties CollectionName, SourceField, TargetField are required.

func (EnrichStepParam) MarshalJSON

func (r EnrichStepParam) MarshalJSON() (data []byte, err error)

func (*EnrichStepParam) UnmarshalJSON

func (r *EnrichStepParam) UnmarshalJSON(data []byte) error

type EnrichStepSearchMode

type EnrichStepSearchMode string

Search mode to use for enrichment (default: "semantic").

**semantic**: Vector similarity search using dense embeddings. Best for finding conceptually similar items.

- Use for: Product descriptions, natural language content - Example: "red sports car" matches "crimson convertible automobile"

**exact**: Exact keyword matching using PostgreSQL text search. Best for exact identifiers.

- Use for: SKU numbers, routing numbers, account IDs, exact tags - Example: "SKU-12345" only matches items containing that exact text

**hybrid**: Combined search using 20% semantic + 80% sparse embeddings (keyword-based).

- Use for: Tags, categories, partial identifiers - Example: Balances semantic meaning with exact keyword matching

const (
	EnrichStepSearchModeSemantic EnrichStepSearchMode = "semantic"
	EnrichStepSearchModeExact    EnrichStepSearchMode = "exact"
	EnrichStepSearchModeHybrid   EnrichStepSearchMode = "hybrid"
)

type Error

type Error = apierror.Error

type ErrorEvent

type ErrorEvent struct {
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// Unique identifier of function that this event is associated with.
	FunctionID string `json:"functionID" api:"required"`
	// Unique name of function that this event is associated with.
	FunctionName string `json:"functionName" api:"required"`
	// Error message.
	Message string `json:"message" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID string `json:"referenceID" api:"required"`
	// Unique identifier of workflow call that this event is associated with.
	CallID string `json:"callID"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Any of "error".
	EventType ErrorEventEventType `json:"eventType"`
	// Unique identifier of function call that this event is associated with.
	FunctionCallID string `json:"functionCallID"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// Version number of function that this event is associated with.
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// The inbound email that triggered this event.
	InboundEmail InboundEmailEvent  `json:"inboundEmail"`
	Metadata     ErrorEventMetadata `json:"metadata"`
	// Unique identifier of workflow that this event is associated with.
	WorkflowID string `json:"workflowID"`
	// Name of workflow that this event is associated with.
	WorkflowName string `json:"workflowName"`
	// Version number of workflow that this event is associated with.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		Message               respjson.Field
		ReferenceID           respjson.Field
		CallID                respjson.Field
		CreatedAt             respjson.Field
		EventType             respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		InboundEmail          respjson.Field
		Metadata              respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ErrorEvent) RawJSON

func (r ErrorEvent) RawJSON() string

Returns the unmodified JSON received from the API

func (*ErrorEvent) UnmarshalJSON

func (r *ErrorEvent) UnmarshalJSON(data []byte) error

type ErrorEventEventType

type ErrorEventEventType string
const (
	ErrorEventEventTypeError ErrorEventEventType = "error"
)

type ErrorEventMetadata

type ErrorEventMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ErrorEventMetadata) RawJSON

func (r ErrorEventMetadata) RawJSON() string

Returns the unmodified JSON received from the API

func (*ErrorEventMetadata) UnmarshalJSON

func (r *ErrorEventMetadata) UnmarshalJSON(data []byte) error

type ErrorGetResponse

type ErrorGetResponse struct {
	// The error event.
	Error ErrorEvent `json:"error" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Error       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ErrorGetResponse) RawJSON

func (r ErrorGetResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*ErrorGetResponse) UnmarshalJSON

func (r *ErrorGetResponse) UnmarshalJSON(data []byte) error

type ErrorListParams

type ErrorListParams struct {
	EndingBefore param.Opt[string] `query:"endingBefore,omitzero" json:"-"`
	Limit        param.Opt[int64]  `query:"limit,omitzero" json:"-"`
	// Case-insensitive substring match against `referenceID`.
	ReferenceIDSubstring param.Opt[string] `query:"referenceIDSubstring,omitzero" json:"-"`
	StartingAfter        param.Opt[string] `query:"startingAfter,omitzero" json:"-"`
	// Filter to errors from specific calls.
	CallIDs       []string `query:"callIDs,omitzero" json:"-"`
	FunctionIDs   []string `query:"functionIDs,omitzero" json:"-"`
	FunctionNames []string `query:"functionNames,omitzero" json:"-"`
	ReferenceIDs  []string `query:"referenceIDs,omitzero" json:"-"`
	// Any of "asc", "desc".
	SortOrder     ErrorListParamsSortOrder `query:"sortOrder,omitzero" json:"-"`
	WorkflowIDs   []string                 `query:"workflowIDs,omitzero" json:"-"`
	WorkflowNames []string                 `query:"workflowNames,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (ErrorListParams) URLQuery

func (r ErrorListParams) URLQuery() (v url.Values, err error)

URLQuery serializes ErrorListParams's query parameters as `url.Values`.

type ErrorListParamsSortOrder

type ErrorListParamsSortOrder string
const (
	ErrorListParamsSortOrderAsc  ErrorListParamsSortOrder = "asc"
	ErrorListParamsSortOrderDesc ErrorListParamsSortOrder = "desc"
)

type ErrorService

type ErrorService struct {
	// contains filtered or unexported fields
}

Retrieve terminal error events from workflow calls.

Errors are events produced by function steps that failed during processing. A single workflow call may produce multiple error events if several steps fail independently.

Errors and outputs from the same call are not mutually exclusive: a partially-completed workflow may have both.

Use `GET /v3/errors` to list errors across calls, or `GET /v3/errors/{eventID}` to retrieve a specific error. To get errors scoped to a single call, filter by `callIDs`.

ErrorService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewErrorService method instead.

func NewErrorService

func NewErrorService(opts ...option.RequestOption) (r ErrorService)

NewErrorService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ErrorService) Get

func (r *ErrorService) Get(ctx context.Context, eventID string, opts ...option.RequestOption) (res *ErrorGetResponse, err error)

**Retrieve a single error event by ID.**

Returns `404` if the event does not exist or if it is not an error event (use `GET /v3/outputs/{eventID}` for non-error events).

func (*ErrorService) List

**List terminal error events.**

Returns error events produced by failed function calls within workflow executions. Non-error output events are excluded; use `GET /v3/outputs` to retrieve those.

## Filtering

Filter by call, workflow, function, or reference ID. Multiple filters are ANDed together.

func (*ErrorService) ListAutoPaging

**List terminal error events.**

Returns error events produced by failed function calls within workflow executions. Non-error output events are excluded; use `GET /v3/outputs` to retrieve those.

## Filtering

Filter by call, workflow, function, or reference ID. Multiple filters are ANDed together.

type EvalResultFetchResultsParams added in v0.10.0

type EvalResultFetchResultsParams struct {
	// Transformation IDs to fetch results for. Up to 100 per request.
	TransformationIDs []string `json:"transformationIDs,omitzero" api:"required"`
	// Optional evaluation version filter.
	EvaluationVersion param.Opt[string] `json:"evaluationVersion,omitzero"`
	// contains filtered or unexported fields
}

func (EvalResultFetchResultsParams) MarshalJSON added in v0.10.0

func (r EvalResultFetchResultsParams) MarshalJSON() (data []byte, err error)

func (*EvalResultFetchResultsParams) UnmarshalJSON added in v0.10.0

func (r *EvalResultFetchResultsParams) UnmarshalJSON(data []byte) error

type EvalResultFetchResultsResponse added in v0.10.0

type EvalResultFetchResultsResponse struct {
	// Completed evaluation results, keyed by transformation ID.
	//
	// A transformation appears here only if its evaluation completed successfully.
	// Still-running evaluations appear in `pending`; failed evaluations appear in
	// `failed`.
	Results any `json:"results" api:"required"`
	// Reserved map of transformation ID to error message for validation failures on
	// the request itself. Populated only in edge cases.
	Errors any `json:"errors"`
	// Transformations whose evaluation failed or was not found.
	Failed []EvalResultFetchResultsResponseFailed `json:"failed"`
	// Transformations whose evaluation is still running.
	Pending []EvalResultFetchResultsResponsePending `json:"pending"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Results     respjson.Field
		Errors      respjson.Field
		Failed      respjson.Field
		Pending     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Batched response containing the evaluation state for every requested transformation ID, partitioned into completed `results`, still-running `pending`, and terminal `failed` groups.

func (EvalResultFetchResultsResponse) RawJSON added in v0.10.0

Returns the unmodified JSON received from the API

func (*EvalResultFetchResultsResponse) UnmarshalJSON added in v0.10.0

func (r *EvalResultFetchResultsResponse) UnmarshalJSON(data []byte) error

type EvalResultFetchResultsResponseFailed added in v0.10.0

type EvalResultFetchResultsResponseFailed struct {
	// Server timestamp associated with the failure.
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// Human-readable failure reason.
	ErrorMessage     string `json:"errorMessage" api:"required"`
	TransformationID string `json:"transformationId" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CreatedAt        respjson.Field
		ErrorMessage     respjson.Field
		TransformationID respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A transformation whose evaluation failed or was not found.

func (EvalResultFetchResultsResponseFailed) RawJSON added in v0.10.0

Returns the unmodified JSON received from the API

func (*EvalResultFetchResultsResponseFailed) UnmarshalJSON added in v0.10.0

func (r *EvalResultFetchResultsResponseFailed) UnmarshalJSON(data []byte) error

type EvalResultFetchResultsResponsePending added in v0.10.0

type EvalResultFetchResultsResponsePending struct {
	// Server timestamp when the evaluation was queued.
	CreatedAt        time.Time `json:"createdAt" api:"required" format:"date-time"`
	TransformationID string    `json:"transformationId" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CreatedAt        respjson.Field
		TransformationID respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A transformation whose evaluation is still running.

func (EvalResultFetchResultsResponsePending) RawJSON added in v0.10.0

Returns the unmodified JSON received from the API

func (*EvalResultFetchResultsResponsePending) UnmarshalJSON added in v0.10.0

func (r *EvalResultFetchResultsResponsePending) UnmarshalJSON(data []byte) error

type EvalResultGetResultsParams added in v0.10.0

type EvalResultGetResultsParams struct {
	// Comma-separated list of transformation IDs to fetch results for. Between 1 and
	// 100 IDs per request.
	TransformationIDs string `query:"transformationIDs" api:"required" json:"-"`
	// Optional evaluation version filter.
	EvaluationVersion param.Opt[string] `query:"evaluationVersion,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (EvalResultGetResultsParams) URLQuery added in v0.10.0

func (r EvalResultGetResultsParams) URLQuery() (v url.Values, err error)

URLQuery serializes EvalResultGetResultsParams's query parameters as `url.Values`.

type EvalResultGetResultsResponse added in v0.10.0

type EvalResultGetResultsResponse struct {
	// Completed evaluation results, keyed by transformation ID.
	//
	// A transformation appears here only if its evaluation completed successfully.
	// Still-running evaluations appear in `pending`; failed evaluations appear in
	// `failed`.
	Results any `json:"results" api:"required"`
	// Reserved map of transformation ID to error message for validation failures on
	// the request itself. Populated only in edge cases.
	Errors any `json:"errors"`
	// Transformations whose evaluation failed or was not found.
	Failed []EvalResultGetResultsResponseFailed `json:"failed"`
	// Transformations whose evaluation is still running.
	Pending []EvalResultGetResultsResponsePending `json:"pending"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Results     respjson.Field
		Errors      respjson.Field
		Failed      respjson.Field
		Pending     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Batched response containing the evaluation state for every requested transformation ID, partitioned into completed `results`, still-running `pending`, and terminal `failed` groups.

func (EvalResultGetResultsResponse) RawJSON added in v0.10.0

Returns the unmodified JSON received from the API

func (*EvalResultGetResultsResponse) UnmarshalJSON added in v0.10.0

func (r *EvalResultGetResultsResponse) UnmarshalJSON(data []byte) error

type EvalResultGetResultsResponseFailed added in v0.10.0

type EvalResultGetResultsResponseFailed struct {
	// Server timestamp associated with the failure.
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// Human-readable failure reason.
	ErrorMessage     string `json:"errorMessage" api:"required"`
	TransformationID string `json:"transformationId" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CreatedAt        respjson.Field
		ErrorMessage     respjson.Field
		TransformationID respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A transformation whose evaluation failed or was not found.

func (EvalResultGetResultsResponseFailed) RawJSON added in v0.10.0

Returns the unmodified JSON received from the API

func (*EvalResultGetResultsResponseFailed) UnmarshalJSON added in v0.10.0

func (r *EvalResultGetResultsResponseFailed) UnmarshalJSON(data []byte) error

type EvalResultGetResultsResponsePending added in v0.10.0

type EvalResultGetResultsResponsePending struct {
	// Server timestamp when the evaluation was queued.
	CreatedAt        time.Time `json:"createdAt" api:"required" format:"date-time"`
	TransformationID string    `json:"transformationId" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CreatedAt        respjson.Field
		TransformationID respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A transformation whose evaluation is still running.

func (EvalResultGetResultsResponsePending) RawJSON added in v0.10.0

Returns the unmodified JSON received from the API

func (*EvalResultGetResultsResponsePending) UnmarshalJSON added in v0.10.0

func (r *EvalResultGetResultsResponsePending) UnmarshalJSON(data []byte) error

type EvalResultService added in v0.10.0

type EvalResultService struct {
	// contains filtered or unexported fields
}

Trigger and retrieve evaluations for completed transformations.

Evaluations run asynchronously and score each transformation's output against the function's schema for confidence, per-field hallucination detection, and relevance. Evaluations are supported for `extract`, `transform`, `analyze`, and `join` events.

## Lifecycle

  1. **Trigger** — `POST /v3/eval` queues jobs for a batch of transformation IDs and returns immediately with `queued` / `skipped` counts plus per-ID errors.
  2. **Poll** — `POST /v3/eval/results` (body) or `GET /v3/eval/results` (query) returns the current state of each requested transformation, partitioned into `results` (completed), `pending` (still running), and `failed` (terminal failures or unknown transformation IDs).

Up to 100 transformation IDs may be submitted per request.

EvalResultService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEvalResultService method instead.

func NewEvalResultService added in v0.10.0

func NewEvalResultService(opts ...option.RequestOption) (r EvalResultService)

NewEvalResultService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EvalResultService) FetchResults added in v0.10.0

**Fetch evaluation results for a batch of transformations (POST).**

For each requested transformation ID the response reports one of three states: a completed `result`, still-`pending`, or `failed`. The POST variant accepts the ID list in the request body; use the `GET` variant with query parameters for simpler clients.

func (*EvalResultService) GetResults added in v0.10.0

**Fetch evaluation results for a batch of transformations.**

Identical behavior to the POST variant; accepts transformation IDs as a comma-separated `transformationIDs` query parameter. Limited to 100 IDs per request.

type EvalService added in v0.10.0

type EvalService struct {

	// Trigger and retrieve evaluations for completed transformations.
	//
	// Evaluations run asynchronously and score each transformation's output against
	// the function's schema for confidence, per-field hallucination detection, and
	// relevance. Evaluations are supported for `extract`, `transform`, `analyze`, and
	// `join` events.
	//
	// ## Lifecycle
	//
	//  1. **Trigger** — `POST /v3/eval` queues jobs for a batch of transformation IDs
	//     and returns immediately with `queued` / `skipped` counts plus per-ID errors.
	//  2. **Poll** — `POST /v3/eval/results` (body) or `GET /v3/eval/results` (query)
	//     returns the current state of each requested transformation, partitioned into
	//     `results` (completed), `pending` (still running), and `failed` (terminal
	//     failures or unknown transformation IDs).
	//
	// Up to 100 transformation IDs may be submitted per request.
	Results EvalResultService
	// contains filtered or unexported fields
}

Trigger and retrieve evaluations for completed transformations.

Evaluations run asynchronously and score each transformation's output against the function's schema for confidence, per-field hallucination detection, and relevance. Evaluations are supported for `extract`, `transform`, `analyze`, and `join` events.

## Lifecycle

  1. **Trigger** — `POST /v3/eval` queues jobs for a batch of transformation IDs and returns immediately with `queued` / `skipped` counts plus per-ID errors.
  2. **Poll** — `POST /v3/eval/results` (body) or `GET /v3/eval/results` (query) returns the current state of each requested transformation, partitioned into `results` (completed), `pending` (still running), and `failed` (terminal failures or unknown transformation IDs).

Up to 100 transformation IDs may be submitted per request.

EvalService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEvalService method instead.

func NewEvalService added in v0.10.0

func NewEvalService(opts ...option.RequestOption) (r EvalService)

NewEvalService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EvalService) TriggerEvaluation added in v0.10.0

**Queue evaluation jobs for a batch of transformations.**

Evaluations run asynchronously and score each transformation's output against the function's schema for confidence, hallucination detection, and relevance. Transformations must belong to events of a supported type: `extract`, `transform`, `analyze`, or `join`.

Returns immediately with a summary of queued vs. skipped transformations and per-transformation errors. Poll `POST /v3/eval/results` or `GET /v3/eval/results` to retrieve results once evaluations complete.

type EvalTriggerEvaluationParams added in v0.10.0

type EvalTriggerEvaluationParams struct {
	// Transformation IDs to evaluate. Up to 100 per request.
	TransformationIDs []string `json:"transformationIDs,omitzero" api:"required"`
	// Optional evaluation version (e.g. `0.1.0-gemini`). When omitted the server's
	// default evaluation version is used.
	EvaluationVersion param.Opt[string] `json:"evaluationVersion,omitzero"`
	// contains filtered or unexported fields
}

func (EvalTriggerEvaluationParams) MarshalJSON added in v0.10.0

func (r EvalTriggerEvaluationParams) MarshalJSON() (data []byte, err error)

func (*EvalTriggerEvaluationParams) UnmarshalJSON added in v0.10.0

func (r *EvalTriggerEvaluationParams) UnmarshalJSON(data []byte) error

type EvalTriggerEvaluationResponse added in v0.10.0

type EvalTriggerEvaluationResponse struct {
	// Number of evaluation jobs newly queued.
	Queued int64 `json:"queued" api:"required"`
	// Number of transformations skipped because an evaluation job was already pending
	// or already completed for them.
	Skipped int64 `json:"skipped" api:"required"`
	// Map of transformation ID to human-readable error message for any transformations
	// that could not be queued (e.g. not found, unsupported event type).
	Errors any `json:"errors"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Queued      respjson.Field
		Skipped     respjson.Field
		Errors      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Summary of the trigger call. Evaluations run asynchronously; use `POST /v3/eval/results` or `GET /v3/eval/results` to poll for results.

func (EvalTriggerEvaluationResponse) RawJSON added in v0.10.0

Returns the unmodified JSON received from the API

func (*EvalTriggerEvaluationResponse) UnmarshalJSON added in v0.10.0

func (r *EvalTriggerEvaluationResponse) UnmarshalJSON(data []byte) error

type EventClassify added in v0.10.0

type EventClassify struct {
	// The classification chosen by the classify function.
	Choice string `json:"choice" api:"required"`
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// Unique identifier of function that this event is associated with.
	FunctionID string `json:"functionID" api:"required"`
	// Unique name of function that this event is associated with.
	FunctionName string `json:"functionName" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID string `json:"referenceID" api:"required"`
	// Unique identifier of workflow call that this event is associated with.
	CallID string `json:"callID"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Any of "classify".
	EventType string `json:"eventType"`
	// Unique identifier of function call that this event is associated with.
	FunctionCallID string `json:"functionCallID"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// Version number of function that this event is associated with.
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// The inbound email that triggered this event.
	InboundEmail InboundEmailEvent     `json:"inboundEmail"`
	Metadata     EventClassifyMetadata `json:"metadata"`
	// The presigned S3 URL of the file that was classified.
	S3URL string `json:"s3URL"`
	// Unique identifier of workflow that this event is associated with.
	WorkflowID string `json:"workflowID"`
	// Name of workflow that this event is associated with.
	WorkflowName string `json:"workflowName"`
	// Version number of workflow that this event is associated with.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Choice                respjson.Field
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		ReferenceID           respjson.Field
		CallID                respjson.Field
		CreatedAt             respjson.Field
		EventType             respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		InboundEmail          respjson.Field
		Metadata              respjson.Field
		S3URL                 respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventClassify) RawJSON added in v0.10.0

func (r EventClassify) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventClassify) UnmarshalJSON added in v0.10.0

func (r *EventClassify) UnmarshalJSON(data []byte) error

type EventClassifyMetadata added in v0.10.0

type EventClassifyMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventClassifyMetadata) RawJSON added in v0.10.0

func (r EventClassifyMetadata) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventClassifyMetadata) UnmarshalJSON added in v0.10.0

func (r *EventClassifyMetadata) UnmarshalJSON(data []byte) error

type EventCollectionProcessing

type EventCollectionProcessing struct {
	// Unique identifier of the collection.
	CollectionID string `json:"collectionID" api:"required"`
	// Name/path of the collection.
	CollectionName string `json:"collectionName" api:"required"`
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// The operation performed (add or update).
	//
	// Any of "add", "update".
	Operation string `json:"operation" api:"required"`
	// Number of items successfully processed.
	ProcessedCount int64 `json:"processedCount" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID string `json:"referenceID" api:"required"`
	// Processing status (success or failed).
	//
	// Any of "success", "failed".
	Status string `json:"status" api:"required"`
	// Array of collection item KSUIDs that were added or updated.
	CollectionItemIDs []string `json:"collectionItemIDs"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Error message if processing failed.
	ErrorMessage string `json:"errorMessage"`
	// Any of "collection_processing".
	EventType string `json:"eventType"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// The inbound email that triggered this event.
	InboundEmail InboundEmailEvent                 `json:"inboundEmail"`
	Metadata     EventCollectionProcessingMetadata `json:"metadata"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionID          respjson.Field
		CollectionName        respjson.Field
		EventID               respjson.Field
		Operation             respjson.Field
		ProcessedCount        respjson.Field
		ReferenceID           respjson.Field
		Status                respjson.Field
		CollectionItemIDs     respjson.Field
		CreatedAt             respjson.Field
		ErrorMessage          respjson.Field
		EventType             respjson.Field
		FunctionCallTryNumber respjson.Field
		InboundEmail          respjson.Field
		Metadata              respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventCollectionProcessing) RawJSON

func (r EventCollectionProcessing) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventCollectionProcessing) UnmarshalJSON

func (r *EventCollectionProcessing) UnmarshalJSON(data []byte) error

type EventCollectionProcessingMetadata

type EventCollectionProcessingMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventCollectionProcessingMetadata) RawJSON

Returns the unmodified JSON received from the API

func (*EventCollectionProcessingMetadata) UnmarshalJSON

func (r *EventCollectionProcessingMetadata) UnmarshalJSON(data []byte) error

type EventEnrich

type EventEnrich struct {
	// The enriched content produced by the enrich function. Contains the input data
	// augmented with results from semantic search against collections.
	EnrichedContent any `json:"enrichedContent" api:"required"`
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// Unique identifier of function that this event is associated with.
	FunctionID string `json:"functionID" api:"required"`
	// Unique name of function that this event is associated with.
	FunctionName string `json:"functionName" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID string `json:"referenceID" api:"required"`
	// Unique identifier of workflow call that this event is associated with.
	CallID string `json:"callID"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Any of "enrich".
	EventType string `json:"eventType"`
	// Unique identifier of function call that this event is associated with.
	FunctionCallID string `json:"functionCallID"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// Version number of function that this event is associated with.
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// The inbound email that triggered this event.
	InboundEmail InboundEmailEvent   `json:"inboundEmail"`
	Metadata     EventEnrichMetadata `json:"metadata"`
	// Unique identifier of workflow that this event is associated with.
	WorkflowID string `json:"workflowID"`
	// Name of workflow that this event is associated with.
	WorkflowName string `json:"workflowName"`
	// Version number of workflow that this event is associated with.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EnrichedContent       respjson.Field
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		ReferenceID           respjson.Field
		CallID                respjson.Field
		CreatedAt             respjson.Field
		EventType             respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		InboundEmail          respjson.Field
		Metadata              respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventEnrich) RawJSON

func (r EventEnrich) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventEnrich) UnmarshalJSON

func (r *EventEnrich) UnmarshalJSON(data []byte) error

type EventEnrichMetadata

type EventEnrichMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventEnrichMetadata) RawJSON

func (r EventEnrichMetadata) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventEnrichMetadata) UnmarshalJSON

func (r *EventEnrichMetadata) UnmarshalJSON(data []byte) error

type EventExtract added in v0.10.0

type EventExtract struct {
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// Unique identifier of function that this event is associated with.
	FunctionID string `json:"functionID" api:"required"`
	// Unique name of function that this event is associated with.
	FunctionName string `json:"functionName" api:"required"`
	// The number of items that were transformed. Used for batch transformations to
	// indicate how many items were transformed.
	ItemCount int64 `json:"itemCount" api:"required"`
	// The offset of the first item that was transformed. Used for batch
	// transformations to indicate which item in the batch this event corresponds to.
	ItemOffset int64 `json:"itemOffset" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID string `json:"referenceID" api:"required"`
	// The transformed content of the input. The structure of this object is defined by
	// the function configuration.
	TransformedContent any `json:"transformedContent" api:"required"`
	// Average confidence score across all extracted fields, in the range [0, 1].
	AvgConfidence float64 `json:"avgConfidence" api:"nullable"`
	// Unique identifier of workflow call that this event is associated with.
	CallID string `json:"callID"`
	// Corrected feedback provided for fine-tuning purposes.
	CorrectedContent EventExtractCorrectedContentUnion `json:"correctedContent" api:"nullable"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Any of "extract".
	EventType string `json:"eventType"`
	// Per-field bounding boxes. A JSON object mapping RFC 6901 JSON Pointer paths
	// (e.g. `"/invoiceNumber"`, `"/items/0/price"`) to the document regions from which
	// each extracted value was sourced.
	FieldBoundingBoxes any `json:"fieldBoundingBoxes"`
	// Per-field confidence scores. A JSON object mapping RFC 6901 JSON Pointer paths
	// (e.g. `"/invoiceNumber"`) to float values in the range [0, 1] indicating the
	// model's confidence in each extracted field value.
	FieldConfidences any `json:"fieldConfidences"`
	// Unique identifier of function call that this event is associated with.
	FunctionCallID string `json:"functionCallID"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// Version number of function that this event is associated with.
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// The inbound email that triggered this event.
	InboundEmail InboundEmailEvent `json:"inboundEmail"`
	// Array of transformation inputs with their types and S3 URLs.
	Inputs []EventExtractInput `json:"inputs" api:"nullable"`
	// The input type of the content you're sending for transformation.
	//
	// Any of "csv", "docx", "email", "heic", "html", "jpeg", "json", "heif", "m4a",
	// "mp3", "pdf", "png", "text", "wav", "webp", "xls", "xlsx", "xml".
	InputType string `json:"inputType"`
	// List of properties that were invalid in the input.
	InvalidProperties []string             `json:"invalidProperties"`
	Metadata          EventExtractMetadata `json:"metadata"`
	// Presigned S3 URL for the input content uploaded to S3.
	S3URL string `json:"s3URL" api:"nullable"`
	// Unique ID for each transformation output generated by bem following Segment's
	// KSUID conventions.
	TransformationID string `json:"transformationID"`
	// Unique identifier of workflow that this event is associated with.
	WorkflowID string `json:"workflowID"`
	// Name of workflow that this event is associated with.
	WorkflowName string `json:"workflowName"`
	// Version number of workflow that this event is associated with.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		ItemCount             respjson.Field
		ItemOffset            respjson.Field
		ReferenceID           respjson.Field
		TransformedContent    respjson.Field
		AvgConfidence         respjson.Field
		CallID                respjson.Field
		CorrectedContent      respjson.Field
		CreatedAt             respjson.Field
		EventType             respjson.Field
		FieldBoundingBoxes    respjson.Field
		FieldConfidences      respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		InboundEmail          respjson.Field
		Inputs                respjson.Field
		InputType             respjson.Field
		InvalidProperties     respjson.Field
		Metadata              respjson.Field
		S3URL                 respjson.Field
		TransformationID      respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

V3 event variants that do not exist in the shared `Event` union.

`ExtractEvent` and `ClassifyEvent` are emitted only by V3-era function types (`extract` and `classify`). The shared `Event` union in `specs/events/models.tsp` predates these types and continues to describe V2 / V1-alpha responses verbatim; V3 response payloads add the new variants via the `EventV3` union below while keeping every shared variant intact for backward compatibility.

func (EventExtract) RawJSON added in v0.10.0

func (r EventExtract) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventExtract) UnmarshalJSON added in v0.10.0

func (r *EventExtract) UnmarshalJSON(data []byte) error

type EventExtractCorrectedContentOutput added in v0.10.0

type EventExtractCorrectedContentOutput struct {
	Output []AnyTypeUnion `json:"output"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Output      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventExtractCorrectedContentOutput) RawJSON added in v0.10.0

Returns the unmodified JSON received from the API

func (*EventExtractCorrectedContentOutput) UnmarshalJSON added in v0.10.0

func (r *EventExtractCorrectedContentOutput) UnmarshalJSON(data []byte) error

type EventExtractCorrectedContentUnion added in v0.10.0

type EventExtractCorrectedContentUnion struct {
	// This field will be present if the value is a [[]any] instead of an object.
	OfAnyArray []any `json:",inline"`
	// This field will be present if the value is a [string] instead of an object.
	OfString string `json:",inline"`
	// This field will be present if the value is a [float64] instead of an object.
	OfFloat float64 `json:",inline"`
	// This field will be present if the value is a [bool] instead of an object.
	OfBool bool `json:",inline"`
	// This field is from variant [EventExtractCorrectedContentOutput].
	Output []AnyTypeUnion `json:"output"`
	JSON   struct {
		OfAnyArray respjson.Field
		OfString   respjson.Field
		OfFloat    respjson.Field
		OfBool     respjson.Field
		Output     respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

EventExtractCorrectedContentUnion contains all possible properties and values from EventExtractCorrectedContentOutput, [[]any], [string], [float64], [bool].

Use the methods beginning with 'As' to cast the union to one of its variants.

If the underlying value is not a json object, one of the following properties will be valid: OfAnyArray OfString OfFloat OfBool]

func (EventExtractCorrectedContentUnion) AsAnyArray added in v0.10.0

func (u EventExtractCorrectedContentUnion) AsAnyArray() (v []any)

func (EventExtractCorrectedContentUnion) AsBool added in v0.10.0

func (u EventExtractCorrectedContentUnion) AsBool() (v bool)

func (EventExtractCorrectedContentUnion) AsEventExtractCorrectedContentOutput added in v0.10.0

func (u EventExtractCorrectedContentUnion) AsEventExtractCorrectedContentOutput() (v EventExtractCorrectedContentOutput)

func (EventExtractCorrectedContentUnion) AsFloat added in v0.10.0

func (EventExtractCorrectedContentUnion) AsString added in v0.10.0

func (u EventExtractCorrectedContentUnion) AsString() (v string)

func (EventExtractCorrectedContentUnion) RawJSON added in v0.10.0

Returns the unmodified JSON received from the API

func (*EventExtractCorrectedContentUnion) UnmarshalJSON added in v0.10.0

func (r *EventExtractCorrectedContentUnion) UnmarshalJSON(data []byte) error

type EventExtractInput added in v0.10.0

type EventExtractInput struct {
	InputContent     string `json:"inputContent" api:"nullable"`
	InputType        string `json:"inputType" api:"nullable"`
	JsonInputContent any    `json:"jsonInputContent" api:"nullable"`
	S3URL            string `json:"s3URL" api:"nullable"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		InputContent     respjson.Field
		InputType        respjson.Field
		JsonInputContent respjson.Field
		S3URL            respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventExtractInput) RawJSON added in v0.10.0

func (r EventExtractInput) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventExtractInput) UnmarshalJSON added in v0.10.0

func (r *EventExtractInput) UnmarshalJSON(data []byte) error

type EventExtractMetadata added in v0.10.0

type EventExtractMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventExtractMetadata) RawJSON added in v0.10.0

func (r EventExtractMetadata) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventExtractMetadata) UnmarshalJSON added in v0.10.0

func (r *EventExtractMetadata) UnmarshalJSON(data []byte) error

type EventJoin

type EventJoin struct {
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// Unique identifier of function that this event is associated with.
	FunctionID string `json:"functionID" api:"required"`
	// Unique name of function that this event is associated with.
	FunctionName string `json:"functionName" api:"required"`
	// List of properties that were invalid in the input.
	InvalidProperties []string `json:"invalidProperties" api:"required"`
	// The items that were joined.
	Items []EventJoinItem `json:"items" api:"required"`
	// The type of join that was performed.
	//
	// Any of "standard".
	JoinType string `json:"joinType" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID string `json:"referenceID" api:"required"`
	// The transformed content of the input. The structure of this object is defined by
	// the function configuration.
	TransformedContent any `json:"transformedContent" api:"required"`
	// Average confidence score across all extracted fields, in the range [0, 1].
	AvgConfidence float64 `json:"avgConfidence" api:"nullable"`
	// Unique identifier of workflow call that this event is associated with.
	CallID string `json:"callID"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Any of "join".
	EventType string `json:"eventType"`
	// Per-field confidence scores. A JSON object mapping RFC 6901 JSON Pointer paths
	// (e.g. `"/invoiceNumber"`) to float values in the range [0, 1] indicating the
	// model's confidence in each extracted field value.
	FieldConfidences any `json:"fieldConfidences"`
	// Unique identifier of function call that this event is associated with.
	FunctionCallID string `json:"functionCallID"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// Version number of function that this event is associated with.
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// The inbound email that triggered this event.
	InboundEmail InboundEmailEvent `json:"inboundEmail"`
	Metadata     EventJoinMetadata `json:"metadata"`
	// Unique ID for each transformation output generated by bem following Segment's
	// KSUID conventions.
	TransformationID string `json:"transformationID"`
	// Unique identifier of workflow that this event is associated with.
	WorkflowID string `json:"workflowID"`
	// Name of workflow that this event is associated with.
	WorkflowName string `json:"workflowName"`
	// Version number of workflow that this event is associated with.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		InvalidProperties     respjson.Field
		Items                 respjson.Field
		JoinType              respjson.Field
		ReferenceID           respjson.Field
		TransformedContent    respjson.Field
		AvgConfidence         respjson.Field
		CallID                respjson.Field
		CreatedAt             respjson.Field
		EventType             respjson.Field
		FieldConfidences      respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		InboundEmail          respjson.Field
		Metadata              respjson.Field
		TransformationID      respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventJoin) RawJSON

func (r EventJoin) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventJoin) UnmarshalJSON

func (r *EventJoin) UnmarshalJSON(data []byte) error

type EventJoinItem

type EventJoinItem struct {
	// The number of items that were transformed.
	ItemCount int64 `json:"itemCount" api:"required"`
	// The offset of the first item that was transformed. Used for batch
	// transformations to indicate which item in the batch this event corresponds to.
	ItemOffset int64 `json:"itemOffset" api:"required"`
	// The unique ID you use internally to refer to this data point.
	ItemReferenceID string `json:"itemReferenceID" api:"required"`
	// The presigned S3 URL of the file that was joined.
	S3URL string `json:"s3URL"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ItemCount       respjson.Field
		ItemOffset      respjson.Field
		ItemReferenceID respjson.Field
		S3URL           respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventJoinItem) RawJSON

func (r EventJoinItem) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventJoinItem) UnmarshalJSON

func (r *EventJoinItem) UnmarshalJSON(data []byte) error

type EventJoinMetadata

type EventJoinMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventJoinMetadata) RawJSON

func (r EventJoinMetadata) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventJoinMetadata) UnmarshalJSON

func (r *EventJoinMetadata) UnmarshalJSON(data []byte) error

type EventRoute

type EventRoute struct {
	// The choice made by the router function.
	Choice string `json:"choice" api:"required"`
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// Unique identifier of function that this event is associated with.
	FunctionID string `json:"functionID" api:"required"`
	// Unique name of function that this event is associated with.
	FunctionName string `json:"functionName" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID string `json:"referenceID" api:"required"`
	// Unique identifier of workflow call that this event is associated with.
	CallID string `json:"callID"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Any of "route".
	EventType string `json:"eventType"`
	// Unique identifier of function call that this event is associated with.
	FunctionCallID string `json:"functionCallID"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// Version number of function that this event is associated with.
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// The inbound email that triggered this event.
	InboundEmail InboundEmailEvent  `json:"inboundEmail"`
	Metadata     EventRouteMetadata `json:"metadata"`
	// The presigned S3 URL of the file that was routed.
	S3URL string `json:"s3URL"`
	// Unique identifier of workflow that this event is associated with.
	WorkflowID string `json:"workflowID"`
	// Name of workflow that this event is associated with.
	WorkflowName string `json:"workflowName"`
	// Version number of workflow that this event is associated with.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Choice                respjson.Field
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		ReferenceID           respjson.Field
		CallID                respjson.Field
		CreatedAt             respjson.Field
		EventType             respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		InboundEmail          respjson.Field
		Metadata              respjson.Field
		S3URL                 respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventRoute) RawJSON

func (r EventRoute) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventRoute) UnmarshalJSON

func (r *EventRoute) UnmarshalJSON(data []byte) error

type EventRouteMetadata

type EventRouteMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventRouteMetadata) RawJSON

func (r EventRouteMetadata) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventRouteMetadata) UnmarshalJSON

func (r *EventRouteMetadata) UnmarshalJSON(data []byte) error

type EventSend

type EventSend struct {
	// Outcome of a Send function's delivery attempt.
	//
	// Any of "success", "skip".
	DeliveryStatus string `json:"deliveryStatus" api:"required"`
	// Destination type for a Send function.
	//
	// Any of "webhook", "s3", "google_drive".
	DestinationType string `json:"destinationType" api:"required"`
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// Unique identifier of function that this event is associated with.
	FunctionID string `json:"functionID" api:"required"`
	// Unique name of function that this event is associated with.
	FunctionName string `json:"functionName" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID string `json:"referenceID" api:"required"`
	// Unique identifier of workflow call that this event is associated with.
	CallID string `json:"callID"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// The full protocol event JSON that was delivered — identical to what subscription
	// publish would deliver for the same event. For ad-hoc calls with a JSON file
	// input, contains the raw input JSON. For ad-hoc calls with a binary file input,
	// contains {"s3URL": "<presigned-url>"}.
	DeliveredContent any `json:"deliveredContent"`
	// Any of "send".
	EventType string `json:"eventType"`
	// Unique identifier of function call that this event is associated with.
	FunctionCallID string `json:"functionCallID"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// Version number of function that this event is associated with.
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// Metadata returned when a Send function delivers to Google Drive.
	GoogleDriveOutput EventSendGoogleDriveOutput `json:"googleDriveOutput"`
	// The inbound email that triggered this event.
	InboundEmail InboundEmailEvent `json:"inboundEmail"`
	Metadata     EventSendMetadata `json:"metadata"`
	// Metadata returned when a Send function delivers to an S3 bucket.
	S3Output EventSendS3Output `json:"s3Output"`
	// Metadata returned when a Send function delivers to a webhook.
	WebhookOutput EventSendWebhookOutput `json:"webhookOutput"`
	// Unique identifier of workflow that this event is associated with.
	WorkflowID string `json:"workflowID"`
	// Name of workflow that this event is associated with.
	WorkflowName string `json:"workflowName"`
	// Version number of workflow that this event is associated with.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DeliveryStatus        respjson.Field
		DestinationType       respjson.Field
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		ReferenceID           respjson.Field
		CallID                respjson.Field
		CreatedAt             respjson.Field
		DeliveredContent      respjson.Field
		EventType             respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		GoogleDriveOutput     respjson.Field
		InboundEmail          respjson.Field
		Metadata              respjson.Field
		S3Output              respjson.Field
		WebhookOutput         respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSend) RawJSON

func (r EventSend) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventSend) UnmarshalJSON

func (r *EventSend) UnmarshalJSON(data []byte) error

type EventSendGoogleDriveOutput

type EventSendGoogleDriveOutput struct {
	// Name of the file created in Google Drive.
	FileName string `json:"fileName" api:"required"`
	// ID of the Google Drive folder the file was placed in.
	FolderID string `json:"folderID" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		FileName    respjson.Field
		FolderID    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Metadata returned when a Send function delivers to Google Drive.

func (EventSendGoogleDriveOutput) RawJSON

func (r EventSendGoogleDriveOutput) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventSendGoogleDriveOutput) UnmarshalJSON

func (r *EventSendGoogleDriveOutput) UnmarshalJSON(data []byte) error

type EventSendMetadata

type EventSendMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSendMetadata) RawJSON

func (r EventSendMetadata) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventSendMetadata) UnmarshalJSON

func (r *EventSendMetadata) UnmarshalJSON(data []byte) error

type EventSendS3Output

type EventSendS3Output struct {
	// Name of the S3 bucket the payload was written to.
	BucketName string `json:"bucketName" api:"required"`
	// Object key under which the payload was stored.
	Key string `json:"key" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		BucketName  respjson.Field
		Key         respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Metadata returned when a Send function delivers to an S3 bucket.

func (EventSendS3Output) RawJSON

func (r EventSendS3Output) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventSendS3Output) UnmarshalJSON

func (r *EventSendS3Output) UnmarshalJSON(data []byte) error

type EventSendWebhookOutput

type EventSendWebhookOutput struct {
	// Raw HTTP response body returned by the webhook endpoint.
	HTTPResponseBody string `json:"httpResponseBody" api:"required"`
	// HTTP status code returned by the webhook endpoint.
	HTTPStatusCode int64 `json:"httpStatusCode" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		HTTPResponseBody respjson.Field
		HTTPStatusCode   respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Metadata returned when a Send function delivers to a webhook.

func (EventSendWebhookOutput) RawJSON

func (r EventSendWebhookOutput) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventSendWebhookOutput) UnmarshalJSON

func (r *EventSendWebhookOutput) UnmarshalJSON(data []byte) error

type EventService added in v0.9.0

type EventService struct {
	// contains filtered or unexported fields
}

Submit training corrections for `extract`, `classify`, and `join` events.

Feedback is event-centric — each correction is attached to an event by its `eventID`, and the server resolves the correct underlying storage (extract/join transformations or classify route events) from the event's function type.

Split and enrich function types do not support feedback.

EventService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEventService method instead.

func NewEventService added in v0.9.0

func NewEventService(opts ...option.RequestOption) (r EventService)

NewEventService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EventService) SubmitFeedback added in v0.9.0

func (r *EventService) SubmitFeedback(ctx context.Context, eventID string, body EventSubmitFeedbackParams, opts ...option.RequestOption) (res *EventSubmitFeedbackResponse, err error)

**Submit a correction for an event.**

Accepts training corrections for `extract`, `classify`, and `join` events. For extract/join events, `correction` is a JSON object matching the function's output schema. For classify events, `correction` is a JSON string matching one of the function version's declared classifications.

Submitting feedback again for the same event overwrites the previous correction.

Unsupported function types (split, enrich) return `400`.

type EventSplitCollection

type EventSplitCollection struct {
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// Unique identifier of function that this event is associated with.
	FunctionID string `json:"functionID" api:"required"`
	// Unique name of function that this event is associated with.
	FunctionName string `json:"functionName" api:"required"`
	// Any of "print_page", "semantic_page".
	OutputType      string                              `json:"outputType" api:"required"`
	PrintPageOutput EventSplitCollectionPrintPageOutput `json:"printPageOutput" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID        string                                 `json:"referenceID" api:"required"`
	SemanticPageOutput EventSplitCollectionSemanticPageOutput `json:"semanticPageOutput" api:"required"`
	// Unique identifier of workflow call that this event is associated with.
	CallID string `json:"callID"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Any of "split_collection".
	EventType string `json:"eventType"`
	// Unique identifier of function call that this event is associated with.
	FunctionCallID string `json:"functionCallID"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// Version number of function that this event is associated with.
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// The inbound email that triggered this event.
	InboundEmail InboundEmailEvent            `json:"inboundEmail"`
	Metadata     EventSplitCollectionMetadata `json:"metadata"`
	// Unique identifier of workflow that this event is associated with.
	WorkflowID string `json:"workflowID"`
	// Name of workflow that this event is associated with.
	WorkflowName string `json:"workflowName"`
	// Version number of workflow that this event is associated with.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		OutputType            respjson.Field
		PrintPageOutput       respjson.Field
		ReferenceID           respjson.Field
		SemanticPageOutput    respjson.Field
		CallID                respjson.Field
		CreatedAt             respjson.Field
		EventType             respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		InboundEmail          respjson.Field
		Metadata              respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSplitCollection) RawJSON

func (r EventSplitCollection) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventSplitCollection) UnmarshalJSON

func (r *EventSplitCollection) UnmarshalJSON(data []byte) error

type EventSplitCollectionMetadata

type EventSplitCollectionMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSplitCollectionMetadata) RawJSON

Returns the unmodified JSON received from the API

func (*EventSplitCollectionMetadata) UnmarshalJSON

func (r *EventSplitCollectionMetadata) UnmarshalJSON(data []byte) error

type EventSplitCollectionPrintPageOutput

type EventSplitCollectionPrintPageOutput struct {
	ItemCount int64                                     `json:"itemCount"`
	Items     []EventSplitCollectionPrintPageOutputItem `json:"items"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ItemCount   respjson.Field
		Items       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSplitCollectionPrintPageOutput) RawJSON

Returns the unmodified JSON received from the API

func (*EventSplitCollectionPrintPageOutput) UnmarshalJSON

func (r *EventSplitCollectionPrintPageOutput) UnmarshalJSON(data []byte) error

type EventSplitCollectionPrintPageOutputItem

type EventSplitCollectionPrintPageOutputItem struct {
	ItemOffset      int64  `json:"itemOffset"`
	ItemReferenceID string `json:"itemReferenceID"`
	S3URL           string `json:"s3URL"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ItemOffset      respjson.Field
		ItemReferenceID respjson.Field
		S3URL           respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSplitCollectionPrintPageOutputItem) RawJSON

Returns the unmodified JSON received from the API

func (*EventSplitCollectionPrintPageOutputItem) UnmarshalJSON

func (r *EventSplitCollectionPrintPageOutputItem) UnmarshalJSON(data []byte) error

type EventSplitCollectionSemanticPageOutput

type EventSplitCollectionSemanticPageOutput struct {
	ItemCount int64                                        `json:"itemCount"`
	Items     []EventSplitCollectionSemanticPageOutputItem `json:"items"`
	PageCount int64                                        `json:"pageCount"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ItemCount   respjson.Field
		Items       respjson.Field
		PageCount   respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSplitCollectionSemanticPageOutput) RawJSON

Returns the unmodified JSON received from the API

func (*EventSplitCollectionSemanticPageOutput) UnmarshalJSON

func (r *EventSplitCollectionSemanticPageOutput) UnmarshalJSON(data []byte) error

type EventSplitCollectionSemanticPageOutputItem

type EventSplitCollectionSemanticPageOutputItem struct {
	ItemClass       string `json:"itemClass"`
	ItemClassCount  int64  `json:"itemClassCount"`
	ItemClassOffset int64  `json:"itemClassOffset"`
	ItemOffset      int64  `json:"itemOffset"`
	ItemReferenceID string `json:"itemReferenceID"`
	PageEnd         int64  `json:"pageEnd"`
	PageStart       int64  `json:"pageStart"`
	S3URL           string `json:"s3URL"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ItemClass       respjson.Field
		ItemClassCount  respjson.Field
		ItemClassOffset respjson.Field
		ItemOffset      respjson.Field
		ItemReferenceID respjson.Field
		PageEnd         respjson.Field
		PageStart       respjson.Field
		S3URL           respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSplitCollectionSemanticPageOutputItem) RawJSON

Returns the unmodified JSON received from the API

func (*EventSplitCollectionSemanticPageOutputItem) UnmarshalJSON

func (r *EventSplitCollectionSemanticPageOutputItem) UnmarshalJSON(data []byte) error

type EventSplitItem

type EventSplitItem struct {
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// Unique identifier of function that this event is associated with.
	FunctionID string `json:"functionID" api:"required"`
	// Unique name of function that this event is associated with.
	FunctionName string `json:"functionName" api:"required"`
	// Any of "print_page", "semantic_page".
	OutputType string `json:"outputType" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID string `json:"referenceID" api:"required"`
	// Unique identifier of workflow call that this event is associated with.
	CallID string `json:"callID"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Any of "split_item".
	EventType string `json:"eventType"`
	// Unique identifier of function call that this event is associated with.
	FunctionCallID string `json:"functionCallID"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// Version number of function that this event is associated with.
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// The inbound email that triggered this event.
	InboundEmail       InboundEmailEvent                `json:"inboundEmail"`
	Metadata           EventSplitItemMetadata           `json:"metadata"`
	PrintPageOutput    EventSplitItemPrintPageOutput    `json:"printPageOutput"`
	SemanticPageOutput EventSplitItemSemanticPageOutput `json:"semanticPageOutput"`
	// Unique identifier of workflow that this event is associated with.
	WorkflowID string `json:"workflowID"`
	// Name of workflow that this event is associated with.
	WorkflowName string `json:"workflowName"`
	// Version number of workflow that this event is associated with.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		OutputType            respjson.Field
		ReferenceID           respjson.Field
		CallID                respjson.Field
		CreatedAt             respjson.Field
		EventType             respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		InboundEmail          respjson.Field
		Metadata              respjson.Field
		PrintPageOutput       respjson.Field
		SemanticPageOutput    respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSplitItem) RawJSON

func (r EventSplitItem) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventSplitItem) UnmarshalJSON

func (r *EventSplitItem) UnmarshalJSON(data []byte) error

type EventSplitItemMetadata

type EventSplitItemMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSplitItemMetadata) RawJSON

func (r EventSplitItemMetadata) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventSplitItemMetadata) UnmarshalJSON

func (r *EventSplitItemMetadata) UnmarshalJSON(data []byte) error

type EventSplitItemPrintPageOutput

type EventSplitItemPrintPageOutput struct {
	CollectionReferenceID string `json:"collectionReferenceID"`
	ItemCount             int64  `json:"itemCount"`
	ItemOffset            int64  `json:"itemOffset"`
	S3URL                 string `json:"s3URL"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionReferenceID respjson.Field
		ItemCount             respjson.Field
		ItemOffset            respjson.Field
		S3URL                 respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSplitItemPrintPageOutput) RawJSON

Returns the unmodified JSON received from the API

func (*EventSplitItemPrintPageOutput) UnmarshalJSON

func (r *EventSplitItemPrintPageOutput) UnmarshalJSON(data []byte) error

type EventSplitItemSemanticPageOutput

type EventSplitItemSemanticPageOutput struct {
	CollectionReferenceID string `json:"collectionReferenceID"`
	ItemClass             string `json:"itemClass"`
	ItemClassCount        int64  `json:"itemClassCount"`
	ItemClassOffset       int64  `json:"itemClassOffset"`
	ItemCount             int64  `json:"itemCount"`
	ItemOffset            int64  `json:"itemOffset"`
	PageCount             int64  `json:"pageCount"`
	PageEnd               int64  `json:"pageEnd"`
	PageStart             int64  `json:"pageStart"`
	S3URL                 string `json:"s3URL"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CollectionReferenceID respjson.Field
		ItemClass             respjson.Field
		ItemClassCount        respjson.Field
		ItemClassOffset       respjson.Field
		ItemCount             respjson.Field
		ItemOffset            respjson.Field
		PageCount             respjson.Field
		PageEnd               respjson.Field
		PageStart             respjson.Field
		S3URL                 respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventSplitItemSemanticPageOutput) RawJSON

Returns the unmodified JSON received from the API

func (*EventSplitItemSemanticPageOutput) UnmarshalJSON

func (r *EventSplitItemSemanticPageOutput) UnmarshalJSON(data []byte) error

type EventSubmitFeedbackParams added in v0.9.0

type EventSubmitFeedbackParams struct {
	Correction    any             `json:"correction,omitzero" api:"required"`
	OrderMatching param.Opt[bool] `json:"orderMatching,omitzero"`
	// contains filtered or unexported fields
}

func (EventSubmitFeedbackParams) MarshalJSON added in v0.9.0

func (r EventSubmitFeedbackParams) MarshalJSON() (data []byte, err error)

func (*EventSubmitFeedbackParams) UnmarshalJSON added in v0.9.0

func (r *EventSubmitFeedbackParams) UnmarshalJSON(data []byte) error

type EventSubmitFeedbackResponse added in v0.9.0

type EventSubmitFeedbackResponse struct {
	Correction any `json:"correction" api:"required"`
	// Server timestamp when the correction was persisted (RFC 3339).
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	EventID   string    `json:"eventID" api:"required"`
	// Function types that support feedback submission.
	//
	// Any of "extract", "classify", "join".
	FunctionType EventSubmitFeedbackResponseFunctionType `json:"functionType" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Correction   respjson.Field
		CreatedAt    respjson.Field
		EventID      respjson.Field
		FunctionType respjson.Field
		ExtraFields  map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Echoed response after a correction is recorded.

func (EventSubmitFeedbackResponse) RawJSON added in v0.9.0

func (r EventSubmitFeedbackResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventSubmitFeedbackResponse) UnmarshalJSON added in v0.9.0

func (r *EventSubmitFeedbackResponse) UnmarshalJSON(data []byte) error

type EventSubmitFeedbackResponseFunctionType added in v0.9.0

type EventSubmitFeedbackResponseFunctionType string

Function types that support feedback submission.

const (
	EventSubmitFeedbackResponseFunctionTypeExtract  EventSubmitFeedbackResponseFunctionType = "extract"
	EventSubmitFeedbackResponseFunctionTypeClassify EventSubmitFeedbackResponseFunctionType = "classify"
	EventSubmitFeedbackResponseFunctionTypeJoin     EventSubmitFeedbackResponseFunctionType = "join"
)

type EventTransform

type EventTransform struct {
	// Unique ID generated by bem to identify the event.
	EventID string `json:"eventID" api:"required"`
	// Unique identifier of function that this event is associated with.
	FunctionID string `json:"functionID" api:"required"`
	// Unique name of function that this event is associated with.
	FunctionName string `json:"functionName" api:"required"`
	// The number of items that were transformed. Used for batch transformations to
	// indicate how many items were transformed.
	ItemCount int64 `json:"itemCount" api:"required"`
	// The offset of the first item that was transformed. Used for batch
	// transformations to indicate which item in the batch this event corresponds to.
	ItemOffset int64 `json:"itemOffset" api:"required"`
	// The unique ID you use internally to refer to this data point, propagated from
	// the original function input.
	ReferenceID string `json:"referenceID" api:"required"`
	// The transformed content of the input. The structure of this object is defined by
	// the function configuration.
	TransformedContent any `json:"transformedContent" api:"required"`
	// Average confidence score across all extracted fields, in the range [0, 1].
	AvgConfidence float64 `json:"avgConfidence" api:"nullable"`
	// Unique identifier of workflow call that this event is associated with.
	CallID string `json:"callID"`
	// Corrected feedback provided for fine-tuning purposes.
	CorrectedContent EventTransformCorrectedContentUnion `json:"correctedContent" api:"nullable"`
	// Timestamp indicating when the event was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Any of "transform".
	EventType string `json:"eventType"`
	// Per-field confidence scores. A JSON object mapping RFC 6901 JSON Pointer paths
	// (e.g. `"/invoiceNumber"`) to float values in the range [0, 1] indicating the
	// model's confidence in each extracted field value.
	FieldConfidences any `json:"fieldConfidences"`
	// Unique identifier of function call that this event is associated with.
	FunctionCallID string `json:"functionCallID"`
	// The attempt number of the function call that created this event. 1 indexed.
	FunctionCallTryNumber int64 `json:"functionCallTryNumber"`
	// Version number of function that this event is associated with.
	FunctionVersionNum int64 `json:"functionVersionNum"`
	// The inbound email that triggered this event.
	InboundEmail InboundEmailEvent `json:"inboundEmail"`
	// Array of transformation inputs with their types and S3 URLs.
	Inputs []EventTransformInput `json:"inputs" api:"nullable"`
	// The input type of the content you're sending for transformation.
	//
	// Any of "csv", "docx", "email", "heic", "html", "jpeg", "json", "heif", "m4a",
	// "mp3", "pdf", "png", "text", "wav", "webp", "xls", "xlsx", "xml".
	InputType string `json:"inputType"`
	// List of properties that were invalid in the input.
	InvalidProperties []string `json:"invalidProperties"`
	// Indicates whether this transformation was created as part of a regression test.
	IsRegression bool `json:"isRegression"`
	// Last timestamp indicating when the transform was published via webhook and
	// received a non-200 response. Set to `null` on a subsequent retry if the webhook
	// service receives a 200 response.
	LastPublishErrorAt string                 `json:"lastPublishErrorAt" api:"nullable"`
	Metadata           EventTransformMetadata `json:"metadata"`
	// Accuracy, precision, recall, and F1 score when corrected JSON is provided.
	Metrics EventTransformMetrics `json:"metrics" api:"nullable"`
	// Indicates whether array order matters when comparing corrected JSON with
	// extracted JSON.
	OrderMatching bool `json:"orderMatching"`
	// ID of pipeline that transformed the original input data.
	PipelineID string `json:"pipelineID"`
	// Timestamp indicating when the transform was published via webhook and received a
	// successful 200 response. Value is `null` if the transformation hasn't been sent.
	PublishedAt time.Time `json:"publishedAt" format:"date-time"`
	// Presigned S3 URL for the input content uploaded to S3.
	S3URL string `json:"s3URL" api:"nullable"`
	// Unique ID for each transformation output generated by bem following Segment's
	// KSUID conventions.
	TransformationID string `json:"transformationID"`
	// Unique identifier of workflow that this event is associated with.
	WorkflowID string `json:"workflowID"`
	// Name of workflow that this event is associated with.
	WorkflowName string `json:"workflowName"`
	// Version number of workflow that this event is associated with.
	WorkflowVersionNum int64 `json:"workflowVersionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		ItemCount             respjson.Field
		ItemOffset            respjson.Field
		ReferenceID           respjson.Field
		TransformedContent    respjson.Field
		AvgConfidence         respjson.Field
		CallID                respjson.Field
		CorrectedContent      respjson.Field
		CreatedAt             respjson.Field
		EventType             respjson.Field
		FieldConfidences      respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		InboundEmail          respjson.Field
		Inputs                respjson.Field
		InputType             respjson.Field
		InvalidProperties     respjson.Field
		IsRegression          respjson.Field
		LastPublishErrorAt    respjson.Field
		Metadata              respjson.Field
		Metrics               respjson.Field
		OrderMatching         respjson.Field
		PipelineID            respjson.Field
		PublishedAt           respjson.Field
		S3URL                 respjson.Field
		TransformationID      respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventTransform) RawJSON

func (r EventTransform) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventTransform) UnmarshalJSON

func (r *EventTransform) UnmarshalJSON(data []byte) error

type EventTransformCorrectedContentOutput

type EventTransformCorrectedContentOutput struct {
	Output []AnyTypeUnion `json:"output"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Output      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventTransformCorrectedContentOutput) RawJSON

Returns the unmodified JSON received from the API

func (*EventTransformCorrectedContentOutput) UnmarshalJSON

func (r *EventTransformCorrectedContentOutput) UnmarshalJSON(data []byte) error

type EventTransformCorrectedContentUnion

type EventTransformCorrectedContentUnion struct {
	// This field will be present if the value is a [[]any] instead of an object.
	OfAnyArray []any `json:",inline"`
	// This field will be present if the value is a [string] instead of an object.
	OfString string `json:",inline"`
	// This field will be present if the value is a [float64] instead of an object.
	OfFloat float64 `json:",inline"`
	// This field will be present if the value is a [bool] instead of an object.
	OfBool bool `json:",inline"`
	// This field is from variant [EventTransformCorrectedContentOutput].
	Output []AnyTypeUnion `json:"output"`
	JSON   struct {
		OfAnyArray respjson.Field
		OfString   respjson.Field
		OfFloat    respjson.Field
		OfBool     respjson.Field
		Output     respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

EventTransformCorrectedContentUnion contains all possible properties and values from EventTransformCorrectedContentOutput, [[]any], [string], [float64], [bool].

Use the methods beginning with 'As' to cast the union to one of its variants.

If the underlying value is not a json object, one of the following properties will be valid: OfAnyArray OfString OfFloat OfBool]

func (EventTransformCorrectedContentUnion) AsAnyArray

func (u EventTransformCorrectedContentUnion) AsAnyArray() (v []any)

func (EventTransformCorrectedContentUnion) AsBool

func (EventTransformCorrectedContentUnion) AsEventTransformCorrectedContentOutput

func (u EventTransformCorrectedContentUnion) AsEventTransformCorrectedContentOutput() (v EventTransformCorrectedContentOutput)

func (EventTransformCorrectedContentUnion) AsFloat

func (EventTransformCorrectedContentUnion) AsString

func (EventTransformCorrectedContentUnion) RawJSON

Returns the unmodified JSON received from the API

func (*EventTransformCorrectedContentUnion) UnmarshalJSON

func (r *EventTransformCorrectedContentUnion) UnmarshalJSON(data []byte) error

type EventTransformInput

type EventTransformInput struct {
	InputContent     string `json:"inputContent" api:"nullable"`
	InputType        string `json:"inputType" api:"nullable"`
	JsonInputContent any    `json:"jsonInputContent" api:"nullable"`
	S3URL            string `json:"s3URL" api:"nullable"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		InputContent     respjson.Field
		InputType        respjson.Field
		JsonInputContent respjson.Field
		S3URL            respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventTransformInput) RawJSON

func (r EventTransformInput) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventTransformInput) UnmarshalJSON

func (r *EventTransformInput) UnmarshalJSON(data []byte) error

type EventTransformMetadata

type EventTransformMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DurationFunctionToEventSeconds respjson.Field
		ExtraFields                    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventTransformMetadata) RawJSON

func (r EventTransformMetadata) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventTransformMetadata) UnmarshalJSON

func (r *EventTransformMetadata) UnmarshalJSON(data []byte) error

type EventTransformMetrics

type EventTransformMetrics struct {
	Differences []EventTransformMetricsDifference `json:"differences"`
	Metrics     EventTransformMetricsMetrics      `json:"metrics"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Differences respjson.Field
		Metrics     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Accuracy, precision, recall, and F1 score when corrected JSON is provided.

func (EventTransformMetrics) RawJSON

func (r EventTransformMetrics) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventTransformMetrics) UnmarshalJSON

func (r *EventTransformMetrics) UnmarshalJSON(data []byte) error

type EventTransformMetricsDifference

type EventTransformMetricsDifference struct {
	Category     string `json:"category"`
	CorrectedVal any    `json:"correctedVal"`
	ExtractedVal any    `json:"extractedVal"`
	JsonPointer  string `json:"jsonPointer"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Category     respjson.Field
		CorrectedVal respjson.Field
		ExtractedVal respjson.Field
		JsonPointer  respjson.Field
		ExtraFields  map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventTransformMetricsDifference) RawJSON

Returns the unmodified JSON received from the API

func (*EventTransformMetricsDifference) UnmarshalJSON

func (r *EventTransformMetricsDifference) UnmarshalJSON(data []byte) error

type EventTransformMetricsMetrics

type EventTransformMetricsMetrics struct {
	Accuracy  float64 `json:"accuracy"`
	F1Score   float64 `json:"f1Score"`
	Precision float64 `json:"precision"`
	Recall    float64 `json:"recall"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Accuracy    respjson.Field
		F1Score     respjson.Field
		Precision   respjson.Field
		Recall      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (EventTransformMetricsMetrics) RawJSON

Returns the unmodified JSON received from the API

func (*EventTransformMetricsMetrics) UnmarshalJSON

func (r *EventTransformMetricsMetrics) UnmarshalJSON(data []byte) error

type EventUnion

type EventUnion struct {
	EventID            string  `json:"eventID"`
	FunctionID         string  `json:"functionID"`
	FunctionName       string  `json:"functionName"`
	ItemCount          int64   `json:"itemCount"`
	ItemOffset         int64   `json:"itemOffset"`
	ReferenceID        string  `json:"referenceID"`
	TransformedContent any     `json:"transformedContent"`
	AvgConfidence      float64 `json:"avgConfidence"`
	CallID             string  `json:"callID"`
	// This field is a union of [EventTransformCorrectedContentUnion],
	// [EventExtractCorrectedContentUnion]
	CorrectedContent EventUnionCorrectedContent `json:"correctedContent"`
	CreatedAt        time.Time                  `json:"createdAt"`
	// Any of "transform", "extract", "route", "classify", "split_collection",
	// "split_item", "error", "join", "enrich", "collection_processing", "send".
	EventType             string `json:"eventType"`
	FieldConfidences      any    `json:"fieldConfidences"`
	FunctionCallID        string `json:"functionCallID"`
	FunctionCallTryNumber int64  `json:"functionCallTryNumber"`
	FunctionVersionNum    int64  `json:"functionVersionNum"`
	// This field is from variant [EventTransform].
	InboundEmail InboundEmailEvent `json:"inboundEmail"`
	// This field is a union of [[]EventTransformInput], [[]EventExtractInput]
	Inputs            EventUnionInputs `json:"inputs"`
	InputType         string           `json:"inputType"`
	InvalidProperties []string         `json:"invalidProperties"`
	// This field is from variant [EventTransform].
	IsRegression bool `json:"isRegression"`
	// This field is from variant [EventTransform].
	LastPublishErrorAt string `json:"lastPublishErrorAt"`
	// This field is a union of [EventTransformMetadata], [EventExtractMetadata],
	// [EventRouteMetadata], [EventClassifyMetadata], [EventSplitCollectionMetadata],
	// [EventSplitItemMetadata], [ErrorEventMetadata], [EventJoinMetadata],
	// [EventEnrichMetadata], [EventCollectionProcessingMetadata], [EventSendMetadata]
	Metadata EventUnionMetadata `json:"metadata"`
	// This field is from variant [EventTransform].
	Metrics EventTransformMetrics `json:"metrics"`
	// This field is from variant [EventTransform].
	OrderMatching bool `json:"orderMatching"`
	// This field is from variant [EventTransform].
	PipelineID string `json:"pipelineID"`
	// This field is from variant [EventTransform].
	PublishedAt        time.Time `json:"publishedAt"`
	S3URL              string    `json:"s3URL"`
	TransformationID   string    `json:"transformationID"`
	WorkflowID         string    `json:"workflowID"`
	WorkflowName       string    `json:"workflowName"`
	WorkflowVersionNum int64     `json:"workflowVersionNum"`
	// This field is from variant [EventExtract].
	FieldBoundingBoxes any    `json:"fieldBoundingBoxes"`
	Choice             string `json:"choice"`
	OutputType         string `json:"outputType"`
	// This field is a union of [EventSplitCollectionPrintPageOutput],
	// [EventSplitItemPrintPageOutput]
	PrintPageOutput EventUnionPrintPageOutput `json:"printPageOutput"`
	// This field is a union of [EventSplitCollectionSemanticPageOutput],
	// [EventSplitItemSemanticPageOutput]
	SemanticPageOutput EventUnionSemanticPageOutput `json:"semanticPageOutput"`
	// This field is from variant [ErrorEvent].
	Message string `json:"message"`
	// This field is from variant [EventJoin].
	Items []EventJoinItem `json:"items"`
	// This field is from variant [EventJoin].
	JoinType string `json:"joinType"`
	// This field is from variant [EventEnrich].
	EnrichedContent any `json:"enrichedContent"`
	// This field is from variant [EventCollectionProcessing].
	CollectionID string `json:"collectionID"`
	// This field is from variant [EventCollectionProcessing].
	CollectionName string `json:"collectionName"`
	// This field is from variant [EventCollectionProcessing].
	Operation string `json:"operation"`
	// This field is from variant [EventCollectionProcessing].
	ProcessedCount int64 `json:"processedCount"`
	// This field is from variant [EventCollectionProcessing].
	Status string `json:"status"`
	// This field is from variant [EventCollectionProcessing].
	CollectionItemIDs []string `json:"collectionItemIDs"`
	// This field is from variant [EventCollectionProcessing].
	ErrorMessage string `json:"errorMessage"`
	// This field is from variant [EventSend].
	DeliveryStatus string `json:"deliveryStatus"`
	// This field is from variant [EventSend].
	DestinationType string `json:"destinationType"`
	// This field is from variant [EventSend].
	DeliveredContent any `json:"deliveredContent"`
	// This field is from variant [EventSend].
	GoogleDriveOutput EventSendGoogleDriveOutput `json:"googleDriveOutput"`
	// This field is from variant [EventSend].
	S3Output EventSendS3Output `json:"s3Output"`
	// This field is from variant [EventSend].
	WebhookOutput EventSendWebhookOutput `json:"webhookOutput"`
	JSON          struct {
		EventID               respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		ItemCount             respjson.Field
		ItemOffset            respjson.Field
		ReferenceID           respjson.Field
		TransformedContent    respjson.Field
		AvgConfidence         respjson.Field
		CallID                respjson.Field
		CorrectedContent      respjson.Field
		CreatedAt             respjson.Field
		EventType             respjson.Field
		FieldConfidences      respjson.Field
		FunctionCallID        respjson.Field
		FunctionCallTryNumber respjson.Field
		FunctionVersionNum    respjson.Field
		InboundEmail          respjson.Field
		Inputs                respjson.Field
		InputType             respjson.Field
		InvalidProperties     respjson.Field
		IsRegression          respjson.Field
		LastPublishErrorAt    respjson.Field
		Metadata              respjson.Field
		Metrics               respjson.Field
		OrderMatching         respjson.Field
		PipelineID            respjson.Field
		PublishedAt           respjson.Field
		S3URL                 respjson.Field
		TransformationID      respjson.Field
		WorkflowID            respjson.Field
		WorkflowName          respjson.Field
		WorkflowVersionNum    respjson.Field
		FieldBoundingBoxes    respjson.Field
		Choice                respjson.Field
		OutputType            respjson.Field
		PrintPageOutput       respjson.Field
		SemanticPageOutput    respjson.Field
		Message               respjson.Field
		Items                 respjson.Field
		JoinType              respjson.Field
		EnrichedContent       respjson.Field
		CollectionID          respjson.Field
		CollectionName        respjson.Field
		Operation             respjson.Field
		ProcessedCount        respjson.Field
		Status                respjson.Field
		CollectionItemIDs     respjson.Field
		ErrorMessage          respjson.Field
		DeliveryStatus        respjson.Field
		DestinationType       respjson.Field
		DeliveredContent      respjson.Field
		GoogleDriveOutput     respjson.Field
		S3Output              respjson.Field
		WebhookOutput         respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

EventUnion contains all possible properties and values from EventTransform, EventExtract, EventRoute, EventClassify, EventSplitCollection, EventSplitItem, ErrorEvent, EventJoin, EventEnrich, EventCollectionProcessing, EventSend.

Use the EventUnion.AsAny method to switch on the variant.

Use the methods beginning with 'As' to cast the union to one of its variants.

func (EventUnion) AsAny

func (u EventUnion) AsAny() anyEvent

Use the following switch statement to find the correct variant

switch variant := EventUnion.AsAny().(type) {
case bem.EventTransform:
case bem.EventExtract:
case bem.EventRoute:
case bem.EventClassify:
case bem.EventSplitCollection:
case bem.EventSplitItem:
case bem.ErrorEvent:
case bem.EventJoin:
case bem.EventEnrich:
case bem.EventCollectionProcessing:
case bem.EventSend:
default:
  fmt.Errorf("no variant present")
}

func (EventUnion) AsClassify added in v0.10.0

func (u EventUnion) AsClassify() (v EventClassify)

func (EventUnion) AsCollectionProcessing

func (u EventUnion) AsCollectionProcessing() (v EventCollectionProcessing)

func (EventUnion) AsEnrich

func (u EventUnion) AsEnrich() (v EventEnrich)

func (EventUnion) AsError

func (u EventUnion) AsError() (v ErrorEvent)

func (EventUnion) AsExtract added in v0.10.0

func (u EventUnion) AsExtract() (v EventExtract)

func (EventUnion) AsJoin

func (u EventUnion) AsJoin() (v EventJoin)

func (EventUnion) AsRoute

func (u EventUnion) AsRoute() (v EventRoute)

func (EventUnion) AsSend

func (u EventUnion) AsSend() (v EventSend)

func (EventUnion) AsSplitCollection

func (u EventUnion) AsSplitCollection() (v EventSplitCollection)

func (EventUnion) AsSplitItem

func (u EventUnion) AsSplitItem() (v EventSplitItem)

func (EventUnion) AsTransform

func (u EventUnion) AsTransform() (v EventTransform)

func (EventUnion) RawJSON

func (u EventUnion) RawJSON() string

Returns the unmodified JSON received from the API

func (*EventUnion) UnmarshalJSON

func (r *EventUnion) UnmarshalJSON(data []byte) error

type EventUnionCorrectedContent added in v0.10.0

type EventUnionCorrectedContent struct {
	// This field will be present if the value is a [[]any] instead of an object.
	OfAnyArray []any `json:",inline"`
	// This field will be present if the value is a [string] instead of an object.
	OfString string `json:",inline"`
	// This field will be present if the value is a [float64] instead of an object.
	OfFloat float64 `json:",inline"`
	// This field will be present if the value is a [bool] instead of an object.
	OfBool bool           `json:",inline"`
	Output []AnyTypeUnion `json:"output"`
	JSON   struct {
		OfAnyArray respjson.Field
		OfString   respjson.Field
		OfFloat    respjson.Field
		OfBool     respjson.Field
		Output     respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

EventUnionCorrectedContent is an implicit subunion of EventUnion. EventUnionCorrectedContent provides convenient access to the sub-properties of the union.

For type safety it is recommended to directly use a variant of the EventUnion.

If the underlying value is not a json object, one of the following properties will be valid: OfAnyArray OfString OfFloat OfBool]

func (*EventUnionCorrectedContent) UnmarshalJSON added in v0.10.0

func (r *EventUnionCorrectedContent) UnmarshalJSON(data []byte) error

type EventUnionInputs added in v0.10.0

type EventUnionInputs struct {
	// This field will be present if the value is a [[]EventTransformInput] instead of
	// an object.
	OfEventTransformInputs []EventTransformInput `json:",inline"`
	// This field will be present if the value is a [[]EventExtractInput] instead of an
	// object.
	OfEventExtractInputs []EventExtractInput `json:",inline"`
	JSON                 struct {
		OfEventTransformInputs respjson.Field
		OfEventExtractInputs   respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

EventUnionInputs is an implicit subunion of EventUnion. EventUnionInputs provides convenient access to the sub-properties of the union.

For type safety it is recommended to directly use a variant of the EventUnion.

If the underlying value is not a json object, one of the following properties will be valid: OfEventTransformInputs OfEventExtractInputs]

func (*EventUnionInputs) UnmarshalJSON added in v0.10.0

func (r *EventUnionInputs) UnmarshalJSON(data []byte) error

type EventUnionMetadata

type EventUnionMetadata struct {
	DurationFunctionToEventSeconds float64 `json:"durationFunctionToEventSeconds"`
	JSON                           struct {
		DurationFunctionToEventSeconds respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

EventUnionMetadata is an implicit subunion of EventUnion. EventUnionMetadata provides convenient access to the sub-properties of the union.

For type safety it is recommended to directly use a variant of the EventUnion.

func (*EventUnionMetadata) UnmarshalJSON

func (r *EventUnionMetadata) UnmarshalJSON(data []byte) error

type EventUnionPrintPageOutput

type EventUnionPrintPageOutput struct {
	ItemCount int64 `json:"itemCount"`
	// This field is from variant [EventSplitCollectionPrintPageOutput].
	Items []EventSplitCollectionPrintPageOutputItem `json:"items"`
	// This field is from variant [EventSplitItemPrintPageOutput].
	CollectionReferenceID string `json:"collectionReferenceID"`
	// This field is from variant [EventSplitItemPrintPageOutput].
	ItemOffset int64 `json:"itemOffset"`
	// This field is from variant [EventSplitItemPrintPageOutput].
	S3URL string `json:"s3URL"`
	JSON  struct {
		ItemCount             respjson.Field
		Items                 respjson.Field
		CollectionReferenceID respjson.Field
		ItemOffset            respjson.Field
		S3URL                 respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

EventUnionPrintPageOutput is an implicit subunion of EventUnion. EventUnionPrintPageOutput provides convenient access to the sub-properties of the union.

For type safety it is recommended to directly use a variant of the EventUnion.

func (*EventUnionPrintPageOutput) UnmarshalJSON

func (r *EventUnionPrintPageOutput) UnmarshalJSON(data []byte) error

type EventUnionSemanticPageOutput

type EventUnionSemanticPageOutput struct {
	ItemCount int64 `json:"itemCount"`
	// This field is from variant [EventSplitCollectionSemanticPageOutput].
	Items     []EventSplitCollectionSemanticPageOutputItem `json:"items"`
	PageCount int64                                        `json:"pageCount"`
	// This field is from variant [EventSplitItemSemanticPageOutput].
	CollectionReferenceID string `json:"collectionReferenceID"`
	// This field is from variant [EventSplitItemSemanticPageOutput].
	ItemClass string `json:"itemClass"`
	// This field is from variant [EventSplitItemSemanticPageOutput].
	ItemClassCount int64 `json:"itemClassCount"`
	// This field is from variant [EventSplitItemSemanticPageOutput].
	ItemClassOffset int64 `json:"itemClassOffset"`
	// This field is from variant [EventSplitItemSemanticPageOutput].
	ItemOffset int64 `json:"itemOffset"`
	// This field is from variant [EventSplitItemSemanticPageOutput].
	PageEnd int64 `json:"pageEnd"`
	// This field is from variant [EventSplitItemSemanticPageOutput].
	PageStart int64 `json:"pageStart"`
	// This field is from variant [EventSplitItemSemanticPageOutput].
	S3URL string `json:"s3URL"`
	JSON  struct {
		ItemCount             respjson.Field
		Items                 respjson.Field
		PageCount             respjson.Field
		CollectionReferenceID respjson.Field
		ItemClass             respjson.Field
		ItemClassCount        respjson.Field
		ItemClassOffset       respjson.Field
		ItemOffset            respjson.Field
		PageEnd               respjson.Field
		PageStart             respjson.Field
		S3URL                 respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

EventUnionSemanticPageOutput is an implicit subunion of EventUnion. EventUnionSemanticPageOutput provides convenient access to the sub-properties of the union.

For type safety it is recommended to directly use a variant of the EventUnion.

func (*EventUnionSemanticPageOutput) UnmarshalJSON

func (r *EventUnionSemanticPageOutput) UnmarshalJSON(data []byte) error

type FNavigateParams added in v0.10.0

type FNavigateParams struct {
	// Operations exposed by `POST /v3/fs`.
	//
	// The verbs and their flag names mirror Unix tools so an LLM agent's existing
	// vocabulary maps directly:
	//
	// - `ls` — list parsed documents
	// - `cat` — read one parsed doc (optionally sliced by range / projected by select)
	// - `grep` — substring or regex search across parse outputs
	// - `head` — first N sections of one doc
	// - `stat` — metadata only (page count, section count, parsed at, ...)
	// - `find` — list canonical entities (cross-doc memory)
	// - `open` — entity + mentions
	// - `xref` — entity → sections across docs that mention it
	//
	// Doc-level ops (ls, cat, grep, head, stat) work on every parsed document,
	// regardless of how the parse function was configured.
	//
	// Memory-level ops (find, open, xref) operate on the global entities table which
	// is only populated when the parse function had `linkAcrossDocuments: true`. On
	// environments with no memory-linked docs they return empty data with a hint
	// pointing at the toggle.
	//
	// Any of "ls", "find", "open", "cat", "grep", "xref", "stat", "head".
	Op FNavigateParamsOp `json:"op,omitzero" api:"required"`
	// When true, return only the hit count without snippet payload. Cheaper than
	// fetching matches when the agent only wants a yes/no.
	CountOnly param.Opt[bool] `json:"countOnly,omitzero"`
	// Pagination cursor. Pass the last item's ID from a previous response
	// (`nextCursor`) to fetch the next page.
	Cursor param.Opt[string] `json:"cursor,omitzero"`
	// When true (default), substring/regex matching is case-insensitive.
	IgnoreCase param.Opt[bool] `json:"ignoreCase,omitzero"`
	// Maximum results to return. Defaults vary per op (25–50).
	Limit param.Opt[int64] `json:"limit,omitzero"`
	// First-N count for `op=head`. Defaults to 10.
	N param.Opt[int64] `json:"n,omitzero"`
	// Identifier for ops that operate on a single resource:
	//
	// - cat / head / stat: a parsed document, by `referenceID` or `transformationID`.
	// - open / xref / stat: an entity, by `entityID`.
	Path param.Opt[string] `json:"path,omitzero"`
	// Substring or regex pattern for `op=grep`.
	Pattern param.Opt[string] `json:"pattern,omitzero"`
	// When true, `pattern` is interpreted as a Go regex. Default false.
	Regex param.Opt[bool] `json:"regex,omitzero"`
	// Restricts grep to one part of the parse output. One of `"sections"`,
	// `"entities"`, `"relationships"`, `"all"` (default).
	Scope param.Opt[string] `json:"scope,omitzero"`
	// Filter options for `op=ls` and `op=find`.
	Filter FNavigateParamsFilter `json:"filter,omitzero"`
	// Slice the parse output along page or section dimensions. Used with `op=cat`.
	Range FNavigateParamsRange `json:"range,omitzero"`
	// Project the parse output to specific dotted paths (e.g.
	// `["sections.label", "sections.page"]`), letting an agent map a doc's structure
	// cheaply before reading content. Used with `op=cat`.
	Select []string `json:"select,omitzero"`
	// contains filtered or unexported fields
}

func (FNavigateParams) MarshalJSON added in v0.10.0

func (r FNavigateParams) MarshalJSON() (data []byte, err error)

func (*FNavigateParams) UnmarshalJSON added in v0.10.0

func (r *FNavigateParams) UnmarshalJSON(data []byte) error

type FNavigateParamsFilter added in v0.10.0

type FNavigateParamsFilter struct {
	// Match a parsed doc's source function name exactly.
	FunctionName param.Opt[string] `json:"functionName,omitzero"`
	// Substring match on canonical name (entities) or `referenceID` (parsed docs).
	// Case-insensitive.
	Search param.Opt[string] `json:"search,omitzero"`
	// Restrict to resources created at or after this timestamp.
	Since param.Opt[time.Time] `json:"since,omitzero" format:"date-time"`
	// Match an entity's `type` field exactly (e.g. `"drug"`, `"study"`).
	Type param.Opt[string] `json:"type,omitzero"`
	// contains filtered or unexported fields
}

Filter options for `op=ls` and `op=find`.

func (FNavigateParamsFilter) MarshalJSON added in v0.10.0

func (r FNavigateParamsFilter) MarshalJSON() (data []byte, err error)

func (*FNavigateParamsFilter) UnmarshalJSON added in v0.10.0

func (r *FNavigateParamsFilter) UnmarshalJSON(data []byte) error

type FNavigateParamsOp added in v0.10.0

type FNavigateParamsOp string

Operations exposed by `POST /v3/fs`.

The verbs and their flag names mirror Unix tools so an LLM agent's existing vocabulary maps directly:

- `ls` — list parsed documents - `cat` — read one parsed doc (optionally sliced by range / projected by select) - `grep` — substring or regex search across parse outputs - `head` — first N sections of one doc - `stat` — metadata only (page count, section count, parsed at, ...) - `find` — list canonical entities (cross-doc memory) - `open` — entity + mentions - `xref` — entity → sections across docs that mention it

Doc-level ops (ls, cat, grep, head, stat) work on every parsed document, regardless of how the parse function was configured.

Memory-level ops (find, open, xref) operate on the global entities table which is only populated when the parse function had `linkAcrossDocuments: true`. On environments with no memory-linked docs they return empty data with a hint pointing at the toggle.

const (
	FNavigateParamsOpLs   FNavigateParamsOp = "ls"
	FNavigateParamsOpFind FNavigateParamsOp = "find"
	FNavigateParamsOpOpen FNavigateParamsOp = "open"
	FNavigateParamsOpCat  FNavigateParamsOp = "cat"
	FNavigateParamsOpGrep FNavigateParamsOp = "grep"
	FNavigateParamsOpXref FNavigateParamsOp = "xref"
	FNavigateParamsOpStat FNavigateParamsOp = "stat"
	FNavigateParamsOpHead FNavigateParamsOp = "head"
)

type FNavigateParamsRange added in v0.10.0

type FNavigateParamsRange struct {
	// Restrict sections to one page (1-indexed).
	Page param.Opt[int64] `json:"page,omitzero"`
	// Restrict sections to an inclusive page range. Two-element array of `[from, to]`
	// (both 1-indexed).
	PageRange []int64 `json:"pageRange,omitzero"`
	// Keep only sections whose `type` matches one of these (e.g. `["table", "list"]`).
	SectionTypes []string `json:"sectionTypes,omitzero"`
	// contains filtered or unexported fields
}

Slice the parse output along page or section dimensions. Used with `op=cat`.

func (FNavigateParamsRange) MarshalJSON added in v0.10.0

func (r FNavigateParamsRange) MarshalJSON() (data []byte, err error)

func (*FNavigateParamsRange) UnmarshalJSON added in v0.10.0

func (r *FNavigateParamsRange) UnmarshalJSON(data []byte) error

type FNavigateResponse added in v0.10.0

type FNavigateResponse struct {
	// Op-specific payload. See per-op shapes below.
	Data any `json:"data" api:"required"`
	// Operations exposed by `POST /v3/fs`.
	//
	// The verbs and their flag names mirror Unix tools so an LLM agent's existing
	// vocabulary maps directly:
	//
	// - `ls` — list parsed documents
	// - `cat` — read one parsed doc (optionally sliced by range / projected by select)
	// - `grep` — substring or regex search across parse outputs
	// - `head` — first N sections of one doc
	// - `stat` — metadata only (page count, section count, parsed at, ...)
	// - `find` — list canonical entities (cross-doc memory)
	// - `open` — entity + mentions
	// - `xref` — entity → sections across docs that mention it
	//
	// Doc-level ops (ls, cat, grep, head, stat) work on every parsed document,
	// regardless of how the parse function was configured.
	//
	// Memory-level ops (find, open, xref) operate on the global entities table which
	// is only populated when the parse function had `linkAcrossDocuments: true`. On
	// environments with no memory-linked docs they return empty data with a hint
	// pointing at the toggle.
	//
	// Any of "ls", "find", "open", "cat", "grep", "xref", "stat", "head".
	Op FNavigateResponseOp `json:"op" api:"required"`
	// Set for ops that return a count rather than a list (`grep` with
	// `countOnly=true`) or as a sanity check on lists.
	Count int64 `json:"count"`
	// True when more pages exist for cursor-paginated ops.
	HasMore bool `json:"hasMore"`
	// Optional human-readable note. Surfaced on memory-level ops (`find` / `open` /
	// `xref`) when the corpus has no memory-linked docs, pointing users at the
	// `linkAcrossDocuments` toggle on the parse function.
	Hint string `json:"hint"`
	// Cursor to pass as `cursor` in the next request to fetch the next page. Empty
	// when `hasMore=false`.
	NextCursor string `json:"nextCursor"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Data        respjson.Field
		Op          respjson.Field
		Count       respjson.Field
		HasMore     respjson.Field
		Hint        respjson.Field
		NextCursor  respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Uniform response shape returned for every `op`. `data` is op-specific JSON (a list, an object, or a string), but the wrapper is constant so a client only learns one parse path.

func (FNavigateResponse) RawJSON added in v0.10.0

func (r FNavigateResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*FNavigateResponse) UnmarshalJSON added in v0.10.0

func (r *FNavigateResponse) UnmarshalJSON(data []byte) error

type FNavigateResponseOp added in v0.10.0

type FNavigateResponseOp string

Operations exposed by `POST /v3/fs`.

The verbs and their flag names mirror Unix tools so an LLM agent's existing vocabulary maps directly:

- `ls` — list parsed documents - `cat` — read one parsed doc (optionally sliced by range / projected by select) - `grep` — substring or regex search across parse outputs - `head` — first N sections of one doc - `stat` — metadata only (page count, section count, parsed at, ...) - `find` — list canonical entities (cross-doc memory) - `open` — entity + mentions - `xref` — entity → sections across docs that mention it

Doc-level ops (ls, cat, grep, head, stat) work on every parsed document, regardless of how the parse function was configured.

Memory-level ops (find, open, xref) operate on the global entities table which is only populated when the parse function had `linkAcrossDocuments: true`. On environments with no memory-linked docs they return empty data with a hint pointing at the toggle.

const (
	FNavigateResponseOpLs   FNavigateResponseOp = "ls"
	FNavigateResponseOpFind FNavigateResponseOp = "find"
	FNavigateResponseOpOpen FNavigateResponseOp = "open"
	FNavigateResponseOpCat  FNavigateResponseOp = "cat"
	FNavigateResponseOpGrep FNavigateResponseOp = "grep"
	FNavigateResponseOpXref FNavigateResponseOp = "xref"
	FNavigateResponseOpStat FNavigateResponseOp = "stat"
	FNavigateResponseOpHead FNavigateResponseOp = "head"
)

type FService added in v0.10.0

type FService struct {
	// contains filtered or unexported fields
}

Unix-shell-style nav over parsed documents and the cross-doc memory store.

`POST /v3/fs` is a single op-driven endpoint designed for LLM agents and programmatic consumers that want to walk a corpus the way they'd walk a filesystem.

## Doc-level ops (every parsed document)

- `ls` — list parsed documents with rich per-doc metadata. - `cat` — read one doc's parse JSON, sliced (`range`) or projected (`select`). - `head` — first N sections of one doc. - `grep` — substring or regex search; `scope`, `path`, `countOnly` available. - `stat` — metadata only (page/section/entity counts, timestamps).

## Memory-level ops (require `linkAcrossDocuments: true` on the parse function)

- `find` — list canonical entities across the corpus. - `open` — entity + mentions. - `xref` — for one entity, sections across docs that mention it (with content).

Memory ops return an empty list with a `hint` when no docs in this environment have been memory-linked.

## Pagination

List ops paginate by cursor — pass the previous response's `nextCursor` back as `cursor`; `hasMore: false` signals the last page. Same idiom as `/v3/calls` and `/v3/outputs`.

FService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewFService method instead.

func NewFService added in v0.10.0

func NewFService(opts ...option.RequestOption) (r FService)

NewFService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*FService) Navigate added in v0.10.0

func (r *FService) Navigate(ctx context.Context, body FNavigateParams, opts ...option.RequestOption) (res *FNavigateResponse, err error)

**Navigate parsed documents and the cross-doc memory store via Unix-shell verbs.**

`POST /v3/fs` is a single op-driven endpoint that lets an LLM agent (or any programmatic client) walk a corpus the way it would walk a filesystem — `ls` to list, `cat` to read, `grep` to search, `head` for a quick peek, `stat` for metadata, and `find` / `open` / `xref` for the cross-doc entity memory layer.

The body always carries an `op` field; other fields apply per op. The response envelope is uniform: `{op, data, hasMore?, nextCursor?, count?, hint?}`.

## Quick reference

| Op | `path` | Other fields | What it does | | ------ | ------------------------- | ------------------------------- | ----------------------------------------- | | `ls` | — | `filter`, `limit`, `cursor` | List parsed documents | | `grep` | referenceID _(optional)_ | `pattern`, `scope`, `countOnly` | Search across documents | | `cat` | referenceID | `range`, `select` | Read a document's parsed content | | `head` | referenceID | `n` | First N sections (default 10) | | `stat` | referenceID _or_ entityID | — | Metadata only | | `find` | — | `filter`, `limit`, `cursor` | List canonical entities | | `open` | entityID | — | Entity detail + all mentions | | `xref` | entityID | `limit`, `cursor` | Sections across docs mentioning an entity |

**`path`** is the positional identifier. For doc ops (`cat`, `head`, `stat`), pass a `referenceID` from `ls`. For entity ops (`open`, `xref`), pass an `entityID` from `find`. `grep` optionally takes a `path` to scope search to one document.

## Examples

**List documents:** `{"op": "ls"}`

**Search one document:** `{"op": "grep", "path": "my-doc-001", "pattern": "holiday", "scope": "sections"}`

**Read one page:** `{"op": "cat", "path": "my-doc-001", "range": {"page": 7}}`

**Read a page range:** `{"op": "cat", "path": "my-doc-001", "range": {"pageRange": [5, 10]}}`

**Project section labels and pages only:** `{"op": "cat", "path": "my-doc-001", "select": ["sections.label", "sections.page", "sections.type"]}`

**Preview first 5 sections:** `{"op": "head", "path": "my-doc-001", "n": 5}`

**Document metadata:** `{"op": "stat", "path": "my-doc-001"}`

**List entities:** `{"op": "find"}`

**Entity detail + mentions:** `{"op": "open", "path": "ent_abc123"}`

**Cross-document sections for an entity:** `{"op": "xref", "path": "ent_abc123"}`

## Key details

`range` is an **object** with optional keys: `page` (integer), `pageRange` (two-element array `[from, to]`), `sectionTypes` (array of strings like `["table", "heading"]`).

`select` is an **array of strings** — dotted paths like `["sections.label", "sections.page"]`.

`scope` (grep) is one of `"sections"`, `"entities"`, `"relationships"`, or `"all"` (default).

## Pagination

List ops (`ls`, `find`) paginate by cursor: pass the last item's `nextCursor` from a previous response to fetch the next page; `hasMore: false` signals the last page. Same idiom as `/v3/calls` and `/v3/outputs`.

type FunctionAnalyze

type FunctionAnalyze struct {
	// Whether bounding box extraction is enabled. Only applicable to analyze and
	// extract functions. When true, the function returns the document regions (page,
	// coordinates) from which each field was extracted.
	EnableBoundingBoxes bool `json:"enableBoundingBoxes" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema" api:"required"`
	// Name of output schema object.
	OutputSchemaName string `json:"outputSchemaName" api:"required"`
	// Reducing the risk of the model stopping early on long documents. Trade-off:
	// Increases total latency.
	PreCount bool             `json:"preCount" api:"required"`
	Type     constant.Analyze `json:"type" default:"analyze"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function.
	Audit FunctionAudit `json:"audit"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EnableBoundingBoxes respjson.Field
		FunctionID          respjson.Field
		FunctionName        respjson.Field
		OutputSchema        respjson.Field
		OutputSchemaName    respjson.Field
		PreCount            respjson.Field
		Type                respjson.Field
		VersionNum          respjson.Field
		Audit               respjson.Field
		DisplayName         respjson.Field
		Tags                respjson.Field
		UsedInWorkflows     respjson.Field
		ExtraFields         map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionAnalyze) RawJSON

func (r FunctionAnalyze) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionAnalyze) UnmarshalJSON

func (r *FunctionAnalyze) UnmarshalJSON(data []byte) error

type FunctionAudit

type FunctionAudit struct {
	// Information about who created the function.
	FunctionCreatedBy UserActionSummary `json:"functionCreatedBy"`
	// Information about who last updated the function.
	FunctionLastUpdatedBy UserActionSummary `json:"functionLastUpdatedBy"`
	// Information about who created the current version.
	VersionCreatedBy UserActionSummary `json:"versionCreatedBy"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		FunctionCreatedBy     respjson.Field
		FunctionLastUpdatedBy respjson.Field
		VersionCreatedBy      respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionAudit) RawJSON

func (r FunctionAudit) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionAudit) UnmarshalJSON

func (r *FunctionAudit) UnmarshalJSON(data []byte) error

type FunctionClassify added in v0.7.0

type FunctionClassify struct {
	// List of classifications a classify function can produce. Shares the underlying
	// route list shape.
	Classifications []ClassificationListItem `json:"classifications" api:"required"`
	// Description of classifier. Can be used to provide additional context on
	// classifier's purpose and expected inputs.
	Description string `json:"description" api:"required"`
	// Email address automatically created by bem. You can forward emails with or
	// without attachments, to be classified.
	EmailAddress string `json:"emailAddress" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string            `json:"functionName" api:"required"`
	Type         constant.Classify `json:"type" default:"classify"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function.
	Audit FunctionAudit `json:"audit"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Classifications respjson.Field
		Description     respjson.Field
		EmailAddress    respjson.Field
		FunctionID      respjson.Field
		FunctionName    respjson.Field
		Type            respjson.Field
		VersionNum      respjson.Field
		Audit           respjson.Field
		DisplayName     respjson.Field
		Tags            respjson.Field
		UsedInWorkflows respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionClassify) RawJSON added in v0.7.0

func (r FunctionClassify) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionClassify) UnmarshalJSON added in v0.7.0

func (r *FunctionClassify) UnmarshalJSON(data []byte) error

type FunctionCopyNewParams

type FunctionCopyNewParams struct {
	// Request to copy an existing function with a new name and optional
	// customizations.
	FunctionCopyRequest FunctionCopyRequestParam
	// contains filtered or unexported fields
}

func (FunctionCopyNewParams) MarshalJSON

func (r FunctionCopyNewParams) MarshalJSON() (data []byte, err error)

func (*FunctionCopyNewParams) UnmarshalJSON

func (r *FunctionCopyNewParams) UnmarshalJSON(data []byte) error

type FunctionCopyRequestParam

type FunctionCopyRequestParam struct {
	// Name of the function to copy from. Must be a valid existing function name.
	SourceFunctionName string `json:"sourceFunctionName" api:"required"`
	// Name for the new copied function. Must be unique within the target environment.
	TargetFunctionName string `json:"targetFunctionName" api:"required"`
	// Optional display name for the copied function. If not provided, defaults to the
	// source function's display name with " (Copy)" appended.
	TargetDisplayName param.Opt[string] `json:"targetDisplayName,omitzero"`
	// Optional environment name to copy the function to. If not provided, the function
	// will be copied within the same environment.
	TargetEnvironment param.Opt[string] `json:"targetEnvironment,omitzero"`
	// Optional array of tags for the copied function. If not provided, defaults to the
	// source function's tags.
	Tags []string `json:"tags,omitzero"`
	// contains filtered or unexported fields
}

Request to copy an existing function with a new name and optional customizations.

The properties SourceFunctionName, TargetFunctionName are required.

func (FunctionCopyRequestParam) MarshalJSON

func (r FunctionCopyRequestParam) MarshalJSON() (data []byte, err error)

func (*FunctionCopyRequestParam) UnmarshalJSON

func (r *FunctionCopyRequestParam) UnmarshalJSON(data []byte) error

type FunctionCopyService

type FunctionCopyService struct {
	// contains filtered or unexported fields
}

Functions are the core building blocks of data transformation in Bem. Each function type serves a specific purpose:

  • **Extract**: Extract structured JSON data from unstructured documents (PDFs, emails, images, spreadsheets), with optional layout-aware bounding-box extraction
  • **Route**: Direct data to different processing paths based on conditions
  • **Split**: Break multi-page documents into individual pages for parallel processing
  • **Join**: Combine outputs from multiple function calls into a single result
  • **Parse**: Render documents into a navigable structure of page-aware sections, named entities, and relationships — designed to be walked by an LLM agent via the [File System API](/api/v3/file-system) (`POST /v3/fs`). Two toggles, both `true` by default: `extractEntities` controls per-document entity and relationship extraction; `linkAcrossDocuments` merges entities into one canonical record per real-world thing across the environment, populating cross-document memory.
  • **Payload Shaping**: Transform and restructure data using JMESPath expressions
  • **Enrich**: Enhance data with semantic search against collections
  • **Send**: Deliver workflow outputs to downstream destinations

Use these endpoints to create, update, list, and manage your functions.

FunctionCopyService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewFunctionCopyService method instead.

func NewFunctionCopyService

func NewFunctionCopyService(opts ...option.RequestOption) (r FunctionCopyService)

NewFunctionCopyService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*FunctionCopyService) New

**Copy a function to a new name within the same environment.**

Forks the source function's current configuration into a brand-new function. The copy starts at `versionNum: 1` regardless of how many versions the source has — version history is not carried over.

Useful for experimenting with schema or prompt changes against a stable production function without disturbing existing callers.

The destination name must be unique in the environment. A copy does not migrate workflows: existing workflow nodes continue to reference the original function.

type FunctionEnrich

type FunctionEnrich struct {
	// Configuration for enrich function with semantic search steps.
	//
	// **How Enrich Functions Work:**
	//
	// Enrich functions use semantic search to augment JSON data with relevant
	// information from collections. They take JSON input (typically from a transform
	// function), extract specified fields, perform vector-based semantic search
	// against collections, and inject the results back into the data.
	//
	// **Input Requirements:**
	//
	// - Must receive JSON input (typically uploaded to S3 from a previous function)
	// - Can be chained after transform or other functions that produce JSON output
	//
	// **Example Use Cases:**
	//
	// - Match product descriptions to SKU codes from a product catalog
	// - Enrich customer data with account information
	// - Link order line items to inventory records
	//
	// **Configuration:**
	//
	// - Define one or more enrichment steps
	// - Each step extracts values, searches a collection, and injects results
	// - Steps are executed sequentially
	Config EnrichConfig `json:"config" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string          `json:"functionName" api:"required"`
	Type         constant.Enrich `json:"type" default:"enrich"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function.
	Audit FunctionAudit `json:"audit"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Config          respjson.Field
		FunctionID      respjson.Field
		FunctionName    respjson.Field
		Type            respjson.Field
		VersionNum      respjson.Field
		Audit           respjson.Field
		DisplayName     respjson.Field
		Tags            respjson.Field
		UsedInWorkflows respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionEnrich) RawJSON

func (r FunctionEnrich) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionEnrich) UnmarshalJSON

func (r *FunctionEnrich) UnmarshalJSON(data []byte) error

type FunctionExtract added in v0.2.0

type FunctionExtract struct {
	// Whether bounding box extraction is enabled. Applies to vision input types (pdf,
	// png, jpeg, heic, heif, webp) that dispatch through the analyze path. When true,
	// the function returns the document regions (page, coordinates) from which each
	// field was extracted.
	EnableBoundingBoxes bool `json:"enableBoundingBoxes" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema" api:"required"`
	// Name of output schema object.
	OutputSchemaName string `json:"outputSchemaName" api:"required"`
	// Reducing the risk of the model stopping early on long documents. Trade-off:
	// Increases total latency.
	PreCount bool             `json:"preCount" api:"required"`
	Type     constant.Extract `json:"type" default:"extract"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function.
	Audit FunctionAudit `json:"audit"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EnableBoundingBoxes respjson.Field
		FunctionID          respjson.Field
		FunctionName        respjson.Field
		OutputSchema        respjson.Field
		OutputSchemaName    respjson.Field
		PreCount            respjson.Field
		Type                respjson.Field
		VersionNum          respjson.Field
		Audit               respjson.Field
		DisplayName         respjson.Field
		Tags                respjson.Field
		UsedInWorkflows     respjson.Field
		ExtraFields         map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A function that extracts structured JSON from documents and images. Accepts a wide range of input types including PDFs, images, spreadsheets, emails, and more.

func (FunctionExtract) RawJSON added in v0.2.0

func (r FunctionExtract) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionExtract) UnmarshalJSON added in v0.2.0

func (r *FunctionExtract) UnmarshalJSON(data []byte) error

type FunctionJoin

type FunctionJoin struct {
	// Description of join function.
	Description string `json:"description" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// The type of join to perform.
	//
	// Any of "standard".
	JoinType string `json:"joinType" api:"required"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema" api:"required"`
	// Name of output schema object.
	OutputSchemaName string        `json:"outputSchemaName" api:"required"`
	Type             constant.Join `json:"type" default:"join"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function.
	Audit FunctionAudit `json:"audit"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Description      respjson.Field
		FunctionID       respjson.Field
		FunctionName     respjson.Field
		JoinType         respjson.Field
		OutputSchema     respjson.Field
		OutputSchemaName respjson.Field
		Type             respjson.Field
		VersionNum       respjson.Field
		Audit            respjson.Field
		DisplayName      respjson.Field
		Tags             respjson.Field
		UsedInWorkflows  respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionJoin) RawJSON

func (r FunctionJoin) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionJoin) UnmarshalJSON

func (r *FunctionJoin) UnmarshalJSON(data []byte) error

type FunctionListParams

type FunctionListParams struct {
	DisplayName   param.Opt[string] `query:"displayName,omitzero" json:"-"`
	EndingBefore  param.Opt[string] `query:"endingBefore,omitzero" json:"-"`
	Limit         param.Opt[int64]  `query:"limit,omitzero" json:"-"`
	StartingAfter param.Opt[string] `query:"startingAfter,omitzero" json:"-"`
	FunctionIDs   []string          `query:"functionIDs,omitzero" json:"-"`
	FunctionNames []string          `query:"functionNames,omitzero" json:"-"`
	// Any of "asc", "desc".
	SortOrder     FunctionListParamsSortOrder `query:"sortOrder,omitzero" json:"-"`
	Tags          []string                    `query:"tags,omitzero" json:"-"`
	Types         []FunctionType              `query:"types,omitzero" json:"-"`
	WorkflowIDs   []string                    `query:"workflowIDs,omitzero" json:"-"`
	WorkflowNames []string                    `query:"workflowNames,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (FunctionListParams) URLQuery

func (r FunctionListParams) URLQuery() (v url.Values, err error)

URLQuery serializes FunctionListParams's query parameters as `url.Values`.

type FunctionListParamsSortOrder

type FunctionListParamsSortOrder string
const (
	FunctionListParamsSortOrderAsc  FunctionListParamsSortOrder = "asc"
	FunctionListParamsSortOrderDesc FunctionListParamsSortOrder = "desc"
)

type FunctionNewParams

type FunctionNewParams struct {
	// V3 wire form of the classify function create payload.
	CreateFunction CreateFunctionUnionParam
	// contains filtered or unexported fields
}

func (FunctionNewParams) MarshalJSON

func (r FunctionNewParams) MarshalJSON() (data []byte, err error)

func (*FunctionNewParams) UnmarshalJSON

func (r *FunctionNewParams) UnmarshalJSON(data []byte) error

type FunctionParse added in v0.10.0

type FunctionParse struct {
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string         `json:"functionName" api:"required"`
	Type         constant.Parse `json:"type" default:"parse"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function.
	Audit FunctionAudit `json:"audit"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Per-version configuration for a Parse function.
	//
	// Parse renders document pages (PDF, image) via vision LLM and emits structured
	// JSON. The two toggles below independently control entity extraction (a per-call
	// output concern) and cross-document memory linking (an environment-wide concern).
	ParseConfig FunctionParseParseConfig `json:"parseConfig"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		FunctionID      respjson.Field
		FunctionName    respjson.Field
		Type            respjson.Field
		VersionNum      respjson.Field
		Audit           respjson.Field
		DisplayName     respjson.Field
		ParseConfig     respjson.Field
		Tags            respjson.Field
		UsedInWorkflows respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionParse) RawJSON added in v0.10.0

func (r FunctionParse) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionParse) UnmarshalJSON added in v0.10.0

func (r *FunctionParse) UnmarshalJSON(data []byte) error

type FunctionParseParseConfig added in v0.10.0

type FunctionParseParseConfig struct {
	// When true, extract named entities (people, organizations, products, studies,
	// identifiers, etc.) and the relationships between them, and dedupe by canonical
	// name within the document. When false, only `sections[]` is extracted;
	// `entities[]` and `relationships[]` come back empty in the parse output. Defaults
	// to true.
	ExtractEntities bool `json:"extractEntities"`
	// When true, link this document's entities to entities seen in earlier documents
	// in this environment, building one canonical record per real-world thing across
	// the corpus. Visible in the Memory tab and queryable via `POST /v3/fs` (op=find /
	// open / xref). Doesn't change this call's parse output. Requires
	// `extractEntities=true`. Defaults to true.
	LinkAcrossDocuments bool `json:"linkAcrossDocuments"`
	// Optional JSONSchema. When provided, each chunk performs schema-guided
	// extraction. When absent, chunks perform open-ended discovery and return
	// sections, entities, and relationships per the discovery schema.
	Schema any `json:"schema"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ExtractEntities     respjson.Field
		LinkAcrossDocuments respjson.Field
		Schema              respjson.Field
		ExtraFields         map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Per-version configuration for a Parse function.

Parse renders document pages (PDF, image) via vision LLM and emits structured JSON. The two toggles below independently control entity extraction (a per-call output concern) and cross-document memory linking (an environment-wide concern).

func (FunctionParseParseConfig) RawJSON added in v0.10.0

func (r FunctionParseParseConfig) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionParseParseConfig) UnmarshalJSON added in v0.10.0

func (r *FunctionParseParseConfig) UnmarshalJSON(data []byte) error

type FunctionPayloadShaping

type FunctionPayloadShaping struct {
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// JMESPath expression that defines how to transform and customize the input
	// payload structure. Payload shaping allows you to extract, reshape, and
	// reorganize data from complex input payloads into a simplified, standardized
	// output format. Use JMESPath syntax to select specific fields, perform
	// calculations, and create new data structures tailored to your needs.
	ShapingSchema string                  `json:"shapingSchema" api:"required"`
	Type          constant.PayloadShaping `json:"type" default:"payload_shaping"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function.
	Audit FunctionAudit `json:"audit"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		FunctionID      respjson.Field
		FunctionName    respjson.Field
		ShapingSchema   respjson.Field
		Type            respjson.Field
		VersionNum      respjson.Field
		Audit           respjson.Field
		DisplayName     respjson.Field
		Tags            respjson.Field
		UsedInWorkflows respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A function that transforms and customizes input payloads using JMESPath expressions. Payload shaping allows you to extract specific data, perform calculations, and reshape complex input structures into simplified, standardized output formats tailored to your downstream systems or business requirements.

func (FunctionPayloadShaping) RawJSON

func (r FunctionPayloadShaping) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionPayloadShaping) UnmarshalJSON

func (r *FunctionPayloadShaping) UnmarshalJSON(data []byte) error

type FunctionResponse

type FunctionResponse struct {
	// V3 read-side union. Same shape as the shared `Function` union but with
	// `classify` in place of `route`. Legacy `transform` and `analyze` functions
	// remain readable via V3.
	Function FunctionUnion `json:"function" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Function    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Single-function response wrapper used by V3 function endpoints. V3 wraps individual function responses in a `{"function": ...}` envelope for consistency with other V3 resource endpoints.

func (FunctionResponse) RawJSON

func (r FunctionResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionResponse) UnmarshalJSON

func (r *FunctionResponse) UnmarshalJSON(data []byte) error

type FunctionSend

type FunctionSend struct {
	// Destination type for a Send function.
	//
	// Any of "webhook", "s3", "google_drive".
	DestinationType string `json:"destinationType" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string        `json:"functionName" api:"required"`
	Type         constant.Send `json:"type" default:"send"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function.
	Audit FunctionAudit `json:"audit"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Google Drive folder ID. Present when destinationType is google_drive. Managed
	// via Paragon OAuth.
	GoogleDriveFolderID string `json:"googleDriveFolderId"`
	// S3 bucket to upload the payload to. Present when destinationType is s3.
	S3Bucket string `json:"s3Bucket"`
	// S3 key prefix (folder path). Optional, present when destinationType is s3.
	S3Prefix string `json:"s3Prefix"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// Whether webhook payloads are signed with an HMAC-SHA256 `bem-signature` header.
	WebhookSigningEnabled bool `json:"webhookSigningEnabled"`
	// Webhook URL to POST the payload to. Present when destinationType is webhook.
	WebhookURL string `json:"webhookUrl"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DestinationType       respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		Type                  respjson.Field
		VersionNum            respjson.Field
		Audit                 respjson.Field
		DisplayName           respjson.Field
		GoogleDriveFolderID   respjson.Field
		S3Bucket              respjson.Field
		S3Prefix              respjson.Field
		Tags                  respjson.Field
		UsedInWorkflows       respjson.Field
		WebhookSigningEnabled respjson.Field
		WebhookURL            respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A function that delivers workflow outputs to an external destination. Send functions receive the output of an upstream workflow node and forward it to a webhook, S3 bucket, or Google Drive folder.

func (FunctionSend) RawJSON

func (r FunctionSend) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionSend) UnmarshalJSON

func (r *FunctionSend) UnmarshalJSON(data []byte) error

type FunctionService

type FunctionService struct {

	// Functions are the core building blocks of data transformation in Bem. Each
	// function type serves a specific purpose:
	//
	//   - **Extract**: Extract structured JSON data from unstructured documents (PDFs,
	//     emails, images, spreadsheets), with optional layout-aware bounding-box
	//     extraction
	//   - **Route**: Direct data to different processing paths based on conditions
	//   - **Split**: Break multi-page documents into individual pages for parallel
	//     processing
	//   - **Join**: Combine outputs from multiple function calls into a single result
	//   - **Parse**: Render documents into a navigable structure of page-aware sections,
	//     named entities, and relationships — designed to be walked by an LLM agent via
	//     the [File System API](/api/v3/file-system) (`POST /v3/fs`). Two toggles, both
	//     `true` by default: `extractEntities` controls per-document entity and
	//     relationship extraction; `linkAcrossDocuments` merges entities into one
	//     canonical record per real-world thing across the environment, populating
	//     cross-document memory.
	//   - **Payload Shaping**: Transform and restructure data using JMESPath expressions
	//   - **Enrich**: Enhance data with semantic search against collections
	//   - **Send**: Deliver workflow outputs to downstream destinations
	//
	// Use these endpoints to create, update, list, and manage your functions.
	Copy FunctionCopyService
	// Functions are the core building blocks of data transformation in Bem. Each
	// function type serves a specific purpose:
	//
	//   - **Extract**: Extract structured JSON data from unstructured documents (PDFs,
	//     emails, images, spreadsheets), with optional layout-aware bounding-box
	//     extraction
	//   - **Route**: Direct data to different processing paths based on conditions
	//   - **Split**: Break multi-page documents into individual pages for parallel
	//     processing
	//   - **Join**: Combine outputs from multiple function calls into a single result
	//   - **Parse**: Render documents into a navigable structure of page-aware sections,
	//     named entities, and relationships — designed to be walked by an LLM agent via
	//     the [File System API](/api/v3/file-system) (`POST /v3/fs`). Two toggles, both
	//     `true` by default: `extractEntities` controls per-document entity and
	//     relationship extraction; `linkAcrossDocuments` merges entities into one
	//     canonical record per real-world thing across the environment, populating
	//     cross-document memory.
	//   - **Payload Shaping**: Transform and restructure data using JMESPath expressions
	//   - **Enrich**: Enhance data with semantic search against collections
	//   - **Send**: Deliver workflow outputs to downstream destinations
	//
	// Use these endpoints to create, update, list, and manage your functions.
	Versions FunctionVersionService
	// contains filtered or unexported fields
}

Functions are the core building blocks of data transformation in Bem. Each function type serves a specific purpose:

  • **Extract**: Extract structured JSON data from unstructured documents (PDFs, emails, images, spreadsheets), with optional layout-aware bounding-box extraction
  • **Route**: Direct data to different processing paths based on conditions
  • **Split**: Break multi-page documents into individual pages for parallel processing
  • **Join**: Combine outputs from multiple function calls into a single result
  • **Parse**: Render documents into a navigable structure of page-aware sections, named entities, and relationships — designed to be walked by an LLM agent via the [File System API](/api/v3/file-system) (`POST /v3/fs`). Two toggles, both `true` by default: `extractEntities` controls per-document entity and relationship extraction; `linkAcrossDocuments` merges entities into one canonical record per real-world thing across the environment, populating cross-document memory.
  • **Payload Shaping**: Transform and restructure data using JMESPath expressions
  • **Enrich**: Enhance data with semantic search against collections
  • **Send**: Deliver workflow outputs to downstream destinations

Use these endpoints to create, update, list, and manage your functions.

FunctionService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewFunctionService method instead.

func NewFunctionService

func NewFunctionService(opts ...option.RequestOption) (r FunctionService)

NewFunctionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*FunctionService) Delete

func (r *FunctionService) Delete(ctx context.Context, functionName string, opts ...option.RequestOption) (err error)

**Delete a function and every one of its versions.**

Permanent. Running and queued calls that reference this function continue to completion against the version they captured at call time, but no new calls can target it.

## Before deleting

Workflow nodes that reference this function will fail at call time after deletion. List workflows that reference it first:

``` GET /v3/workflows?functionNames=my-function ```

Update or remove those workflows, or create a replacement function and re-point the workflow nodes, before deleting.

func (*FunctionService) Get

func (r *FunctionService) Get(ctx context.Context, functionName string, opts ...option.RequestOption) (res *FunctionResponse, err error)

**Retrieve a function's current version by name.**

Returns the function record with its `currentVersionNum` and the configuration of that version. To inspect a historical version, use `GET /v3/functions/{functionName}/versions/{versionNum}`.

func (*FunctionService) List

**List functions in the current environment.**

Returns each function's current version. Combine filters freely — they AND together.

## Filtering

  • `functionIDs` / `functionNames`: exact-match identity filters.
  • `displayName`: case-insensitive substring match.
  • `types`: one or more of `extract`, `classify`, `split`, `join`, `enrich`, `payload_shaping`. Legacy `transform`, `analyze`, `route`, and `send` types remain readable via this filter.
  • `tags`: returns functions tagged with any of the supplied tags.
  • `workflowIDs` / `workflowNames`: returns only functions referenced by the named workflows. Useful for "what functions does this workflow depend on?" lookups.

## Pagination

Cursor-based with `startingAfter` and `endingBefore` (functionIDs). Default limit 50, maximum 100.

func (*FunctionService) ListAutoPaging

**List functions in the current environment.**

Returns each function's current version. Combine filters freely — they AND together.

## Filtering

  • `functionIDs` / `functionNames`: exact-match identity filters.
  • `displayName`: case-insensitive substring match.
  • `types`: one or more of `extract`, `classify`, `split`, `join`, `enrich`, `payload_shaping`. Legacy `transform`, `analyze`, `route`, and `send` types remain readable via this filter.
  • `tags`: returns functions tagged with any of the supplied tags.
  • `workflowIDs` / `workflowNames`: returns only functions referenced by the named workflows. Useful for "what functions does this workflow depend on?" lookups.

## Pagination

Cursor-based with `startingAfter` and `endingBefore` (functionIDs). Default limit 50, maximum 100.

func (*FunctionService) New

**Create a function.**

The function type (`extract`, `classify`, `split`, `join`, `enrich`, or `payload_shaping`) determines which configuration fields are required — see [Function types overview](/guide/function-types/overview) for the per-type contract.

The response contains both `functionID` and `functionName`. Either is a stable handle you can use elsewhere; most workflows reference functions by `functionName` because it's human-readable.

## Naming rules

  • `functionName` must be unique per environment.
  • Allowed characters: letters, digits, hyphens, and underscores.
  • Names cannot be reused after deletion within the same environment for at least the retention window of the previous record.

The new function is created at `versionNum: 1`. Subsequent `PATCH /v3/functions/{functionName}` calls produce new versions — the version-1 configuration remains immutable and addressable.

func (*FunctionService) Update

func (r *FunctionService) Update(ctx context.Context, pathFunctionName string, body FunctionUpdateParams, opts ...option.RequestOption) (res *FunctionResponse, err error)

**Update a function. Updates create a new version.**

The previous version remains addressable and immutable. Workflow nodes that pinned the function with a `versionNum` continue to use the pinned version; nodes that reference the function by name with no version automatically pick up the new version on their next call.

## What you can change

Any field allowed by the function's type. Most commonly: `outputSchema` (for `extract`/`join`), `classifications` (for `classify`), `displayName`, and `tags`.

## Versioning behaviour

  • Each successful update increments `currentVersionNum` by 1.
  • `displayName`, `tags`, and `functionName` updates also create a new version, so the version history is a complete record of every change.
  • To revert, fetch the previous version and re-submit its configuration as a new update — versions themselves are immutable.

type FunctionSplit

type FunctionSplit struct {
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// The method used to split pages.
	//
	// Any of "print_page", "semantic_page".
	SplitType string         `json:"splitType" api:"required"`
	Type      constant.Split `json:"type" default:"split"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function.
	Audit FunctionAudit `json:"audit"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Configuration for print page splitting.
	PrintPageSplitConfig FunctionSplitPrintPageSplitConfig `json:"printPageSplitConfig"`
	// Configuration for semantic page splitting.
	SemanticPageSplitConfig FunctionSplitSemanticPageSplitConfig `json:"semanticPageSplitConfig"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		FunctionID              respjson.Field
		FunctionName            respjson.Field
		SplitType               respjson.Field
		Type                    respjson.Field
		VersionNum              respjson.Field
		Audit                   respjson.Field
		DisplayName             respjson.Field
		PrintPageSplitConfig    respjson.Field
		SemanticPageSplitConfig respjson.Field
		Tags                    respjson.Field
		UsedInWorkflows         respjson.Field
		ExtraFields             map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionSplit) RawJSON

func (r FunctionSplit) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionSplit) UnmarshalJSON

func (r *FunctionSplit) UnmarshalJSON(data []byte) error

type FunctionSplitPrintPageSplitConfig

type FunctionSplitPrintPageSplitConfig struct {
	NextFunctionID string `json:"nextFunctionID"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		NextFunctionID respjson.Field
		ExtraFields    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Configuration for print page splitting.

func (FunctionSplitPrintPageSplitConfig) RawJSON

Returns the unmodified JSON received from the API

func (*FunctionSplitPrintPageSplitConfig) UnmarshalJSON

func (r *FunctionSplitPrintPageSplitConfig) UnmarshalJSON(data []byte) error

type FunctionSplitSemanticPageSplitConfig

type FunctionSplitSemanticPageSplitConfig struct {
	ItemClasses []SplitFunctionSemanticPageItemClass `json:"itemClasses"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ItemClasses respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Configuration for semantic page splitting.

func (FunctionSplitSemanticPageSplitConfig) RawJSON

Returns the unmodified JSON received from the API

func (*FunctionSplitSemanticPageSplitConfig) UnmarshalJSON

func (r *FunctionSplitSemanticPageSplitConfig) UnmarshalJSON(data []byte) error

type FunctionTransform

type FunctionTransform struct {
	// Email address automatically created by bem. You can forward emails with or
	// without attachments, to be transformed.
	EmailAddress string `json:"emailAddress" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema" api:"required"`
	// Name of output schema object.
	OutputSchemaName string `json:"outputSchemaName" api:"required"`
	// Whether tabular chunking is enabled on the pipeline. This processes tables in
	// CSV/Excel in row batches, rather than all rows at once.
	TabularChunkingEnabled bool               `json:"tabularChunkingEnabled" api:"required"`
	Type                   constant.Transform `json:"type" default:"transform"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function.
	Audit FunctionAudit `json:"audit"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EmailAddress           respjson.Field
		FunctionID             respjson.Field
		FunctionName           respjson.Field
		OutputSchema           respjson.Field
		OutputSchemaName       respjson.Field
		TabularChunkingEnabled respjson.Field
		Type                   respjson.Field
		VersionNum             respjson.Field
		Audit                  respjson.Field
		DisplayName            respjson.Field
		Tags                   respjson.Field
		UsedInWorkflows        respjson.Field
		ExtraFields            map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionTransform) RawJSON

func (r FunctionTransform) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionTransform) UnmarshalJSON

func (r *FunctionTransform) UnmarshalJSON(data []byte) error

type FunctionType

type FunctionType string

The type of the function.

const (
	FunctionTypeTransform      FunctionType = "transform"
	FunctionTypeExtract        FunctionType = "extract"
	FunctionTypeRoute          FunctionType = "route"
	FunctionTypeClassify       FunctionType = "classify"
	FunctionTypeSend           FunctionType = "send"
	FunctionTypeSplit          FunctionType = "split"
	FunctionTypeJoin           FunctionType = "join"
	FunctionTypeAnalyze        FunctionType = "analyze"
	FunctionTypePayloadShaping FunctionType = "payload_shaping"
	FunctionTypeEnrich         FunctionType = "enrich"
	FunctionTypeParse          FunctionType = "parse"
)

type FunctionUnion

type FunctionUnion struct {
	EmailAddress     string `json:"emailAddress"`
	FunctionID       string `json:"functionID"`
	FunctionName     string `json:"functionName"`
	OutputSchema     any    `json:"outputSchema"`
	OutputSchemaName string `json:"outputSchemaName"`
	// This field is from variant [FunctionTransform].
	TabularChunkingEnabled bool `json:"tabularChunkingEnabled"`
	// Any of "transform", "extract", "analyze", "classify", "send", "split", "join",
	// "payload_shaping", "enrich", "parse".
	Type       string `json:"type"`
	VersionNum int64  `json:"versionNum"`
	// This field is from variant [FunctionTransform].
	Audit               FunctionAudit       `json:"audit"`
	DisplayName         string              `json:"displayName"`
	Tags                []string            `json:"tags"`
	UsedInWorkflows     []WorkflowUsageInfo `json:"usedInWorkflows"`
	EnableBoundingBoxes bool                `json:"enableBoundingBoxes"`
	PreCount            bool                `json:"preCount"`
	// This field is from variant [FunctionClassify].
	Classifications []ClassificationListItem `json:"classifications"`
	Description     string                   `json:"description"`
	// This field is from variant [FunctionSend].
	DestinationType string `json:"destinationType"`
	// This field is from variant [FunctionSend].
	GoogleDriveFolderID string `json:"googleDriveFolderId"`
	// This field is from variant [FunctionSend].
	S3Bucket string `json:"s3Bucket"`
	// This field is from variant [FunctionSend].
	S3Prefix string `json:"s3Prefix"`
	// This field is from variant [FunctionSend].
	WebhookSigningEnabled bool `json:"webhookSigningEnabled"`
	// This field is from variant [FunctionSend].
	WebhookURL string `json:"webhookUrl"`
	// This field is from variant [FunctionSplit].
	SplitType string `json:"splitType"`
	// This field is from variant [FunctionSplit].
	PrintPageSplitConfig FunctionSplitPrintPageSplitConfig `json:"printPageSplitConfig"`
	// This field is from variant [FunctionSplit].
	SemanticPageSplitConfig FunctionSplitSemanticPageSplitConfig `json:"semanticPageSplitConfig"`
	// This field is from variant [FunctionJoin].
	JoinType string `json:"joinType"`
	// This field is from variant [FunctionPayloadShaping].
	ShapingSchema string `json:"shapingSchema"`
	// This field is from variant [FunctionEnrich].
	Config EnrichConfig `json:"config"`
	// This field is from variant [FunctionParse].
	ParseConfig FunctionParseParseConfig `json:"parseConfig"`
	JSON        struct {
		EmailAddress            respjson.Field
		FunctionID              respjson.Field
		FunctionName            respjson.Field
		OutputSchema            respjson.Field
		OutputSchemaName        respjson.Field
		TabularChunkingEnabled  respjson.Field
		Type                    respjson.Field
		VersionNum              respjson.Field
		Audit                   respjson.Field
		DisplayName             respjson.Field
		Tags                    respjson.Field
		UsedInWorkflows         respjson.Field
		EnableBoundingBoxes     respjson.Field
		PreCount                respjson.Field
		Classifications         respjson.Field
		Description             respjson.Field
		DestinationType         respjson.Field
		GoogleDriveFolderID     respjson.Field
		S3Bucket                respjson.Field
		S3Prefix                respjson.Field
		WebhookSigningEnabled   respjson.Field
		WebhookURL              respjson.Field
		SplitType               respjson.Field
		PrintPageSplitConfig    respjson.Field
		SemanticPageSplitConfig respjson.Field
		JoinType                respjson.Field
		ShapingSchema           respjson.Field
		Config                  respjson.Field
		ParseConfig             respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

FunctionUnion contains all possible properties and values from FunctionTransform, FunctionExtract, FunctionAnalyze, FunctionClassify, FunctionSend, FunctionSplit, FunctionJoin, FunctionPayloadShaping, FunctionEnrich, FunctionParse.

Use the FunctionUnion.AsAny method to switch on the variant.

Use the methods beginning with 'As' to cast the union to one of its variants.

func (FunctionUnion) AsAnalyze

func (u FunctionUnion) AsAnalyze() (v FunctionAnalyze)

func (FunctionUnion) AsAny

func (u FunctionUnion) AsAny() anyFunction

Use the following switch statement to find the correct variant

switch variant := FunctionUnion.AsAny().(type) {
case bem.FunctionTransform:
case bem.FunctionExtract:
case bem.FunctionAnalyze:
case bem.FunctionClassify:
case bem.FunctionSend:
case bem.FunctionSplit:
case bem.FunctionJoin:
case bem.FunctionPayloadShaping:
case bem.FunctionEnrich:
case bem.FunctionParse:
default:
  fmt.Errorf("no variant present")
}

func (FunctionUnion) AsClassify added in v0.7.0

func (u FunctionUnion) AsClassify() (v FunctionClassify)

func (FunctionUnion) AsEnrich

func (u FunctionUnion) AsEnrich() (v FunctionEnrich)

func (FunctionUnion) AsExtract added in v0.2.0

func (u FunctionUnion) AsExtract() (v FunctionExtract)

func (FunctionUnion) AsJoin

func (u FunctionUnion) AsJoin() (v FunctionJoin)

func (FunctionUnion) AsParse added in v0.10.0

func (u FunctionUnion) AsParse() (v FunctionParse)

func (FunctionUnion) AsPayloadShaping

func (u FunctionUnion) AsPayloadShaping() (v FunctionPayloadShaping)

func (FunctionUnion) AsSend

func (u FunctionUnion) AsSend() (v FunctionSend)

func (FunctionUnion) AsSplit

func (u FunctionUnion) AsSplit() (v FunctionSplit)

func (FunctionUnion) AsTransform

func (u FunctionUnion) AsTransform() (v FunctionTransform)

func (FunctionUnion) RawJSON

func (u FunctionUnion) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionUnion) UnmarshalJSON

func (r *FunctionUnion) UnmarshalJSON(data []byte) error

type FunctionUpdateParams

type FunctionUpdateParams struct {
	// V3 create/update variants of the shared function payloads.
	//
	// The V3 Functions API no longer accepts the legacy `transform` or `analyze`
	// function types when creating new functions or updating existing ones — both have
	// been unified under `extract`. Existing functions of those types remain readable
	// and callable via V3, so the V3 read-side unions still include `transform` and
	// `analyze` variants.
	//
	// The V3 API also exposes `classify` in place of the legacy `route` type on
	// create/update, with `classifications` in place of `routes`. Read-side
	// `ClassifyFunction` / `ClassifyFunctionVersion` / `ClassificationList` are
	// defined in the shared functions models and used by both the V2 and V3 response
	// unions (existing classify functions are returned from V2 GET endpoints
	// verbatim).V3 wire form of the classify function upsert payload.
	UpdateFunction UpdateFunctionUnionParam
	// contains filtered or unexported fields
}

func (FunctionUpdateParams) MarshalJSON

func (r FunctionUpdateParams) MarshalJSON() (data []byte, err error)

func (*FunctionUpdateParams) UnmarshalJSON

func (r *FunctionUpdateParams) UnmarshalJSON(data []byte) error

type FunctionVersionAnalyze

type FunctionVersionAnalyze struct {
	// Whether bounding box extraction is enabled. Only applicable to analyze and
	// extract functions. When true, the function returns the document regions (page,
	// coordinates) from which each field was extracted.
	EnableBoundingBoxes bool `json:"enableBoundingBoxes" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema" api:"required"`
	// Name of output schema object.
	OutputSchemaName string `json:"outputSchemaName" api:"required"`
	// Reducing the risk of the model stopping early on long documents. Trade-off:
	// Increases total latency.
	PreCount bool             `json:"preCount" api:"required"`
	Type     constant.Analyze `json:"type" default:"analyze"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function version.
	Audit FunctionAudit `json:"audit"`
	// The date and time the function version was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EnableBoundingBoxes respjson.Field
		FunctionID          respjson.Field
		FunctionName        respjson.Field
		OutputSchema        respjson.Field
		OutputSchemaName    respjson.Field
		PreCount            respjson.Field
		Type                respjson.Field
		VersionNum          respjson.Field
		Audit               respjson.Field
		CreatedAt           respjson.Field
		DisplayName         respjson.Field
		Tags                respjson.Field
		UsedInWorkflows     respjson.Field
		ExtraFields         map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionAnalyze) RawJSON

func (r FunctionVersionAnalyze) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionAnalyze) UnmarshalJSON

func (r *FunctionVersionAnalyze) UnmarshalJSON(data []byte) error

type FunctionVersionClassify added in v0.7.0

type FunctionVersionClassify struct {
	// List of classifications a classify function can produce. Shares the underlying
	// route list shape.
	Classifications []ClassificationListItem `json:"classifications" api:"required"`
	// Description of classifier. Can be used to provide additional context on
	// classifier's purpose and expected inputs.
	Description string `json:"description" api:"required"`
	// Email address automatically created by bem. You can forward emails with or
	// without attachments, to be classified.
	EmailAddress string `json:"emailAddress" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string            `json:"functionName" api:"required"`
	Type         constant.Classify `json:"type" default:"classify"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function version.
	Audit FunctionAudit `json:"audit"`
	// The date and time the function version was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Classifications respjson.Field
		Description     respjson.Field
		EmailAddress    respjson.Field
		FunctionID      respjson.Field
		FunctionName    respjson.Field
		Type            respjson.Field
		VersionNum      respjson.Field
		Audit           respjson.Field
		CreatedAt       respjson.Field
		DisplayName     respjson.Field
		Tags            respjson.Field
		UsedInWorkflows respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionClassify) RawJSON added in v0.7.0

func (r FunctionVersionClassify) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionClassify) UnmarshalJSON added in v0.7.0

func (r *FunctionVersionClassify) UnmarshalJSON(data []byte) error

type FunctionVersionEnrich

type FunctionVersionEnrich struct {
	// Configuration for enrich function with semantic search steps.
	//
	// **How Enrich Functions Work:**
	//
	// Enrich functions use semantic search to augment JSON data with relevant
	// information from collections. They take JSON input (typically from a transform
	// function), extract specified fields, perform vector-based semantic search
	// against collections, and inject the results back into the data.
	//
	// **Input Requirements:**
	//
	// - Must receive JSON input (typically uploaded to S3 from a previous function)
	// - Can be chained after transform or other functions that produce JSON output
	//
	// **Example Use Cases:**
	//
	// - Match product descriptions to SKU codes from a product catalog
	// - Enrich customer data with account information
	// - Link order line items to inventory records
	//
	// **Configuration:**
	//
	// - Define one or more enrichment steps
	// - Each step extracts values, searches a collection, and injects results
	// - Steps are executed sequentially
	Config EnrichConfig `json:"config" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string          `json:"functionName" api:"required"`
	Type         constant.Enrich `json:"type" default:"enrich"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function version.
	Audit FunctionAudit `json:"audit"`
	// The date and time the function version was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Config          respjson.Field
		FunctionID      respjson.Field
		FunctionName    respjson.Field
		Type            respjson.Field
		VersionNum      respjson.Field
		Audit           respjson.Field
		CreatedAt       respjson.Field
		DisplayName     respjson.Field
		Tags            respjson.Field
		UsedInWorkflows respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionEnrich) RawJSON

func (r FunctionVersionEnrich) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionEnrich) UnmarshalJSON

func (r *FunctionVersionEnrich) UnmarshalJSON(data []byte) error

type FunctionVersionExtract added in v0.2.0

type FunctionVersionExtract struct {
	// Whether bounding box extraction is enabled. Applies to vision input types (pdf,
	// png, jpeg, heic, heif, webp) that dispatch through the analyze path. When true,
	// the function returns the document regions (page, coordinates) from which each
	// field was extracted.
	EnableBoundingBoxes bool `json:"enableBoundingBoxes" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema" api:"required"`
	// Name of output schema object.
	OutputSchemaName string `json:"outputSchemaName" api:"required"`
	// Reducing the risk of the model stopping early on long documents. Trade-off:
	// Increases total latency.
	PreCount bool `json:"preCount" api:"required"`
	// Whether tabular chunking is enabled. When true, tables in CSV/Excel files are
	// processed in row batches rather than all at once.
	TabularChunkingEnabled bool             `json:"tabularChunkingEnabled" api:"required"`
	Type                   constant.Extract `json:"type" default:"extract"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function version.
	Audit FunctionAudit `json:"audit"`
	// The date and time the function version was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EnableBoundingBoxes    respjson.Field
		FunctionID             respjson.Field
		FunctionName           respjson.Field
		OutputSchema           respjson.Field
		OutputSchemaName       respjson.Field
		PreCount               respjson.Field
		TabularChunkingEnabled respjson.Field
		Type                   respjson.Field
		VersionNum             respjson.Field
		Audit                  respjson.Field
		CreatedAt              respjson.Field
		DisplayName            respjson.Field
		Tags                   respjson.Field
		UsedInWorkflows        respjson.Field
		ExtraFields            map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionExtract) RawJSON added in v0.2.0

func (r FunctionVersionExtract) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionExtract) UnmarshalJSON added in v0.2.0

func (r *FunctionVersionExtract) UnmarshalJSON(data []byte) error

type FunctionVersionGetParams

type FunctionVersionGetParams struct {
	FunctionName string `path:"functionName" api:"required" json:"-"`
	// contains filtered or unexported fields
}

type FunctionVersionGetResponse

type FunctionVersionGetResponse struct {
	// V3 read-side union for function versions. Same shape as the shared
	// `FunctionVersion` union but with `classify` in place of `route`.
	Function FunctionVersionUnion `json:"function" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Function    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Single-function-version response wrapper used by V3 endpoints.

func (FunctionVersionGetResponse) RawJSON

func (r FunctionVersionGetResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionGetResponse) UnmarshalJSON

func (r *FunctionVersionGetResponse) UnmarshalJSON(data []byte) error

type FunctionVersionIdentifier

type FunctionVersionIdentifier struct {
	// Unique identifier of function. Provide either id or name, not both.
	ID string `json:"id"`
	// Name of function. Must be UNIQUE on a per-environment basis. Provide either id
	// or name, not both.
	Name string `json:"name"`
	// Version number of function.
	VersionNum int64 `json:"versionNum"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID          respjson.Field
		Name        respjson.Field
		VersionNum  respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionIdentifier) RawJSON

func (r FunctionVersionIdentifier) RawJSON() string

Returns the unmodified JSON received from the API

func (FunctionVersionIdentifier) ToParam

ToParam converts this FunctionVersionIdentifier to a FunctionVersionIdentifierParam.

Warning: the fields of the param type will not be present. ToParam should only be used at the last possible moment before sending a request. Test for this with FunctionVersionIdentifierParam.Overrides()

func (*FunctionVersionIdentifier) UnmarshalJSON

func (r *FunctionVersionIdentifier) UnmarshalJSON(data []byte) error

type FunctionVersionIdentifierParam

type FunctionVersionIdentifierParam struct {
	// Unique identifier of function. Provide either id or name, not both.
	ID param.Opt[string] `json:"id,omitzero"`
	// Name of function. Must be UNIQUE on a per-environment basis. Provide either id
	// or name, not both.
	Name param.Opt[string] `json:"name,omitzero"`
	// Version number of function.
	VersionNum param.Opt[int64] `json:"versionNum,omitzero"`
	// contains filtered or unexported fields
}

func (FunctionVersionIdentifierParam) MarshalJSON

func (r FunctionVersionIdentifierParam) MarshalJSON() (data []byte, err error)

func (*FunctionVersionIdentifierParam) UnmarshalJSON

func (r *FunctionVersionIdentifierParam) UnmarshalJSON(data []byte) error

type FunctionVersionJoin

type FunctionVersionJoin struct {
	// Description of join function.
	Description string `json:"description" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// The type of join to perform.
	//
	// Any of "standard".
	JoinType string `json:"joinType" api:"required"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema" api:"required"`
	// Name of output schema object.
	OutputSchemaName string        `json:"outputSchemaName" api:"required"`
	Type             constant.Join `json:"type" default:"join"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function version.
	Audit FunctionAudit `json:"audit"`
	// The date and time the function version was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Description      respjson.Field
		FunctionID       respjson.Field
		FunctionName     respjson.Field
		JoinType         respjson.Field
		OutputSchema     respjson.Field
		OutputSchemaName respjson.Field
		Type             respjson.Field
		VersionNum       respjson.Field
		Audit            respjson.Field
		CreatedAt        respjson.Field
		DisplayName      respjson.Field
		Tags             respjson.Field
		UsedInWorkflows  respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionJoin) RawJSON

func (r FunctionVersionJoin) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionJoin) UnmarshalJSON

func (r *FunctionVersionJoin) UnmarshalJSON(data []byte) error

type FunctionVersionParse added in v0.10.0

type FunctionVersionParse struct {
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string         `json:"functionName" api:"required"`
	Type         constant.Parse `json:"type" default:"parse"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function version.
	Audit FunctionAudit `json:"audit"`
	// The date and time the function version was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Per-version configuration for a Parse function.
	//
	// Parse renders document pages (PDF, image) via vision LLM and emits structured
	// JSON. The two toggles below independently control entity extraction (a per-call
	// output concern) and cross-document memory linking (an environment-wide concern).
	ParseConfig FunctionVersionParseParseConfig `json:"parseConfig"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		FunctionID      respjson.Field
		FunctionName    respjson.Field
		Type            respjson.Field
		VersionNum      respjson.Field
		Audit           respjson.Field
		CreatedAt       respjson.Field
		DisplayName     respjson.Field
		ParseConfig     respjson.Field
		Tags            respjson.Field
		UsedInWorkflows respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionParse) RawJSON added in v0.10.0

func (r FunctionVersionParse) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionParse) UnmarshalJSON added in v0.10.0

func (r *FunctionVersionParse) UnmarshalJSON(data []byte) error

type FunctionVersionParseParseConfig added in v0.10.0

type FunctionVersionParseParseConfig struct {
	// When true, extract named entities (people, organizations, products, studies,
	// identifiers, etc.) and the relationships between them, and dedupe by canonical
	// name within the document. When false, only `sections[]` is extracted;
	// `entities[]` and `relationships[]` come back empty in the parse output. Defaults
	// to true.
	ExtractEntities bool `json:"extractEntities"`
	// When true, link this document's entities to entities seen in earlier documents
	// in this environment, building one canonical record per real-world thing across
	// the corpus. Visible in the Memory tab and queryable via `POST /v3/fs` (op=find /
	// open / xref). Doesn't change this call's parse output. Requires
	// `extractEntities=true`. Defaults to true.
	LinkAcrossDocuments bool `json:"linkAcrossDocuments"`
	// Optional JSONSchema. When provided, each chunk performs schema-guided
	// extraction. When absent, chunks perform open-ended discovery and return
	// sections, entities, and relationships per the discovery schema.
	Schema any `json:"schema"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ExtractEntities     respjson.Field
		LinkAcrossDocuments respjson.Field
		Schema              respjson.Field
		ExtraFields         map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Per-version configuration for a Parse function.

Parse renders document pages (PDF, image) via vision LLM and emits structured JSON. The two toggles below independently control entity extraction (a per-call output concern) and cross-document memory linking (an environment-wide concern).

func (FunctionVersionParseParseConfig) RawJSON added in v0.10.0

Returns the unmodified JSON received from the API

func (*FunctionVersionParseParseConfig) UnmarshalJSON added in v0.10.0

func (r *FunctionVersionParseParseConfig) UnmarshalJSON(data []byte) error

type FunctionVersionPayloadShaping

type FunctionVersionPayloadShaping struct {
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// JMESPath expression that defines how to transform and customize the input
	// payload structure. Payload shaping allows you to extract, reshape, and
	// reorganize data from complex input payloads into a simplified, standardized
	// output format. Use JMESPath syntax to select specific fields, perform
	// calculations, and create new data structures tailored to your needs.
	ShapingSchema string                  `json:"shapingSchema" api:"required"`
	Type          constant.PayloadShaping `json:"type" default:"payload_shaping"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function version.
	Audit FunctionAudit `json:"audit"`
	// The date and time the function version was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		FunctionID      respjson.Field
		FunctionName    respjson.Field
		ShapingSchema   respjson.Field
		Type            respjson.Field
		VersionNum      respjson.Field
		Audit           respjson.Field
		CreatedAt       respjson.Field
		DisplayName     respjson.Field
		Tags            respjson.Field
		UsedInWorkflows respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A version of a payload shaping function that transforms and customizes input payloads using JMESPath expressions. Payload shaping allows you to extract specific data, perform calculations, and reshape complex input structures into simplified, standardized output formats tailored to your downstream systems or business requirements.

func (FunctionVersionPayloadShaping) RawJSON

Returns the unmodified JSON received from the API

func (*FunctionVersionPayloadShaping) UnmarshalJSON

func (r *FunctionVersionPayloadShaping) UnmarshalJSON(data []byte) error

type FunctionVersionSend

type FunctionVersionSend struct {
	// Destination type for a Send function.
	//
	// Any of "webhook", "s3", "google_drive".
	DestinationType string `json:"destinationType" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string        `json:"functionName" api:"required"`
	Type         constant.Send `json:"type" default:"send"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function version.
	Audit FunctionAudit `json:"audit"`
	// The date and time the function version was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName         string `json:"displayName"`
	GoogleDriveFolderID string `json:"googleDriveFolderId"`
	S3Bucket            string `json:"s3Bucket"`
	S3Prefix            string `json:"s3Prefix"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// Whether webhook deliveries are signed with an HMAC-SHA256 `bem-signature`
	// header.
	WebhookSigningEnabled bool   `json:"webhookSigningEnabled"`
	WebhookURL            string `json:"webhookUrl"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DestinationType       respjson.Field
		FunctionID            respjson.Field
		FunctionName          respjson.Field
		Type                  respjson.Field
		VersionNum            respjson.Field
		Audit                 respjson.Field
		CreatedAt             respjson.Field
		DisplayName           respjson.Field
		GoogleDriveFolderID   respjson.Field
		S3Bucket              respjson.Field
		S3Prefix              respjson.Field
		Tags                  respjson.Field
		UsedInWorkflows       respjson.Field
		WebhookSigningEnabled respjson.Field
		WebhookURL            respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionSend) RawJSON

func (r FunctionVersionSend) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionSend) UnmarshalJSON

func (r *FunctionVersionSend) UnmarshalJSON(data []byte) error

type FunctionVersionService

type FunctionVersionService struct {
	// contains filtered or unexported fields
}

Functions are the core building blocks of data transformation in Bem. Each function type serves a specific purpose:

  • **Extract**: Extract structured JSON data from unstructured documents (PDFs, emails, images, spreadsheets), with optional layout-aware bounding-box extraction
  • **Route**: Direct data to different processing paths based on conditions
  • **Split**: Break multi-page documents into individual pages for parallel processing
  • **Join**: Combine outputs from multiple function calls into a single result
  • **Parse**: Render documents into a navigable structure of page-aware sections, named entities, and relationships — designed to be walked by an LLM agent via the [File System API](/api/v3/file-system) (`POST /v3/fs`). Two toggles, both `true` by default: `extractEntities` controls per-document entity and relationship extraction; `linkAcrossDocuments` merges entities into one canonical record per real-world thing across the environment, populating cross-document memory.
  • **Payload Shaping**: Transform and restructure data using JMESPath expressions
  • **Enrich**: Enhance data with semantic search against collections
  • **Send**: Deliver workflow outputs to downstream destinations

Use these endpoints to create, update, list, and manage your functions.

FunctionVersionService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewFunctionVersionService method instead.

func NewFunctionVersionService

func NewFunctionVersionService(opts ...option.RequestOption) (r FunctionVersionService)

NewFunctionVersionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*FunctionVersionService) Get

**Retrieve a specific historical version of a function.**

Versions are immutable. Use this endpoint to inspect what a function looked like at the moment a particular call was made — every event and transformation records the function version it ran against.

func (*FunctionVersionService) List

func (r *FunctionVersionService) List(ctx context.Context, functionName string, opts ...option.RequestOption) (res *ListFunctionVersionsResponse, err error)

**List every version of a function.**

Returns the full version history, newest-first. Each row captures the configuration the function had between updates. Useful for audits ("when did this schema change?") and for diffing two versions before promoting an update to production.

type FunctionVersionSplit

type FunctionVersionSplit struct {
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Any of "print_page", "semantic_page".
	SplitType string         `json:"splitType" api:"required"`
	Type      constant.Split `json:"type" default:"split"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function version.
	Audit FunctionAudit `json:"audit"`
	// The date and time the function version was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName             string                                      `json:"displayName"`
	PrintPageSplitConfig    FunctionVersionSplitPrintPageSplitConfig    `json:"printPageSplitConfig"`
	SemanticPageSplitConfig FunctionVersionSplitSemanticPageSplitConfig `json:"semanticPageSplitConfig"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		FunctionID              respjson.Field
		FunctionName            respjson.Field
		SplitType               respjson.Field
		Type                    respjson.Field
		VersionNum              respjson.Field
		Audit                   respjson.Field
		CreatedAt               respjson.Field
		DisplayName             respjson.Field
		PrintPageSplitConfig    respjson.Field
		SemanticPageSplitConfig respjson.Field
		Tags                    respjson.Field
		UsedInWorkflows         respjson.Field
		ExtraFields             map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionSplit) RawJSON

func (r FunctionVersionSplit) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionSplit) UnmarshalJSON

func (r *FunctionVersionSplit) UnmarshalJSON(data []byte) error

type FunctionVersionSplitPrintPageSplitConfig

type FunctionVersionSplitPrintPageSplitConfig struct {
	NextFunctionID string `json:"nextFunctionID"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		NextFunctionID respjson.Field
		ExtraFields    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionSplitPrintPageSplitConfig) RawJSON

Returns the unmodified JSON received from the API

func (*FunctionVersionSplitPrintPageSplitConfig) UnmarshalJSON

func (r *FunctionVersionSplitPrintPageSplitConfig) UnmarshalJSON(data []byte) error

type FunctionVersionSplitSemanticPageSplitConfig

type FunctionVersionSplitSemanticPageSplitConfig struct {
	ItemClasses []SplitFunctionSemanticPageItemClass `json:"itemClasses"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ItemClasses respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionSplitSemanticPageSplitConfig) RawJSON

Returns the unmodified JSON received from the API

func (*FunctionVersionSplitSemanticPageSplitConfig) UnmarshalJSON

func (r *FunctionVersionSplitSemanticPageSplitConfig) UnmarshalJSON(data []byte) error

type FunctionVersionTransform

type FunctionVersionTransform struct {
	// Email address automatically created by bem. You can forward emails with or
	// without attachments, to be transformed.
	EmailAddress string `json:"emailAddress" api:"required"`
	// Unique identifier of function.
	FunctionID string `json:"functionID" api:"required"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName string `json:"functionName" api:"required"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema" api:"required"`
	// Name of output schema object.
	OutputSchemaName string `json:"outputSchemaName" api:"required"`
	// Whether tabular chunking is enabled on the pipeline. This processes tables in
	// CSV/Excel in row batches, rather than all rows at once.
	TabularChunkingEnabled bool               `json:"tabularChunkingEnabled" api:"required"`
	Type                   constant.Transform `json:"type" default:"transform"`
	// Version number of function.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information for the function version.
	Audit FunctionAudit `json:"audit"`
	// The date and time the function version was created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName string `json:"displayName"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags"`
	// List of workflows that use this function.
	UsedInWorkflows []WorkflowUsageInfo `json:"usedInWorkflows"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EmailAddress           respjson.Field
		FunctionID             respjson.Field
		FunctionName           respjson.Field
		OutputSchema           respjson.Field
		OutputSchemaName       respjson.Field
		TabularChunkingEnabled respjson.Field
		Type                   respjson.Field
		VersionNum             respjson.Field
		Audit                  respjson.Field
		CreatedAt              respjson.Field
		DisplayName            respjson.Field
		Tags                   respjson.Field
		UsedInWorkflows        respjson.Field
		ExtraFields            map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (FunctionVersionTransform) RawJSON

func (r FunctionVersionTransform) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionTransform) UnmarshalJSON

func (r *FunctionVersionTransform) UnmarshalJSON(data []byte) error

type FunctionVersionUnion

type FunctionVersionUnion struct {
	EmailAddress           string `json:"emailAddress"`
	FunctionID             string `json:"functionID"`
	FunctionName           string `json:"functionName"`
	OutputSchema           any    `json:"outputSchema"`
	OutputSchemaName       string `json:"outputSchemaName"`
	TabularChunkingEnabled bool   `json:"tabularChunkingEnabled"`
	// Any of "transform", "extract", "analyze", "classify", "send", "split", "join",
	// "enrich", "payload_shaping", "parse".
	Type       string `json:"type"`
	VersionNum int64  `json:"versionNum"`
	// This field is from variant [FunctionVersionTransform].
	Audit               FunctionAudit       `json:"audit"`
	CreatedAt           time.Time           `json:"createdAt"`
	DisplayName         string              `json:"displayName"`
	Tags                []string            `json:"tags"`
	UsedInWorkflows     []WorkflowUsageInfo `json:"usedInWorkflows"`
	EnableBoundingBoxes bool                `json:"enableBoundingBoxes"`
	PreCount            bool                `json:"preCount"`
	// This field is from variant [FunctionVersionClassify].
	Classifications []ClassificationListItem `json:"classifications"`
	Description     string                   `json:"description"`
	// This field is from variant [FunctionVersionSend].
	DestinationType string `json:"destinationType"`
	// This field is from variant [FunctionVersionSend].
	GoogleDriveFolderID string `json:"googleDriveFolderId"`
	// This field is from variant [FunctionVersionSend].
	S3Bucket string `json:"s3Bucket"`
	// This field is from variant [FunctionVersionSend].
	S3Prefix string `json:"s3Prefix"`
	// This field is from variant [FunctionVersionSend].
	WebhookSigningEnabled bool `json:"webhookSigningEnabled"`
	// This field is from variant [FunctionVersionSend].
	WebhookURL string `json:"webhookUrl"`
	// This field is from variant [FunctionVersionSplit].
	SplitType string `json:"splitType"`
	// This field is from variant [FunctionVersionSplit].
	PrintPageSplitConfig FunctionVersionSplitPrintPageSplitConfig `json:"printPageSplitConfig"`
	// This field is from variant [FunctionVersionSplit].
	SemanticPageSplitConfig FunctionVersionSplitSemanticPageSplitConfig `json:"semanticPageSplitConfig"`
	// This field is from variant [FunctionVersionJoin].
	JoinType string `json:"joinType"`
	// This field is from variant [FunctionVersionEnrich].
	Config EnrichConfig `json:"config"`
	// This field is from variant [FunctionVersionPayloadShaping].
	ShapingSchema string `json:"shapingSchema"`
	// This field is from variant [FunctionVersionParse].
	ParseConfig FunctionVersionParseParseConfig `json:"parseConfig"`
	JSON        struct {
		EmailAddress            respjson.Field
		FunctionID              respjson.Field
		FunctionName            respjson.Field
		OutputSchema            respjson.Field
		OutputSchemaName        respjson.Field
		TabularChunkingEnabled  respjson.Field
		Type                    respjson.Field
		VersionNum              respjson.Field
		Audit                   respjson.Field
		CreatedAt               respjson.Field
		DisplayName             respjson.Field
		Tags                    respjson.Field
		UsedInWorkflows         respjson.Field
		EnableBoundingBoxes     respjson.Field
		PreCount                respjson.Field
		Classifications         respjson.Field
		Description             respjson.Field
		DestinationType         respjson.Field
		GoogleDriveFolderID     respjson.Field
		S3Bucket                respjson.Field
		S3Prefix                respjson.Field
		WebhookSigningEnabled   respjson.Field
		WebhookURL              respjson.Field
		SplitType               respjson.Field
		PrintPageSplitConfig    respjson.Field
		SemanticPageSplitConfig respjson.Field
		JoinType                respjson.Field
		Config                  respjson.Field
		ShapingSchema           respjson.Field
		ParseConfig             respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

FunctionVersionUnion contains all possible properties and values from FunctionVersionTransform, FunctionVersionExtract, FunctionVersionAnalyze, FunctionVersionClassify, FunctionVersionSend, FunctionVersionSplit, FunctionVersionJoin, FunctionVersionEnrich, FunctionVersionPayloadShaping, FunctionVersionParse.

Use the FunctionVersionUnion.AsAny method to switch on the variant.

Use the methods beginning with 'As' to cast the union to one of its variants.

func (FunctionVersionUnion) AsAnalyze

func (u FunctionVersionUnion) AsAnalyze() (v FunctionVersionAnalyze)

func (FunctionVersionUnion) AsAny

func (u FunctionVersionUnion) AsAny() anyFunctionVersion

Use the following switch statement to find the correct variant

switch variant := FunctionVersionUnion.AsAny().(type) {
case bem.FunctionVersionTransform:
case bem.FunctionVersionExtract:
case bem.FunctionVersionAnalyze:
case bem.FunctionVersionClassify:
case bem.FunctionVersionSend:
case bem.FunctionVersionSplit:
case bem.FunctionVersionJoin:
case bem.FunctionVersionEnrich:
case bem.FunctionVersionPayloadShaping:
case bem.FunctionVersionParse:
default:
  fmt.Errorf("no variant present")
}

func (FunctionVersionUnion) AsClassify added in v0.7.0

func (u FunctionVersionUnion) AsClassify() (v FunctionVersionClassify)

func (FunctionVersionUnion) AsEnrich

func (FunctionVersionUnion) AsExtract added in v0.2.0

func (u FunctionVersionUnion) AsExtract() (v FunctionVersionExtract)

func (FunctionVersionUnion) AsJoin

func (FunctionVersionUnion) AsParse added in v0.10.0

func (FunctionVersionUnion) AsPayloadShaping

func (u FunctionVersionUnion) AsPayloadShaping() (v FunctionVersionPayloadShaping)

func (FunctionVersionUnion) AsSend

func (FunctionVersionUnion) AsSplit

func (FunctionVersionUnion) AsTransform

func (u FunctionVersionUnion) AsTransform() (v FunctionVersionTransform)

func (FunctionVersionUnion) RawJSON

func (u FunctionVersionUnion) RawJSON() string

Returns the unmodified JSON received from the API

func (*FunctionVersionUnion) UnmarshalJSON

func (r *FunctionVersionUnion) UnmarshalJSON(data []byte) error

type InboundEmailEvent

type InboundEmailEvent struct {
	// The email address of the sender.
	From string `json:"from" api:"required"`
	// The subject of the email.
	Subject string `json:"subject" api:"required"`
	// The email address of the recipient.
	To string `json:"to" api:"required"`
	// The email address of the original intended recipient if the email itself was
	// forwarded.
	DeliveredTo string `json:"deliveredTo"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		From        respjson.Field
		Subject     respjson.Field
		To          respjson.Field
		DeliveredTo respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (InboundEmailEvent) RawJSON

func (r InboundEmailEvent) RawJSON() string

Returns the unmodified JSON received from the API

func (*InboundEmailEvent) UnmarshalJSON

func (r *InboundEmailEvent) UnmarshalJSON(data []byte) error

type InferSchemaNewParams

type InferSchemaNewParams struct {
	// The file to analyze and infer a JSON schema from.
	File any `json:"file,omitzero" api:"required"`
	// contains filtered or unexported fields
}

func (InferSchemaNewParams) MarshalMultipart

func (r InferSchemaNewParams) MarshalMultipart() (data []byte, contentType string, err error)

type InferSchemaNewResponse

type InferSchemaNewResponse struct {
	// Analysis result returned by the infer-schema endpoint.
	Analysis InferSchemaNewResponseAnalysis `json:"analysis" api:"required"`
	// Original filename of the uploaded file.
	Filename string `json:"filename" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Analysis    respjson.Field
		Filename    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Response from the infer-schema endpoint.

func (InferSchemaNewResponse) RawJSON

func (r InferSchemaNewResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*InferSchemaNewResponse) UnmarshalJSON

func (r *InferSchemaNewResponse) UnmarshalJSON(data []byte) error

type InferSchemaNewResponseAnalysis

type InferSchemaNewResponseAnalysis struct {
	// Classification of the primary content. One of: `textual`, `visual`, `audio`,
	// `video`, `mixed`.
	ContentNature string `json:"contentNature" api:"required"`
	// MIME content type of the uploaded file.
	ContentType string `json:"contentType" api:"required"`
	// 2-3 sentence description of what the file contains.
	Description string `json:"description" api:"required"`
	// List of distinct document types found in the file with counts.
	DocumentTypes []InferSchemaNewResponseAnalysisDocumentType `json:"documentTypes" api:"required"`
	// Original filename of the uploaded file.
	FileName string `json:"fileName" api:"required"`
	// High-level file category (e.g. "document", "image", "spreadsheet", "email").
	FileType string `json:"fileType" api:"required"`
	// Whether the file contains multiple separate documents bundled together.
	IsMultiDocument bool `json:"isMultiDocument" api:"required"`
	// Size of the uploaded file in bytes.
	SizeBytes int64 `json:"sizeBytes" api:"required"`
	// Inferred JSON Schema representing all extractable data fields.
	Schema any `json:"schema"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ContentNature   respjson.Field
		ContentType     respjson.Field
		Description     respjson.Field
		DocumentTypes   respjson.Field
		FileName        respjson.Field
		FileType        respjson.Field
		IsMultiDocument respjson.Field
		SizeBytes       respjson.Field
		Schema          respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Analysis result returned by the infer-schema endpoint.

func (InferSchemaNewResponseAnalysis) RawJSON

Returns the unmodified JSON received from the API

func (*InferSchemaNewResponseAnalysis) UnmarshalJSON

func (r *InferSchemaNewResponseAnalysis) UnmarshalJSON(data []byte) error

type InferSchemaNewResponseAnalysisDocumentType

type InferSchemaNewResponseAnalysisDocumentType struct {
	// Number of instances of this document type in the file.
	Count int64 `json:"count" api:"required"`
	// Brief description of this document type.
	Description string `json:"description" api:"required"`
	// Short snake_case name (e.g. "invoice", "receipt", "utility_bill").
	Name string `json:"name" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Count       respjson.Field
		Description respjson.Field
		Name        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Describes a distinct document type found in the file.

func (InferSchemaNewResponseAnalysisDocumentType) RawJSON

Returns the unmodified JSON received from the API

func (*InferSchemaNewResponseAnalysisDocumentType) UnmarshalJSON

func (r *InferSchemaNewResponseAnalysisDocumentType) UnmarshalJSON(data []byte) error

type InferSchemaService

type InferSchemaService struct {
	// contains filtered or unexported fields
}

Infer JSON Schemas from uploaded documents using AI.

Upload a file (PDF, image, spreadsheet, email, etc.) and receive a general-purpose JSON Schema that captures the document's structure. The inferred schema can be used directly as the `outputSchema` when creating Extract functions.

The schema is designed to be broadly applicable to documents of the same type, not just the specific file uploaded.

InferSchemaService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewInferSchemaService method instead.

func NewInferSchemaService

func NewInferSchemaService(opts ...option.RequestOption) (r InferSchemaService)

NewInferSchemaService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*InferSchemaService) New

**Analyze a file and infer a JSON Schema from its contents.**

Accepts a file via multipart form upload and uses Gemini to analyze the document, returning a description of its contents, an inferred JSON Schema capturing all extractable fields, and document classification metadata.

The returned schema is designed to be reusable across many similar documents of the same type, not just the specific file uploaded. It can be used directly as the `outputSchema` when creating a Transform function.

The endpoint also detects whether the file contains multiple bundled documents and classifies the content nature (textual, visual, audio, video, or mixed).

## Supported file types

PDF, PNG, JPEG, HEIC, HEIF, WebP, CSV, XLS, XLSX, DOCX, JSON, HTML, XML, EML, plain text, WAV, MP3, M4A, MP4.

## File size limit

Maximum file size is **20 MB**.

## Examples

Using curl:

```bash

curl -X POST https://api.bem.ai/v3/infer-schema \
  -H "x-api-key: YOUR_API_KEY" \
  -F "file=@invoice.pdf"

```

Using the Bem CLI:

```bash bem infer-schema create --file @invoice.pdf ```

type ListFunctionVersionsResponse

type ListFunctionVersionsResponse struct {
	// The total number of results available.
	TotalCount int64                  `json:"totalCount"`
	Versions   []FunctionVersionUnion `json:"versions"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		TotalCount  respjson.Field
		Versions    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ListFunctionVersionsResponse) RawJSON

Returns the unmodified JSON received from the API

func (*ListFunctionVersionsResponse) UnmarshalJSON

func (r *ListFunctionVersionsResponse) UnmarshalJSON(data []byte) error

type ListFunctionsResponse

type ListFunctionsResponse struct {
	Functions []FunctionUnion `json:"functions"`
	// The total number of results available.
	TotalCount int64 `json:"totalCount"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Functions   respjson.Field
		TotalCount  respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ListFunctionsResponse) RawJSON

func (r ListFunctionsResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*ListFunctionsResponse) UnmarshalJSON

func (r *ListFunctionsResponse) UnmarshalJSON(data []byte) error

type OutputGetResponse

type OutputGetResponse struct {
	// V3 read-side event union. Superset of the shared `Event` union: it contains
	// every shared variant verbatim (backward compatible) and adds the V3-only
	// `extract` and `classify` variants.
	Output EventUnion `json:"output" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Output      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (OutputGetResponse) RawJSON

func (r OutputGetResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*OutputGetResponse) UnmarshalJSON

func (r *OutputGetResponse) UnmarshalJSON(data []byte) error

type OutputListParams

type OutputListParams struct {
	EndingBefore param.Opt[string] `query:"endingBefore,omitzero" json:"-"`
	// When `true`, includes intermediate events (those that spawned a downstream
	// function call). Default: `false`.
	IncludeIntermediate param.Opt[bool] `query:"includeIntermediate,omitzero" json:"-"`
	// If `true`, only outputs with a corrected (labelled) payload. If `false`, only
	// outputs that are not labelled. If omitted, no filter is applied.
	IsLabelled param.Opt[bool] `query:"isLabelled,omitzero" json:"-"`
	// If `true`, only regression-marked outputs. If `false`, only non-regression
	// outputs. If omitted, no filter is applied.
	//
	// Note: clients migrating from `/v1-beta/transformations` should pass
	// `isRegression=false` explicitly to preserve the legacy default (regressions
	// hidden unless explicitly requested).
	IsRegression param.Opt[bool]  `query:"isRegression,omitzero" json:"-"`
	Limit        param.Opt[int64] `query:"limit,omitzero" json:"-"`
	// Case-insensitive substring match against `referenceID`.
	ReferenceIDSubstring param.Opt[string] `query:"referenceIDSubstring,omitzero" json:"-"`
	StartingAfter        param.Opt[string] `query:"startingAfter,omitzero" json:"-"`
	// Filter to outputs from specific calls.
	CallIDs []string `query:"callIDs,omitzero" json:"-"`
	// Filter to specific output events by their event IDs (KSUIDs).
	EventIDs []string `query:"eventIDs,omitzero" json:"-"`
	// Filter to specific non-error output event types, e.g. `classify` or `extract`.
	EventTypes    []string `query:"eventTypes,omitzero" json:"-"`
	FunctionIDs   []string `query:"functionIDs,omitzero" json:"-"`
	FunctionNames []string `query:"functionNames,omitzero" json:"-"`
	// Filter to specific function version numbers.
	FunctionVersionNums []int64  `query:"functionVersionNums,omitzero" json:"-"`
	ReferenceIDs        []string `query:"referenceIDs,omitzero" json:"-"`
	// Any of "asc", "desc".
	SortOrder OutputListParamsSortOrder `query:"sortOrder,omitzero" json:"-"`
	// Filter by legacy transformation IDs. Provided for backwards compatibility with
	// clients migrating from `/v1-beta/transformations`.
	TransformationIDs []string `query:"transformationIDs,omitzero" json:"-"`
	WorkflowIDs       []string `query:"workflowIDs,omitzero" json:"-"`
	WorkflowNames     []string `query:"workflowNames,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (OutputListParams) URLQuery

func (r OutputListParams) URLQuery() (v url.Values, err error)

URLQuery serializes OutputListParams's query parameters as `url.Values`.

type OutputListParamsSortOrder

type OutputListParamsSortOrder string
const (
	OutputListParamsSortOrderAsc  OutputListParamsSortOrder = "asc"
	OutputListParamsSortOrderDesc OutputListParamsSortOrder = "desc"
)

type OutputService

type OutputService struct {
	// contains filtered or unexported fields
}

Retrieve terminal non-error output events from workflow calls.

Outputs are events produced by successful terminal function steps — steps that completed without errors and did not spawn further downstream function calls. A single workflow call may produce multiple outputs (e.g. from a split-then-transform pipeline).

Outputs and errors from the same call are not mutually exclusive: a partially-completed workflow may have both.

Use `GET /v3/outputs` to list outputs across calls, or `GET /v3/outputs/{eventID}` to retrieve a specific output. To get outputs scoped to a single call, filter by `callIDs`.

OutputService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewOutputService method instead.

func NewOutputService

func NewOutputService(opts ...option.RequestOption) (r OutputService)

NewOutputService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*OutputService) Get

func (r *OutputService) Get(ctx context.Context, eventID string, opts ...option.RequestOption) (res *OutputGetResponse, err error)

**Retrieve a single output event by ID.**

Fetches any non-error event by its `eventID`. Returns `404` if the event does not exist or if it is an error event (use `GET /v3/errors/{eventID}` for those).

func (*OutputService) List

**List terminal non-error output events.**

Returns events that represent successful terminal outputs — primary events (non-split-collection) that did not trigger any downstream function calls. Error events are excluded; use `GET /v3/errors` to retrieve those.

## Intermediate Events

By default, intermediate events (those that spawned a downstream function call in a multi-step workflow) are excluded. Pass `includeIntermediate=true` to include them.

## Filtering

Filter by call, workflow, function, or reference ID. Multiple filters are ANDed together.

func (*OutputService) ListAutoPaging

**List terminal non-error output events.**

Returns events that represent successful terminal outputs — primary events (non-split-collection) that did not trigger any downstream function calls. Error events are excluded; use `GET /v3/errors` to retrieve those.

## Intermediate Events

By default, intermediate events (those that spawned a downstream function call in a multi-step workflow) are excluded. Pass `includeIntermediate=true` to include them.

## Filtering

Filter by call, workflow, function, or reference ID. Multiple filters are ANDed together.

type SplitFunctionSemanticPageItemClass

type SplitFunctionSemanticPageItemClass struct {
	Name        string `json:"name" api:"required"`
	Description string `json:"description"`
	// The unique ID of the function you want to use for this item class.
	NextFunctionID string `json:"nextFunctionID"`
	// The unique name of the function you want to use for this item class.
	NextFunctionName string `json:"nextFunctionName"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Name             respjson.Field
		Description      respjson.Field
		NextFunctionID   respjson.Field
		NextFunctionName respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SplitFunctionSemanticPageItemClass) RawJSON

Returns the unmodified JSON received from the API

func (SplitFunctionSemanticPageItemClass) ToParam

ToParam converts this SplitFunctionSemanticPageItemClass to a SplitFunctionSemanticPageItemClassParam.

Warning: the fields of the param type will not be present. ToParam should only be used at the last possible moment before sending a request. Test for this with SplitFunctionSemanticPageItemClassParam.Overrides()

func (*SplitFunctionSemanticPageItemClass) UnmarshalJSON

func (r *SplitFunctionSemanticPageItemClass) UnmarshalJSON(data []byte) error

type SplitFunctionSemanticPageItemClassParam

type SplitFunctionSemanticPageItemClassParam struct {
	Name        string            `json:"name" api:"required"`
	Description param.Opt[string] `json:"description,omitzero"`
	// The unique ID of the function you want to use for this item class.
	NextFunctionID param.Opt[string] `json:"nextFunctionID,omitzero"`
	// The unique name of the function you want to use for this item class.
	NextFunctionName param.Opt[string] `json:"nextFunctionName,omitzero"`
	// contains filtered or unexported fields
}

The property Name is required.

func (SplitFunctionSemanticPageItemClassParam) MarshalJSON

func (r SplitFunctionSemanticPageItemClassParam) MarshalJSON() (data []byte, err error)

func (*SplitFunctionSemanticPageItemClassParam) UnmarshalJSON

func (r *SplitFunctionSemanticPageItemClassParam) UnmarshalJSON(data []byte) error

type UpdateFunctionClassifyParam added in v0.7.0

type UpdateFunctionClassifyParam struct {
	// Description of classifier. Can be used to provide additional context on
	// classifier's purpose and expected inputs.
	Description param.Opt[string] `json:"description,omitzero"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName param.Opt[string] `json:"functionName,omitzero"`
	// List of classifications a classify function can produce. Shares the underlying
	// route list shape.
	Classifications []ClassificationListItemParam `json:"classifications,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "classify".
	Type constant.Classify `json:"type" default:"classify"`
	// contains filtered or unexported fields
}

V3 create/update variants of the shared function payloads.

The V3 Functions API no longer accepts the legacy `transform` or `analyze` function types when creating new functions or updating existing ones — both have been unified under `extract`. Existing functions of those types remain readable and callable via V3, so the V3 read-side unions still include `transform` and `analyze` variants.

The V3 API also exposes `classify` in place of the legacy `route` type on create/update, with `classifications` in place of `routes`. Read-side `ClassifyFunction` / `ClassifyFunctionVersion` / `ClassificationList` are defined in the shared functions models and used by both the V2 and V3 response unions (existing classify functions are returned from V2 GET endpoints verbatim).V3 wire form of the classify function upsert payload.

The property Type is required.

func (UpdateFunctionClassifyParam) MarshalJSON added in v0.7.0

func (r UpdateFunctionClassifyParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionClassifyParam) UnmarshalJSON added in v0.7.0

func (r *UpdateFunctionClassifyParam) UnmarshalJSON(data []byte) error

type UpdateFunctionEnrichParam

type UpdateFunctionEnrichParam struct {
	// Configuration for enrich function with semantic search steps.
	//
	// **How Enrich Functions Work:**
	//
	// Enrich functions use semantic search to augment JSON data with relevant
	// information from collections. They take JSON input (typically from a transform
	// function), extract specified fields, perform vector-based semantic search
	// against collections, and inject the results back into the data.
	//
	// **Input Requirements:**
	//
	// - Must receive JSON input (typically uploaded to S3 from a previous function)
	// - Can be chained after transform or other functions that produce JSON output
	//
	// **Example Use Cases:**
	//
	// - Match product descriptions to SKU codes from a product catalog
	// - Enrich customer data with account information
	// - Link order line items to inventory records
	//
	// **Configuration:**
	//
	// - Define one or more enrichment steps
	// - Each step extracts values, searches a collection, and injects results
	// - Steps are executed sequentially
	Config EnrichConfigParam `json:"config,omitzero"`
	// This field can be elided, and will marshal its zero value as "enrich".
	Type constant.Enrich `json:"type" default:"enrich"`
	// contains filtered or unexported fields
}

The property Type is required.

func (UpdateFunctionEnrichParam) MarshalJSON

func (r UpdateFunctionEnrichParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionEnrichParam) UnmarshalJSON

func (r *UpdateFunctionEnrichParam) UnmarshalJSON(data []byte) error

type UpdateFunctionExtractParam added in v0.2.0

type UpdateFunctionExtractParam struct {
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Whether bounding box extraction is enabled. Applies to vision input types (pdf,
	// png, jpeg, heic, heif, webp) that dispatch through the analyze path. When true,
	// the function returns the document regions (page, coordinates) from which each
	// field was extracted. Enabling this automatically configures the function to use
	// the bounding box model. Disabling resets to the default.
	EnableBoundingBoxes param.Opt[bool] `json:"enableBoundingBoxes,omitzero"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName param.Opt[string] `json:"functionName,omitzero"`
	// Name of output schema object.
	OutputSchemaName param.Opt[string] `json:"outputSchemaName,omitzero"`
	// Reducing the risk of the model stopping early on long documents. Trade-off:
	// Increases total latency. Compatible with `enableBoundingBoxes`.
	PreCount param.Opt[bool] `json:"preCount,omitzero"`
	// Whether tabular chunking is enabled. When true, tables in CSV/Excel files are
	// processed in row batches rather than all at once.
	TabularChunkingEnabled param.Opt[bool] `json:"tabularChunkingEnabled,omitzero"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "extract".
	Type constant.Extract `json:"type" default:"extract"`
	// contains filtered or unexported fields
}

The property Type is required.

func (UpdateFunctionExtractParam) MarshalJSON added in v0.2.0

func (r UpdateFunctionExtractParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionExtractParam) UnmarshalJSON added in v0.2.0

func (r *UpdateFunctionExtractParam) UnmarshalJSON(data []byte) error

type UpdateFunctionJoinParam

type UpdateFunctionJoinParam struct {
	// Description of join function.
	Description param.Opt[string] `json:"description,omitzero"`
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName param.Opt[string] `json:"functionName,omitzero"`
	// Name of output schema object.
	OutputSchemaName param.Opt[string] `json:"outputSchemaName,omitzero"`
	// The type of join to perform.
	//
	// Any of "standard".
	JoinType string `json:"joinType,omitzero"`
	// Desired output structure defined in standard JSON Schema convention.
	OutputSchema any `json:"outputSchema,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "join".
	Type constant.Join `json:"type" default:"join"`
	// contains filtered or unexported fields
}

The property Type is required.

func (UpdateFunctionJoinParam) MarshalJSON

func (r UpdateFunctionJoinParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionJoinParam) UnmarshalJSON

func (r *UpdateFunctionJoinParam) UnmarshalJSON(data []byte) error

type UpdateFunctionParseParam added in v0.10.0

type UpdateFunctionParseParam struct {
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName param.Opt[string] `json:"functionName,omitzero"`
	// Per-version configuration for a Parse function.
	//
	// Parse renders document pages (PDF, image) via vision LLM and emits structured
	// JSON. The two toggles below independently control entity extraction (a per-call
	// output concern) and cross-document memory linking (an environment-wide concern).
	ParseConfig UpdateFunctionParseParseConfigParam `json:"parseConfig,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "parse".
	Type constant.Parse `json:"type" default:"parse"`
	// contains filtered or unexported fields
}

The property Type is required.

func (UpdateFunctionParseParam) MarshalJSON added in v0.10.0

func (r UpdateFunctionParseParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionParseParam) UnmarshalJSON added in v0.10.0

func (r *UpdateFunctionParseParam) UnmarshalJSON(data []byte) error

type UpdateFunctionParseParseConfigParam added in v0.10.0

type UpdateFunctionParseParseConfigParam struct {
	// When true, extract named entities (people, organizations, products, studies,
	// identifiers, etc.) and the relationships between them, and dedupe by canonical
	// name within the document. When false, only `sections[]` is extracted;
	// `entities[]` and `relationships[]` come back empty in the parse output. Defaults
	// to true.
	ExtractEntities param.Opt[bool] `json:"extractEntities,omitzero"`
	// When true, link this document's entities to entities seen in earlier documents
	// in this environment, building one canonical record per real-world thing across
	// the corpus. Visible in the Memory tab and queryable via `POST /v3/fs` (op=find /
	// open / xref). Doesn't change this call's parse output. Requires
	// `extractEntities=true`. Defaults to true.
	LinkAcrossDocuments param.Opt[bool] `json:"linkAcrossDocuments,omitzero"`
	// Optional JSONSchema. When provided, each chunk performs schema-guided
	// extraction. When absent, chunks perform open-ended discovery and return
	// sections, entities, and relationships per the discovery schema.
	Schema any `json:"schema,omitzero"`
	// contains filtered or unexported fields
}

Per-version configuration for a Parse function.

Parse renders document pages (PDF, image) via vision LLM and emits structured JSON. The two toggles below independently control entity extraction (a per-call output concern) and cross-document memory linking (an environment-wide concern).

func (UpdateFunctionParseParseConfigParam) MarshalJSON added in v0.10.0

func (r UpdateFunctionParseParseConfigParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionParseParseConfigParam) UnmarshalJSON added in v0.10.0

func (r *UpdateFunctionParseParseConfigParam) UnmarshalJSON(data []byte) error

type UpdateFunctionPayloadShapingParam

type UpdateFunctionPayloadShapingParam struct {
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName param.Opt[string] `json:"functionName,omitzero"`
	// JMESPath expression that defines how to transform and customize the input
	// payload structure. Payload shaping allows you to extract, reshape, and
	// reorganize data from complex input payloads into a simplified, standardized
	// output format. Use JMESPath syntax to select specific fields, perform
	// calculations, and create new data structures tailored to your needs.
	ShapingSchema param.Opt[string] `json:"shapingSchema,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "payload_shaping".
	Type constant.PayloadShaping `json:"type" default:"payload_shaping"`
	// contains filtered or unexported fields
}

A function that transforms and customizes input payloads using JMESPath expressions. Payload shaping allows you to extract specific data, perform calculations, and reshape complex input structures into simplified, standardized output formats tailored to your downstream systems or business requirements.

The property Type is required.

func (UpdateFunctionPayloadShapingParam) MarshalJSON

func (r UpdateFunctionPayloadShapingParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionPayloadShapingParam) UnmarshalJSON

func (r *UpdateFunctionPayloadShapingParam) UnmarshalJSON(data []byte) error

type UpdateFunctionSendParam

type UpdateFunctionSendParam struct {
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName param.Opt[string] `json:"functionName,omitzero"`
	// Google Drive folder ID. Required when destinationType is google_drive. Managed
	// via Paragon OAuth.
	GoogleDriveFolderID param.Opt[string] `json:"googleDriveFolderId,omitzero"`
	// S3 bucket to upload the payload to. Required when destinationType is s3.
	S3Bucket param.Opt[string] `json:"s3Bucket,omitzero"`
	// Optional S3 key prefix (folder path).
	S3Prefix param.Opt[string] `json:"s3Prefix,omitzero"`
	// Whether to sign webhook deliveries with an HMAC-SHA256 `bem-signature` header.
	// Defaults to `true` when omitted — signing is on by default for new send
	// functions. Set explicitly to `false` to disable.
	WebhookSigningEnabled param.Opt[bool] `json:"webhookSigningEnabled,omitzero"`
	// Webhook URL to POST the payload to. Required when destinationType is webhook.
	WebhookURL param.Opt[string] `json:"webhookUrl,omitzero"`
	// Destination type for a Send function.
	//
	// Any of "webhook", "s3", "google_drive".
	DestinationType string `json:"destinationType,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "send".
	Type constant.Send `json:"type" default:"send"`
	// contains filtered or unexported fields
}

The property Type is required.

func (UpdateFunctionSendParam) MarshalJSON

func (r UpdateFunctionSendParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionSendParam) UnmarshalJSON

func (r *UpdateFunctionSendParam) UnmarshalJSON(data []byte) error

type UpdateFunctionSplitParam

type UpdateFunctionSplitParam struct {
	// Display name of function. Human-readable name to help you identify the function.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Name of function. Must be UNIQUE on a per-environment basis.
	FunctionName            param.Opt[string]                               `json:"functionName,omitzero"`
	PrintPageSplitConfig    UpdateFunctionSplitPrintPageSplitConfigParam    `json:"printPageSplitConfig,omitzero"`
	SemanticPageSplitConfig UpdateFunctionSplitSemanticPageSplitConfigParam `json:"semanticPageSplitConfig,omitzero"`
	// Any of "print_page", "semantic_page".
	SplitType string `json:"splitType,omitzero"`
	// Array of tags to categorize and organize functions.
	Tags []string `json:"tags,omitzero"`
	// This field can be elided, and will marshal its zero value as "split".
	Type constant.Split `json:"type" default:"split"`
	// contains filtered or unexported fields
}

The property Type is required.

func (UpdateFunctionSplitParam) MarshalJSON

func (r UpdateFunctionSplitParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionSplitParam) UnmarshalJSON

func (r *UpdateFunctionSplitParam) UnmarshalJSON(data []byte) error

type UpdateFunctionSplitPrintPageSplitConfigParam

type UpdateFunctionSplitPrintPageSplitConfigParam struct {
	NextFunctionID   param.Opt[string] `json:"nextFunctionID,omitzero"`
	NextFunctionName param.Opt[string] `json:"nextFunctionName,omitzero"`
	// contains filtered or unexported fields
}

func (UpdateFunctionSplitPrintPageSplitConfigParam) MarshalJSON

func (r UpdateFunctionSplitPrintPageSplitConfigParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionSplitPrintPageSplitConfigParam) UnmarshalJSON

func (r *UpdateFunctionSplitPrintPageSplitConfigParam) UnmarshalJSON(data []byte) error

type UpdateFunctionSplitSemanticPageSplitConfigParam

type UpdateFunctionSplitSemanticPageSplitConfigParam struct {
	ItemClasses []SplitFunctionSemanticPageItemClassParam `json:"itemClasses,omitzero"`
	// contains filtered or unexported fields
}

func (UpdateFunctionSplitSemanticPageSplitConfigParam) MarshalJSON

func (r UpdateFunctionSplitSemanticPageSplitConfigParam) MarshalJSON() (data []byte, err error)

func (*UpdateFunctionSplitSemanticPageSplitConfigParam) UnmarshalJSON

type UpdateFunctionUnionParam

type UpdateFunctionUnionParam struct {
	OfExtract        *UpdateFunctionExtractParam        `json:",omitzero,inline"`
	OfClassify       *UpdateFunctionClassifyParam       `json:",omitzero,inline"`
	OfSend           *UpdateFunctionSendParam           `json:",omitzero,inline"`
	OfSplit          *UpdateFunctionSplitParam          `json:",omitzero,inline"`
	OfJoin           *UpdateFunctionJoinParam           `json:",omitzero,inline"`
	OfPayloadShaping *UpdateFunctionPayloadShapingParam `json:",omitzero,inline"`
	OfEnrich         *UpdateFunctionEnrichParam         `json:",omitzero,inline"`
	OfParse          *UpdateFunctionParseParam          `json:",omitzero,inline"`
	// contains filtered or unexported fields
}

Only one field can be non-zero.

Use param.IsOmitted to confirm if a field is set.

func (UpdateFunctionUnionParam) MarshalJSON

func (u UpdateFunctionUnionParam) MarshalJSON() ([]byte, error)

func (*UpdateFunctionUnionParam) UnmarshalJSON

func (u *UpdateFunctionUnionParam) UnmarshalJSON(data []byte) error

type UserActionSummary

type UserActionSummary struct {
	// The date and time the action was created.
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// Unique identifier of the user action.
	UserActionID string `json:"userActionID" api:"required"`
	// API key name. Present for API key-initiated actions.
	APIKeyName string `json:"apiKeyName"`
	// Email address. Present for email-initiated actions.
	EmailAddress string `json:"emailAddress"`
	// User's email address. Present for user-initiated actions.
	UserEmail string `json:"userEmail"`
	// User's ID. Present for user-initiated actions.
	UserID string `json:"userID"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CreatedAt    respjson.Field
		UserActionID respjson.Field
		APIKeyName   respjson.Field
		EmailAddress respjson.Field
		UserEmail    respjson.Field
		UserID       respjson.Field
		ExtraFields  map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (UserActionSummary) RawJSON

func (r UserActionSummary) RawJSON() string

Returns the unmodified JSON received from the API

func (*UserActionSummary) UnmarshalJSON

func (r *UserActionSummary) UnmarshalJSON(data []byte) error

type WebhookSecretGetResponse added in v0.9.0

type WebhookSecretGetResponse struct {
	// The signing secret value. Store this securely — it is shown in full only on
	// generation.
	Secret string `json:"secret" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Secret      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Webhook signing secret used to verify `bem-signature` headers on delivered webhooks.

func (WebhookSecretGetResponse) RawJSON added in v0.9.0

func (r WebhookSecretGetResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WebhookSecretGetResponse) UnmarshalJSON added in v0.9.0

func (r *WebhookSecretGetResponse) UnmarshalJSON(data []byte) error

type WebhookSecretNewResponse added in v0.9.0

type WebhookSecretNewResponse struct {
	// The signing secret value. Store this securely — it is shown in full only on
	// generation.
	Secret string `json:"secret" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Secret      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Webhook signing secret used to verify `bem-signature` headers on delivered webhooks.

func (WebhookSecretNewResponse) RawJSON added in v0.9.0

func (r WebhookSecretNewResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WebhookSecretNewResponse) UnmarshalJSON added in v0.9.0

func (r *WebhookSecretNewResponse) UnmarshalJSON(data []byte) error

type WebhookSecretService added in v0.9.0

type WebhookSecretService struct {
	// contains filtered or unexported fields
}

Manage the webhook signing secret used to authenticate outbound webhook deliveries.

When a signing secret is active, every webhook delivery includes a `bem-signature` header in the format `t={unix_timestamp},v1={hex_hmac_sha256}`. The signature covers `{timestamp}.{raw_request_body}` and can be verified using HMAC-SHA256 with your secret.

Rotate the secret at any time with `POST /v3/webhook-secret`. To avoid downtime during rotation, update your verification logic to accept both the old and new secret briefly before revoking the old one.

WebhookSecretService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewWebhookSecretService method instead.

func NewWebhookSecretService added in v0.9.0

func NewWebhookSecretService(opts ...option.RequestOption) (r WebhookSecretService)

NewWebhookSecretService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*WebhookSecretService) Get added in v0.9.0

**Get the current webhook signing secret.**

Returns the active secret used to sign outbound webhook deliveries via the `bem-signature` header. Returns 404 if no secret has been generated for this environment yet.

Use the secret to verify incoming webhook payloads:

1. Parse `bem-signature: t={timestamp},v1={signature}`. 2. Construct the signed string: `{timestamp}.{raw request body}`. 3. Compute HMAC-SHA256 of that string using the secret. 4. Compare the hex digest against `v1`. 5. Reject requests where the timestamp is more than a few minutes old.

func (*WebhookSecretService) New added in v0.9.0

**Generate a new webhook signing secret.**

Creates a new signing secret for this environment (or replaces the existing one). The new secret is returned in full exactly once — store it securely.

After rotation all newly delivered webhooks will be signed with the new secret. Update your verification logic before calling this endpoint if you need zero-downtime rotation.

func (*WebhookSecretService) Revoke added in v0.9.0

func (r *WebhookSecretService) Revoke(ctx context.Context, opts ...option.RequestOption) (err error)

**Revoke the current webhook signing secret.**

Deletes the active signing secret. Webhook deliveries will continue but will no longer include a `bem-signature` header until a new secret is generated.

type Workflow

type Workflow struct {
	// Unique identifier of the workflow.
	ID string `json:"id" api:"required"`
	// Connectors currently attached to this workflow. For version-scoped reads
	// (`/versions/{n}`) this is always empty — connectors are current-state and not
	// part of version history.
	Connectors []WorkflowConnector `json:"connectors" api:"required"`
	// The date and time the workflow was created.
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// All directed edges in this workflow version's DAG.
	Edges []WorkflowEdgeResponse `json:"edges" api:"required"`
	// Name of the entry-point call-site node.
	MainNodeName string `json:"mainNodeName" api:"required"`
	// Unique name of the workflow within the environment.
	Name string `json:"name" api:"required"`
	// All call-site nodes in this workflow version's DAG.
	Nodes []WorkflowNodeResponse `json:"nodes" api:"required"`
	// The date and time the workflow was last updated.
	UpdatedAt time.Time `json:"updatedAt" api:"required" format:"date-time"`
	// Version number of this workflow version.
	VersionNum int64 `json:"versionNum" api:"required"`
	// Audit trail information.
	Audit WorkflowAudit `json:"audit"`
	// Human-readable display name.
	DisplayName string `json:"displayName"`
	// Inbound email address associated with the workflow, if any.
	EmailAddress string `json:"emailAddress"`
	// Tags associated with the workflow.
	Tags []string `json:"tags"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID           respjson.Field
		Connectors   respjson.Field
		CreatedAt    respjson.Field
		Edges        respjson.Field
		MainNodeName respjson.Field
		Name         respjson.Field
		Nodes        respjson.Field
		UpdatedAt    respjson.Field
		VersionNum   respjson.Field
		Audit        respjson.Field
		DisplayName  respjson.Field
		EmailAddress respjson.Field
		Tags         respjson.Field
		ExtraFields  map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

V3 read representation of a workflow version.

func (Workflow) RawJSON

func (r Workflow) RawJSON() string

Returns the unmodified JSON received from the API

func (*Workflow) UnmarshalJSON

func (r *Workflow) UnmarshalJSON(data []byte) error

type WorkflowAudit

type WorkflowAudit struct {
	// Information about who created the current version.
	VersionCreatedBy UserActionSummary `json:"versionCreatedBy"`
	// Information about who created the workflow.
	WorkflowCreatedBy UserActionSummary `json:"workflowCreatedBy"`
	// Information about who last updated the workflow.
	WorkflowLastUpdatedBy UserActionSummary `json:"workflowLastUpdatedBy"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		VersionCreatedBy      respjson.Field
		WorkflowCreatedBy     respjson.Field
		WorkflowLastUpdatedBy respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WorkflowAudit) RawJSON

func (r WorkflowAudit) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowAudit) UnmarshalJSON

func (r *WorkflowAudit) UnmarshalJSON(data []byte) error

type WorkflowCallParams

type WorkflowCallParams struct {
	// Input file(s) for a call. Provide exactly one of `singleFile` or `batchFiles`.
	//
	// In the CLI, use the nested flags `--input.single-file` or `--input.batch-files`
	// with `@path/to/file` for automatic file embedding:
	// `--input.single-file '{"inputContent": "@invoice.pdf", "inputType": "pdf"}' --wait`
	Input WorkflowCallParamsInput `json:"input,omitzero" api:"required"`
	// Block until the call completes (up to 30 seconds) and return the finished call
	// object. Default: `false`. This is a boolean flag — use `--wait` or
	// `--wait=true`, not `--wait true`.
	Wait param.Opt[bool] `query:"wait,omitzero" json:"-"`
	// Your reference ID for tracking this call.
	CallReferenceID param.Opt[string] `json:"callReferenceID,omitzero"`
	// Arbitrary JSON object attached to this call. Stored on the call record and
	// injected into `transformedContent` under the reserved `_metadata` key (alongside
	// `referenceID`). Must be a JSON object. Maximum size: 4 KB.
	Metadata any `json:"metadata,omitzero"`
	// contains filtered or unexported fields
}

func (WorkflowCallParams) MarshalJSON

func (r WorkflowCallParams) MarshalJSON() (data []byte, err error)

func (WorkflowCallParams) URLQuery

func (r WorkflowCallParams) URLQuery() (v url.Values, err error)

URLQuery serializes WorkflowCallParams's query parameters as `url.Values`.

func (*WorkflowCallParams) UnmarshalJSON

func (r *WorkflowCallParams) UnmarshalJSON(data []byte) error

type WorkflowCallParamsInput

type WorkflowCallParamsInput struct {
	// Multiple files to process in one call. Each item in the `inputs` array has its
	// own `inputContent` and `inputType`.
	BatchFiles WorkflowCallParamsInputBatchFiles `json:"batchFiles,omitzero"`
	// A single file input with base64-encoded content.
	//
	// When using the Bem CLI, use `@path/to/file` in the `inputContent` field to
	// automatically read and base64-encode the file:
	// `--input.single-file '{"inputContent": "@file.pdf", "inputType": "pdf"}' --wait`
	SingleFile WorkflowCallParamsInputSingleFile `json:"singleFile,omitzero"`
	// contains filtered or unexported fields
}

Input file(s) for a call. Provide exactly one of `singleFile` or `batchFiles`.

In the CLI, use the nested flags `--input.single-file` or `--input.batch-files` with `@path/to/file` for automatic file embedding: `--input.single-file '{"inputContent": "@invoice.pdf", "inputType": "pdf"}' --wait`

func (WorkflowCallParamsInput) MarshalJSON

func (r WorkflowCallParamsInput) MarshalJSON() (data []byte, err error)

func (*WorkflowCallParamsInput) UnmarshalJSON

func (r *WorkflowCallParamsInput) UnmarshalJSON(data []byte) error

type WorkflowCallParamsInputBatchFiles

type WorkflowCallParamsInputBatchFiles struct {
	Inputs []WorkflowCallParamsInputBatchFilesInput `json:"inputs,omitzero"`
	// contains filtered or unexported fields
}

Multiple files to process in one call. Each item in the `inputs` array has its own `inputContent` and `inputType`.

func (WorkflowCallParamsInputBatchFiles) MarshalJSON

func (r WorkflowCallParamsInputBatchFiles) MarshalJSON() (data []byte, err error)

func (*WorkflowCallParamsInputBatchFiles) UnmarshalJSON

func (r *WorkflowCallParamsInputBatchFiles) UnmarshalJSON(data []byte) error

type WorkflowCallParamsInputBatchFilesInput

type WorkflowCallParamsInputBatchFilesInput struct {
	// Base64-encoded file content. In the Bem CLI, use `@path/to/file` to embed file
	// contents automatically.
	InputContent string `json:"inputContent" api:"required"`
	// The input type of the content you're sending for transformation.
	//
	// Any of "csv", "docx", "email", "heic", "html", "jpeg", "json", "heif", "m4a",
	// "mp3", "pdf", "png", "text", "wav", "webp", "xls", "xlsx", "xml".
	InputType       string            `json:"inputType,omitzero" api:"required"`
	ItemReferenceID param.Opt[string] `json:"itemReferenceID,omitzero"`
	// contains filtered or unexported fields
}

The properties InputContent, InputType are required.

func (WorkflowCallParamsInputBatchFilesInput) MarshalJSON

func (r WorkflowCallParamsInputBatchFilesInput) MarshalJSON() (data []byte, err error)

func (*WorkflowCallParamsInputBatchFilesInput) UnmarshalJSON

func (r *WorkflowCallParamsInputBatchFilesInput) UnmarshalJSON(data []byte) error

type WorkflowCallParamsInputSingleFile

type WorkflowCallParamsInputSingleFile struct {
	// Base64-encoded file content. In the Bem CLI, use `@path/to/file` to embed file
	// contents automatically.
	InputContent string `json:"inputContent" api:"required"`
	// The input type of the content you're sending for transformation.
	//
	// Any of "csv", "docx", "email", "heic", "html", "jpeg", "json", "heif", "m4a",
	// "mp3", "pdf", "png", "text", "wav", "webp", "xls", "xlsx", "xml".
	InputType string `json:"inputType,omitzero" api:"required"`
	// contains filtered or unexported fields
}

A single file input with base64-encoded content.

When using the Bem CLI, use `@path/to/file` in the `inputContent` field to automatically read and base64-encode the file: `--input.single-file '{"inputContent": "@file.pdf", "inputType": "pdf"}' --wait`

The properties InputContent, InputType are required.

func (WorkflowCallParamsInputSingleFile) MarshalJSON

func (r WorkflowCallParamsInputSingleFile) MarshalJSON() (data []byte, err error)

func (*WorkflowCallParamsInputSingleFile) UnmarshalJSON

func (r *WorkflowCallParamsInputSingleFile) UnmarshalJSON(data []byte) error

type WorkflowConnector added in v0.7.0

type WorkflowConnector struct {
	// Unique connector API ID.
	ConnectorID string `json:"connectorID" api:"required"`
	// Human-friendly connector name.
	Name string `json:"name" api:"required"`
	// Discriminator for a workflow connector. V3 supports `paragon` only.
	//
	// Any of "paragon".
	Type string `json:"type" api:"required"`
	// Paragon-integration configuration on a workflow connector.
	Paragon WorkflowConnectorParagon `json:"paragon"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ConnectorID respjson.Field
		Name        respjson.Field
		Type        respjson.Field
		Paragon     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A connector attached to a workflow. Ingestion point that triggers the workflow.

func (WorkflowConnector) RawJSON added in v0.7.0

func (r WorkflowConnector) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowConnector) UnmarshalJSON added in v0.7.0

func (r *WorkflowConnector) UnmarshalJSON(data []byte) error

type WorkflowConnectorParagon added in v0.7.0

type WorkflowConnectorParagon struct {
	// Opaque per-integration configuration (e.g. `{"folderId": "..."}`).
	Configuration any `json:"configuration" api:"required"`
	// Paragon integration key (e.g. "googledrive").
	Integration string `json:"integration" api:"required"`
	// Paragon sync ID managed by the server. Read-only.
	SyncID string `json:"syncID" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Configuration respjson.Field
		Integration   respjson.Field
		SyncID        respjson.Field
		ExtraFields   map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Paragon-integration configuration on a workflow connector.

func (WorkflowConnectorParagon) RawJSON added in v0.7.0

func (r WorkflowConnectorParagon) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowConnectorParagon) UnmarshalJSON added in v0.7.0

func (r *WorkflowConnectorParagon) UnmarshalJSON(data []byte) error

type WorkflowCopyParams

type WorkflowCopyParams struct {
	// Name of the source workflow to copy from.
	SourceWorkflowName string `json:"sourceWorkflowName" api:"required"`
	// Name for the new copied workflow. Must be unique within the target environment.
	TargetWorkflowName string `json:"targetWorkflowName" api:"required"`
	// Optional version number of the source workflow to copy. If not provided, copies
	// the current version.
	SourceWorkflowVersionNum param.Opt[int64] `json:"sourceWorkflowVersionNum,omitzero"`
	// Optional display name for the copied workflow. If not provided, uses the source
	// workflow's display name with " (Copy)" appended.
	TargetDisplayName param.Opt[string] `json:"targetDisplayName,omitzero"`
	// Optional target environment name. If provided, copies the workflow to a
	// different environment. When copying to a different environment, all functions
	// used in the workflow will also be copied.
	TargetEnvironment param.Opt[string] `json:"targetEnvironment,omitzero"`
	// Optional tags for the copied workflow. If not provided, uses the source
	// workflow's tags.
	Tags []string `json:"tags,omitzero"`
	// contains filtered or unexported fields
}

func (WorkflowCopyParams) MarshalJSON

func (r WorkflowCopyParams) MarshalJSON() (data []byte, err error)

func (*WorkflowCopyParams) UnmarshalJSON

func (r *WorkflowCopyParams) UnmarshalJSON(data []byte) error

type WorkflowCopyResponse

type WorkflowCopyResponse struct {
	// Functions that were copied when copying to a different environment. Empty when
	// copying within the same environment.
	CopiedFunctions []WorkflowCopyResponseCopiedFunction `json:"copiedFunctions"`
	// The environment the workflow was copied to.
	Environment string `json:"environment"`
	// Error message if the workflow copy failed.
	Error string `json:"error"`
	// V3 read representation of a workflow version.
	Workflow Workflow `json:"workflow"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CopiedFunctions respjson.Field
		Environment     respjson.Field
		Error           respjson.Field
		Workflow        respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WorkflowCopyResponse) RawJSON

func (r WorkflowCopyResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowCopyResponse) UnmarshalJSON

func (r *WorkflowCopyResponse) UnmarshalJSON(data []byte) error

type WorkflowCopyResponseCopiedFunction

type WorkflowCopyResponseCopiedFunction struct {
	// ID of the source function that was copied.
	SourceFunctionID string `json:"sourceFunctionID" api:"required"`
	// Name of the source function that was copied.
	SourceFunctionName string `json:"sourceFunctionName" api:"required"`
	// Version number of the source function that was copied.
	SourceVersionNum int64 `json:"sourceVersionNum" api:"required"`
	// ID of the newly created function in the target environment.
	TargetFunctionID string `json:"targetFunctionID" api:"required"`
	// Name of the newly created function in the target environment.
	TargetFunctionName string `json:"targetFunctionName" api:"required"`
	// Version number of the newly created function in the target environment.
	TargetVersionNum int64 `json:"targetVersionNum" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		SourceFunctionID   respjson.Field
		SourceFunctionName respjson.Field
		SourceVersionNum   respjson.Field
		TargetFunctionID   respjson.Field
		TargetFunctionName respjson.Field
		TargetVersionNum   respjson.Field
		ExtraFields        map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WorkflowCopyResponseCopiedFunction) RawJSON

Returns the unmodified JSON received from the API

func (*WorkflowCopyResponseCopiedFunction) UnmarshalJSON

func (r *WorkflowCopyResponseCopiedFunction) UnmarshalJSON(data []byte) error

type WorkflowEdgeResponse

type WorkflowEdgeResponse struct {
	// Name of the destination node.
	DestinationNodeName string `json:"destinationNodeName" api:"required"`
	// Name of the source node.
	SourceNodeName string `json:"sourceNodeName" api:"required"`
	// Labelled outlet on the source node, if any.
	DestinationName string `json:"destinationName"`
	// Opaque free-form JSON object attached to this edge on create/update. Returned
	// verbatim; never interpreted by the server.
	Metadata any `json:"metadata"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DestinationNodeName respjson.Field
		SourceNodeName      respjson.Field
		DestinationName     respjson.Field
		Metadata            respjson.Field
		ExtraFields         map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Read representation of a directed edge between call-site nodes.

func (WorkflowEdgeResponse) RawJSON

func (r WorkflowEdgeResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowEdgeResponse) UnmarshalJSON

func (r *WorkflowEdgeResponse) UnmarshalJSON(data []byte) error

type WorkflowGetResponse

type WorkflowGetResponse struct {
	// Error message if the workflow retrieval failed.
	Error string `json:"error"`
	// V3 read representation of a workflow version.
	Workflow Workflow `json:"workflow"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Error       respjson.Field
		Workflow    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WorkflowGetResponse) RawJSON

func (r WorkflowGetResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowGetResponse) UnmarshalJSON

func (r *WorkflowGetResponse) UnmarshalJSON(data []byte) error

type WorkflowListParams

type WorkflowListParams struct {
	DisplayName   param.Opt[string] `query:"displayName,omitzero" json:"-"`
	EndingBefore  param.Opt[string] `query:"endingBefore,omitzero" json:"-"`
	Limit         param.Opt[int64]  `query:"limit,omitzero" json:"-"`
	StartingAfter param.Opt[string] `query:"startingAfter,omitzero" json:"-"`
	FunctionIDs   []string          `query:"functionIDs,omitzero" json:"-"`
	FunctionNames []string          `query:"functionNames,omitzero" json:"-"`
	// Any of "asc", "desc".
	SortOrder     WorkflowListParamsSortOrder `query:"sortOrder,omitzero" json:"-"`
	Tags          []string                    `query:"tags,omitzero" json:"-"`
	WorkflowIDs   []string                    `query:"workflowIDs,omitzero" json:"-"`
	WorkflowNames []string                    `query:"workflowNames,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (WorkflowListParams) URLQuery

func (r WorkflowListParams) URLQuery() (v url.Values, err error)

URLQuery serializes WorkflowListParams's query parameters as `url.Values`.

type WorkflowListParamsSortOrder

type WorkflowListParamsSortOrder string
const (
	WorkflowListParamsSortOrderAsc  WorkflowListParamsSortOrder = "asc"
	WorkflowListParamsSortOrderDesc WorkflowListParamsSortOrder = "desc"
)

type WorkflowNewParams

type WorkflowNewParams struct {
	// Name of the entry-point node. Must not be a destination of any edge.
	MainNodeName string `json:"mainNodeName" api:"required"`
	// Unique name for the workflow. Must match `^[a-zA-Z0-9_-]{1,128}$`.
	Name string `json:"name" api:"required"`
	// Call-site nodes in the DAG. At least one is required.
	Nodes []WorkflowNewParamsNode `json:"nodes,omitzero" api:"required"`
	// Human-readable display name.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// Connectors to attach to the workflow at creation. If any entry fails to
	// provision, the entire workflow creation is rolled back.
	Connectors []WorkflowNewParamsConnector `json:"connectors,omitzero"`
	// Directed edges between nodes. Omit or leave empty for single-node workflows.
	Edges []WorkflowNewParamsEdge `json:"edges,omitzero"`
	// Tags to categorize and organize the workflow.
	Tags []string `json:"tags,omitzero"`
	// contains filtered or unexported fields
}

func (WorkflowNewParams) MarshalJSON

func (r WorkflowNewParams) MarshalJSON() (data []byte, err error)

func (*WorkflowNewParams) UnmarshalJSON

func (r *WorkflowNewParams) UnmarshalJSON(data []byte) error

type WorkflowNewParamsConnector added in v0.7.0

type WorkflowNewParamsConnector struct {
	// Human-friendly connector name.
	Name string `json:"name" api:"required"`
	// Discriminator for a workflow connector. V3 supports `paragon` only.
	//
	// Any of "paragon".
	Type string `json:"type,omitzero" api:"required"`
	// Present → update. Absent → create.
	ConnectorID param.Opt[string] `json:"connectorID,omitzero"`
	// Request-side config block for a Paragon connector. Fields absent on update are
	// unchanged.
	Paragon WorkflowNewParamsConnectorParagon `json:"paragon,omitzero"`
	// contains filtered or unexported fields
}

Create/update entry for a connector inline with the workflow.

The properties Name, Type are required.

func (WorkflowNewParamsConnector) MarshalJSON added in v0.7.0

func (r WorkflowNewParamsConnector) MarshalJSON() (data []byte, err error)

func (*WorkflowNewParamsConnector) UnmarshalJSON added in v0.7.0

func (r *WorkflowNewParamsConnector) UnmarshalJSON(data []byte) error

type WorkflowNewParamsConnectorParagon added in v0.7.0

type WorkflowNewParamsConnectorParagon struct {
	// Paragon integration key. Required on create.
	Integration param.Opt[string] `json:"integration,omitzero"`
	// Opaque per-integration configuration. Required on create.
	Configuration any `json:"configuration,omitzero"`
	// contains filtered or unexported fields
}

Request-side config block for a Paragon connector. Fields absent on update are unchanged.

func (WorkflowNewParamsConnectorParagon) MarshalJSON added in v0.7.0

func (r WorkflowNewParamsConnectorParagon) MarshalJSON() (data []byte, err error)

func (*WorkflowNewParamsConnectorParagon) UnmarshalJSON added in v0.7.0

func (r *WorkflowNewParamsConnectorParagon) UnmarshalJSON(data []byte) error

type WorkflowNewParamsEdge

type WorkflowNewParamsEdge struct {
	// Name of the destination node.
	DestinationNodeName string `json:"destinationNodeName" api:"required"`
	// Name of the source node.
	SourceNodeName string `json:"sourceNodeName" api:"required"`
	// Labelled outlet on the source node that activates this edge. Omit for the
	// default (unlabelled) outlet.
	DestinationName param.Opt[string] `json:"destinationName,omitzero"`
	// Opaque free-form JSON object attached to this edge. Stored and returned
	// verbatim; the server does not interpret it.
	Metadata any `json:"metadata,omitzero"`
	// contains filtered or unexported fields
}

A directed edge between two named call-site nodes.

The properties DestinationNodeName, SourceNodeName are required.

func (WorkflowNewParamsEdge) MarshalJSON

func (r WorkflowNewParamsEdge) MarshalJSON() (data []byte, err error)

func (*WorkflowNewParamsEdge) UnmarshalJSON

func (r *WorkflowNewParamsEdge) UnmarshalJSON(data []byte) error

type WorkflowNewParamsNode

type WorkflowNewParamsNode struct {
	// The function (and version) to execute at this call site.
	Function FunctionVersionIdentifierParam `json:"function,omitzero" api:"required"`
	// Name for this call site. Must be unique within the workflow version. Defaults to
	// the function's own name when omitted.
	Name param.Opt[string] `json:"name,omitzero"`
	// Opaque free-form JSON object attached to this node. Stored and returned
	// verbatim; the server does not interpret it. Intended for client-side concerns
	// such as canvas display properties (position, color, collapsed state, etc.).
	Metadata any `json:"metadata,omitzero"`
	// contains filtered or unexported fields
}

A single function call-site node in a workflow DAG.

The property Function is required.

func (WorkflowNewParamsNode) MarshalJSON

func (r WorkflowNewParamsNode) MarshalJSON() (data []byte, err error)

func (*WorkflowNewParamsNode) UnmarshalJSON

func (r *WorkflowNewParamsNode) UnmarshalJSON(data []byte) error

type WorkflowNewResponseEnvelope added in v0.8.0

type WorkflowNewResponseEnvelope struct {
	// Per-connector failures from the diff/apply phase. Empty or omitted when all
	// operations succeeded.
	ConnectorErrors []WorkflowNewResponseEnvelopeConnectorError `json:"connectorErrors"`
	// Error message if the workflow creation failed.
	Error string `json:"error"`
	// V3 read representation of a workflow version.
	Workflow Workflow `json:"workflow"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ConnectorErrors respjson.Field
		Error           respjson.Field
		Workflow        respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WorkflowNewResponseEnvelope) RawJSON added in v0.8.0

func (r WorkflowNewResponseEnvelope) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowNewResponseEnvelope) UnmarshalJSON added in v0.8.0

func (r *WorkflowNewResponseEnvelope) UnmarshalJSON(data []byte) error

type WorkflowNewResponseEnvelopeConnectorError added in v0.8.0

type WorkflowNewResponseEnvelopeConnectorError struct {
	// Machine-readable error code.
	Code string `json:"code" api:"required"`
	// Human-readable error message.
	Message string `json:"message" api:"required"`
	// Which diff operation was attempted.
	//
	// Any of "create", "update", "delete".
	Operation string `json:"operation" api:"required"`
	// Populated for update/delete failures.
	ConnectorID string `json:"connectorID"`
	// Populated for create failures.
	Name string `json:"name"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Code        respjson.Field
		Message     respjson.Field
		Operation   respjson.Field
		ConnectorID respjson.Field
		Name        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Per-connector failure surfaced alongside a successful workflow DAG save.

func (WorkflowNewResponseEnvelopeConnectorError) RawJSON added in v0.8.0

Returns the unmodified JSON received from the API

func (*WorkflowNewResponseEnvelopeConnectorError) UnmarshalJSON added in v0.8.0

func (r *WorkflowNewResponseEnvelopeConnectorError) UnmarshalJSON(data []byte) error

type WorkflowNodeResponse

type WorkflowNodeResponse struct {
	// Function (and version) executing at this call site.
	Function FunctionVersionIdentifier `json:"function" api:"required"`
	// Name of this call site, unique within the workflow version.
	Name string `json:"name" api:"required"`
	// Opaque free-form JSON object attached to this node on create/update. Returned
	// verbatim; never interpreted by the server.
	Metadata any `json:"metadata"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Function    respjson.Field
		Name        respjson.Field
		Metadata    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Read representation of a call-site node.

func (WorkflowNodeResponse) RawJSON

func (r WorkflowNodeResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowNodeResponse) UnmarshalJSON

func (r *WorkflowNodeResponse) UnmarshalJSON(data []byte) error

type WorkflowService

type WorkflowService struct {

	// Workflows orchestrate one or more functions into a directed acyclic graph (DAG)
	// for document processing.
	//
	// Use these endpoints to create, update, list, and manage workflows, and to invoke
	// them with file input via `POST /v3/workflows/{workflowName}/call`.
	//
	// The call endpoint accepts files as either multipart form data or JSON with
	// base64-encoded content. In the Bem CLI, use `@path/to/file` inside JSON values
	// to automatically read and encode files:
	//
	// “`
	//
	//	bem workflows call --workflow-name my-workflow \
	//	  --input.single-file '{"inputContent": "@file.pdf", "inputType": "pdf"}' \
	//	  --wait
	//
	// “`
	Versions WorkflowVersionService
	// contains filtered or unexported fields
}

Workflows orchestrate one or more functions into a directed acyclic graph (DAG) for document processing.

Use these endpoints to create, update, list, and manage workflows, and to invoke them with file input via `POST /v3/workflows/{workflowName}/call`.

The call endpoint accepts files as either multipart form data or JSON with base64-encoded content. In the Bem CLI, use `@path/to/file` inside JSON values to automatically read and encode files:

```

bem workflows call --workflow-name my-workflow \
  --input.single-file '{"inputContent": "@file.pdf", "inputType": "pdf"}' \
  --wait

```

WorkflowService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewWorkflowService method instead.

func NewWorkflowService

func NewWorkflowService(opts ...option.RequestOption) (r WorkflowService)

NewWorkflowService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*WorkflowService) Call

func (r *WorkflowService) Call(ctx context.Context, workflowName string, params WorkflowCallParams, opts ...option.RequestOption) (res *CallGetResponse, err error)

**Invoke a workflow.**

Submit the input file as either a multipart form request or a JSON request with base64-encoded file content. The workflow name is derived from the URL path.

## Input Formats

  • **Multipart form** (`multipart/form-data`): attach the file directly via the `file` or `files` fields. Set `wait` in the form body to control synchronous behaviour.
  • **JSON** (`application/json`): base64-encode the file content and set it in `input.singleFile.inputContent` or `input.batchFiles.inputs[*].inputContent`. Pass `wait=true` as a query parameter to control synchronous behaviour.

## Synchronous vs Asynchronous

By default the call is created asynchronously and this endpoint returns `202 Accepted` immediately with a `pending` call object. Set `wait` to `true` to block until the call completes (up to 30 seconds):

  • On success: returns `200 OK` with the completed call, `outputs` populated
  • On failure: returns `500 Internal Server Error` with the call and an `error` message
  • On timeout: returns `202 Accepted` with the still-running call

## Tracking

Poll `GET /v3/calls/{callID}` to check status, or configure a webhook subscription to receive events when the call finishes.

## CLI Usage

Use `@path/to/file` inside JSON string values to embed file contents automatically. Binary files (PDF, images, audio) are base64-encoded; text files are embedded as strings.

Single file (synchronous):

```bash

bem workflows call \
  --workflow-name my-workflow \
  --input.single-file '{"inputContent": "@invoice.pdf", "inputType": "pdf"}' \
  --wait

```

Single file (asynchronous, returns callID immediately):

```bash

bem workflows call \
  --workflow-name my-workflow \
  --input.single-file '{"inputContent": "@invoice.pdf", "inputType": "pdf"}'

```

Batch files:

```bash

bem workflows call \
  --workflow-name my-workflow \
  --input.batch-files '{"inputs": [{"inputContent": "@a.pdf", "inputType": "pdf"}, {"inputContent": "@b.png", "inputType": "png"}]}'

```

Alternative: pass the full `--input` flag as JSON:

```bash

bem workflows call \
  --workflow-name my-workflow \
  --input '{"singleFile": {"inputContent": "@invoice.pdf", "inputType": "pdf"}}' \
  --wait

```

**Important:** `--wait` is a boolean flag. Use `--wait` or `--wait=true`. Do **not** use `--wait true` (with a space) — the `true` will be parsed as an unexpected positional argument.

Supported `inputType` values: csv, docx, email, heic, heif, html, jpeg, json, m4a, mp3, pdf, png, text, wav, webp, xls, xlsx, xml.

func (*WorkflowService) Copy

**Copy a workflow to a new name.**

Forks the source workflow's current version into a brand-new workflow at `versionNum: 1`. The full node graph and edges are carried over, but the _functions_ the copied nodes reference are shared, not duplicated — both workflows now point at the same functions.

Useful for forking a production workflow to test a topology change without disturbing the live caller.

func (*WorkflowService) Delete

func (r *WorkflowService) Delete(ctx context.Context, workflowName string, opts ...option.RequestOption) (err error)

**Delete a workflow and every one of its versions.**

Permanent. Running and queued calls against this workflow continue to completion against the version they captured at call time; subsequent attempts to call the workflow return `404 Not Found`.

Functions referenced by the deleted workflow are not removed — they remain available to other workflows or for direct reference.

func (*WorkflowService) Get

func (r *WorkflowService) Get(ctx context.Context, workflowName string, opts ...option.RequestOption) (res *WorkflowGetResponse, err error)

**Retrieve a workflow's current version by name.**

Returns the full workflow record: `currentVersionNum`, `mainNodeName`, the `nodes` array (with each node's function reference and pinned `versionNum` if any), and the `edges` array. To inspect a historical version, use `GET /v3/workflows/{workflowName}/versions/{versionNum}`.

func (*WorkflowService) List

**List workflows in the current environment.**

Returns each workflow's current version, including its node graph and main node. Combine filters freely — they AND together.

## Filtering

  • `workflowIDs` / `workflowNames`: exact-match identity filters.
  • `displayName`: case-insensitive substring match.
  • `tags`: returns workflows tagged with any of the supplied tags.
  • `functionIDs` / `functionNames`: returns only workflows that reference the named functions in any node. Useful for "which workflows depend on this function?" lookups before changing or deleting a function.

## Pagination

Cursor-based with `startingAfter` and `endingBefore` (workflowIDs). Default limit 50, maximum 100.

func (*WorkflowService) ListAutoPaging

**List workflows in the current environment.**

Returns each workflow's current version, including its node graph and main node. Combine filters freely — they AND together.

## Filtering

  • `workflowIDs` / `workflowNames`: exact-match identity filters.
  • `displayName`: case-insensitive substring match.
  • `tags`: returns workflows tagged with any of the supplied tags.
  • `functionIDs` / `functionNames`: returns only workflows that reference the named functions in any node. Useful for "which workflows depend on this function?" lookups before changing or deleting a function.

## Pagination

Cursor-based with `startingAfter` and `endingBefore` (workflowIDs). Default limit 50, maximum 100.

func (*WorkflowService) New

func (r *WorkflowService) New(ctx context.Context, body WorkflowNewParams, opts ...option.RequestOption) (res *Workflow, err error)

**Create a workflow.**

A workflow is a directed acyclic graph of nodes (each pointing at a function) with one entry point (`mainNodeName`). The graph runs end-to-end on every call.

## Required structure

  • `name`: unique within the environment, alphanumeric plus hyphens and underscores.
  • `mainNodeName`: must match one of the `nodes[].name` values, and must not be the destination of any edge.
  • `nodes`: at least one. Each node has a unique `name` and a `function` reference (by `functionName` or `functionID`, optionally pinned to a `versionNum`).
  • `edges`: optional for single-node workflows. For branching sources (Classify, semantic Split), each edge carries a `destinationName` matching a `classifications[].name` or `itemClasses[].name` on the source function.

The created workflow is at `versionNum: 1`. Subsequent `PATCH /v3/workflows/{workflowName}` calls produce new versions.

## Common patterns

  • **Single-node**: one extract/classify function, no edges.
  • **Sequential**: extract → enrich → payload_shaping (linear edges).
  • **Branching**: classify → multiple extracts (one edge per classification name).
  • **Split-then-process**: split → multiple extracts (one edge per item class).

See [Workflows explained](/guide/workflows-explained) for end-to-end examples of each pattern.

func (*WorkflowService) Update

func (r *WorkflowService) Update(ctx context.Context, workflowName string, body WorkflowUpdateParams, opts ...option.RequestOption) (res *WorkflowUpdateResponse, err error)

**Update a workflow. Updates create a new version.**

The previous version remains addressable and immutable. Pending and running calls captured at the old version continue against it; new calls run against the new version.

## Topology updates

To change the graph you must provide `mainNodeName`, `nodes`, AND `edges` together — partial topology updates are rejected. The full graph is replaced atomically.

## Metadata-only updates

Omit all three fields to update only `displayName`, `tags`, or `name` while keeping the topology of the current version.

## Reverting

To roll back, fetch the desired prior version and resubmit its `mainNodeName`/`nodes`/`edges` as a new update. Versions themselves are immutable — there is no "pin to version N" operation at the workflow level (use `nodes[].function.versionNum` to pin individual functions).

type WorkflowUpdateParams

type WorkflowUpdateParams struct {
	// Human-readable display name.
	DisplayName param.Opt[string] `json:"displayName,omitzero"`
	// `mainNodeName`, `nodes`, and `edges` must be provided together to update the DAG
	// topology. If none are provided the topology is copied unchanged from the current
	// version.
	MainNodeName param.Opt[string] `json:"mainNodeName,omitzero"`
	// New name for the workflow (renames it). Must match `^[a-zA-Z0-9_-]{1,128}$`.
	Name param.Opt[string] `json:"name,omitzero"`
	// Declarative, full-desired-state array of connectors. If omitted, existing
	// connectors are left unchanged. If provided, it replaces the current set: entries
	// with `connectorID` are updates, entries without are creates, and existing
	// connectors whose `connectorID` is absent are deleted.
	Connectors []WorkflowUpdateParamsConnector `json:"connectors,omitzero"`
	Edges      []WorkflowUpdateParamsEdge      `json:"edges,omitzero"`
	Nodes      []WorkflowUpdateParamsNode      `json:"nodes,omitzero"`
	// Tags to categorize and organize the workflow.
	Tags []string `json:"tags,omitzero"`
	// contains filtered or unexported fields
}

func (WorkflowUpdateParams) MarshalJSON

func (r WorkflowUpdateParams) MarshalJSON() (data []byte, err error)

func (*WorkflowUpdateParams) UnmarshalJSON

func (r *WorkflowUpdateParams) UnmarshalJSON(data []byte) error

type WorkflowUpdateParamsConnector added in v0.7.0

type WorkflowUpdateParamsConnector struct {
	// Human-friendly connector name.
	Name string `json:"name" api:"required"`
	// Discriminator for a workflow connector. V3 supports `paragon` only.
	//
	// Any of "paragon".
	Type string `json:"type,omitzero" api:"required"`
	// Present → update. Absent → create.
	ConnectorID param.Opt[string] `json:"connectorID,omitzero"`
	// Request-side config block for a Paragon connector. Fields absent on update are
	// unchanged.
	Paragon WorkflowUpdateParamsConnectorParagon `json:"paragon,omitzero"`
	// contains filtered or unexported fields
}

Create/update entry for a connector inline with the workflow.

The properties Name, Type are required.

func (WorkflowUpdateParamsConnector) MarshalJSON added in v0.7.0

func (r WorkflowUpdateParamsConnector) MarshalJSON() (data []byte, err error)

func (*WorkflowUpdateParamsConnector) UnmarshalJSON added in v0.7.0

func (r *WorkflowUpdateParamsConnector) UnmarshalJSON(data []byte) error

type WorkflowUpdateParamsConnectorParagon added in v0.7.0

type WorkflowUpdateParamsConnectorParagon struct {
	// Paragon integration key. Required on create.
	Integration param.Opt[string] `json:"integration,omitzero"`
	// Opaque per-integration configuration. Required on create.
	Configuration any `json:"configuration,omitzero"`
	// contains filtered or unexported fields
}

Request-side config block for a Paragon connector. Fields absent on update are unchanged.

func (WorkflowUpdateParamsConnectorParagon) MarshalJSON added in v0.7.0

func (r WorkflowUpdateParamsConnectorParagon) MarshalJSON() (data []byte, err error)

func (*WorkflowUpdateParamsConnectorParagon) UnmarshalJSON added in v0.7.0

func (r *WorkflowUpdateParamsConnectorParagon) UnmarshalJSON(data []byte) error

type WorkflowUpdateParamsEdge

type WorkflowUpdateParamsEdge struct {
	// Name of the destination node.
	DestinationNodeName string `json:"destinationNodeName" api:"required"`
	// Name of the source node.
	SourceNodeName string `json:"sourceNodeName" api:"required"`
	// Labelled outlet on the source node that activates this edge. Omit for the
	// default (unlabelled) outlet.
	DestinationName param.Opt[string] `json:"destinationName,omitzero"`
	// Opaque free-form JSON object attached to this edge. Stored and returned
	// verbatim; the server does not interpret it.
	Metadata any `json:"metadata,omitzero"`
	// contains filtered or unexported fields
}

A directed edge between two named call-site nodes.

The properties DestinationNodeName, SourceNodeName are required.

func (WorkflowUpdateParamsEdge) MarshalJSON

func (r WorkflowUpdateParamsEdge) MarshalJSON() (data []byte, err error)

func (*WorkflowUpdateParamsEdge) UnmarshalJSON

func (r *WorkflowUpdateParamsEdge) UnmarshalJSON(data []byte) error

type WorkflowUpdateParamsNode

type WorkflowUpdateParamsNode struct {
	// The function (and version) to execute at this call site.
	Function FunctionVersionIdentifierParam `json:"function,omitzero" api:"required"`
	// Name for this call site. Must be unique within the workflow version. Defaults to
	// the function's own name when omitted.
	Name param.Opt[string] `json:"name,omitzero"`
	// Opaque free-form JSON object attached to this node. Stored and returned
	// verbatim; the server does not interpret it. Intended for client-side concerns
	// such as canvas display properties (position, color, collapsed state, etc.).
	Metadata any `json:"metadata,omitzero"`
	// contains filtered or unexported fields
}

A single function call-site node in a workflow DAG.

The property Function is required.

func (WorkflowUpdateParamsNode) MarshalJSON

func (r WorkflowUpdateParamsNode) MarshalJSON() (data []byte, err error)

func (*WorkflowUpdateParamsNode) UnmarshalJSON

func (r *WorkflowUpdateParamsNode) UnmarshalJSON(data []byte) error

type WorkflowUpdateResponse

type WorkflowUpdateResponse struct {
	// Per-connector failures from the diff/apply phase. Empty or omitted when all
	// operations succeeded.
	ConnectorErrors []WorkflowUpdateResponseConnectorError `json:"connectorErrors"`
	// Error message if the workflow update failed.
	Error string `json:"error"`
	// V3 read representation of a workflow version.
	Workflow Workflow `json:"workflow"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ConnectorErrors respjson.Field
		Error           respjson.Field
		Workflow        respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WorkflowUpdateResponse) RawJSON

func (r WorkflowUpdateResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowUpdateResponse) UnmarshalJSON

func (r *WorkflowUpdateResponse) UnmarshalJSON(data []byte) error

type WorkflowUpdateResponseConnectorError added in v0.7.0

type WorkflowUpdateResponseConnectorError struct {
	// Machine-readable error code.
	Code string `json:"code" api:"required"`
	// Human-readable error message.
	Message string `json:"message" api:"required"`
	// Which diff operation was attempted.
	//
	// Any of "create", "update", "delete".
	Operation string `json:"operation" api:"required"`
	// Populated for update/delete failures.
	ConnectorID string `json:"connectorID"`
	// Populated for create failures.
	Name string `json:"name"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Code        respjson.Field
		Message     respjson.Field
		Operation   respjson.Field
		ConnectorID respjson.Field
		Name        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Per-connector failure surfaced alongside a successful workflow DAG save.

func (WorkflowUpdateResponseConnectorError) RawJSON added in v0.7.0

Returns the unmodified JSON received from the API

func (*WorkflowUpdateResponseConnectorError) UnmarshalJSON added in v0.7.0

func (r *WorkflowUpdateResponseConnectorError) UnmarshalJSON(data []byte) error

type WorkflowUsageInfo

type WorkflowUsageInfo struct {
	// Current version number of workflow, provided for reference - compare to
	// usedInWorkflowVersionNums to see whether the current version of the workflow
	// uses this function version.
	CurrentVersionNum int64 `json:"currentVersionNum" api:"required"`
	// Version numbers of workflows that this function version is used in.
	UsedInWorkflowVersionNums []int64 `json:"usedInWorkflowVersionNums" api:"required"`
	// Unique identifier of workflow.
	WorkflowID string `json:"workflowID" api:"required"`
	// Name of workflow.
	WorkflowName string `json:"workflowName" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CurrentVersionNum         respjson.Field
		UsedInWorkflowVersionNums respjson.Field
		WorkflowID                respjson.Field
		WorkflowName              respjson.Field
		ExtraFields               map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WorkflowUsageInfo) RawJSON

func (r WorkflowUsageInfo) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowUsageInfo) UnmarshalJSON

func (r *WorkflowUsageInfo) UnmarshalJSON(data []byte) error

type WorkflowVersionGetParams

type WorkflowVersionGetParams struct {
	WorkflowName string `path:"workflowName" api:"required" json:"-"`
	// contains filtered or unexported fields
}

type WorkflowVersionGetResponse

type WorkflowVersionGetResponse struct {
	// Error message if the workflow version retrieval failed.
	Error string `json:"error"`
	// V3 read representation of a workflow version.
	Workflow Workflow `json:"workflow"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Error       respjson.Field
		Workflow    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WorkflowVersionGetResponse) RawJSON

func (r WorkflowVersionGetResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WorkflowVersionGetResponse) UnmarshalJSON

func (r *WorkflowVersionGetResponse) UnmarshalJSON(data []byte) error

type WorkflowVersionListParams

type WorkflowVersionListParams struct {
	EndingBefore  param.Opt[int64] `query:"endingBefore,omitzero" json:"-"`
	Limit         param.Opt[int64] `query:"limit,omitzero" json:"-"`
	StartingAfter param.Opt[int64] `query:"startingAfter,omitzero" json:"-"`
	// Any of "asc", "desc".
	SortOrder WorkflowVersionListParamsSortOrder `query:"sortOrder,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (WorkflowVersionListParams) URLQuery

func (r WorkflowVersionListParams) URLQuery() (v url.Values, err error)

URLQuery serializes WorkflowVersionListParams's query parameters as `url.Values`.

type WorkflowVersionListParamsSortOrder

type WorkflowVersionListParamsSortOrder string
const (
	WorkflowVersionListParamsSortOrderAsc  WorkflowVersionListParamsSortOrder = "asc"
	WorkflowVersionListParamsSortOrderDesc WorkflowVersionListParamsSortOrder = "desc"
)

type WorkflowVersionService

type WorkflowVersionService struct {
	// contains filtered or unexported fields
}

Workflows orchestrate one or more functions into a directed acyclic graph (DAG) for document processing.

Use these endpoints to create, update, list, and manage workflows, and to invoke them with file input via `POST /v3/workflows/{workflowName}/call`.

The call endpoint accepts files as either multipart form data or JSON with base64-encoded content. In the Bem CLI, use `@path/to/file` inside JSON values to automatically read and encode files:

```

bem workflows call --workflow-name my-workflow \
  --input.single-file '{"inputContent": "@file.pdf", "inputType": "pdf"}' \
  --wait

```

WorkflowVersionService contains methods and other services that help with interacting with the bem API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewWorkflowVersionService method instead.

func NewWorkflowVersionService

func NewWorkflowVersionService(opts ...option.RequestOption) (r WorkflowVersionService)

NewWorkflowVersionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*WorkflowVersionService) Get

**Retrieve a specific historical version of a workflow.**

Versions are immutable. Use this endpoint to see what a workflow looked like at the moment a particular call was made — every call record carries the workflow `versionNum` it ran against.

func (*WorkflowVersionService) List

**List every version of a workflow.**

Versions are immutable. Each row captures what the workflow looked like between updates: graph topology, metadata, and timestamps. Returns newest-first by default. Cursor pagination via `startingAfter` / `endingBefore` over `versionNum`.

func (*WorkflowVersionService) ListAutoPaging

**List every version of a workflow.**

Versions are immutable. Each row captures what the workflow looked like between updates: graph topology, metadata, and timestamps. Returns newest-first by default. Cursor pagination via `startingAfter` / `endingBefore` over `versionNum`.

Directories

Path Synopsis
encoding/json
Package json implements encoding and decoding of JSON as defined in RFC 7159.
Package json implements encoding and decoding of JSON as defined in RFC 7159.
encoding/json/shims
This package provides shims over Go 1.2{2,3} APIs which are missing from Go 1.22, and used by the Go 1.24 encoding/json package.
This package provides shims over Go 1.2{2,3} APIs which are missing from Go 1.22, and used by the Go 1.24 encoding/json package.
packages
shared

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL