greenflashpublicapi

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

README

Greenflash Go API Library

Go Reference

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

It is generated with Stainless.

MCP Server

Use the Greenflash 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/greenflash-ai/go" // imported as greenflashpublicapi
)

Or to pin the version:

go get -u 'github.com/greenflash-ai/go@v0.1.1'

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/greenflash-ai/go"
	"github.com/greenflash-ai/go/option"
)

func main() {
	client := greenflashpublicapi.NewClient(
		option.WithAPIKey("My API Key"), // defaults to os.LookupEnv("GREENFLASH_API_KEY")
	)
	createMessageResponse, err := client.Messages.New(context.TODO(), greenflashpublicapi.MessageNewParams{
		CreateMessageParams: greenflashpublicapi.CreateMessageParams{
			ExternalUserID: "user-123",
			Messages:       []greenflashpublicapi.MessageItemParam{{}, {}, {}, {}, {}},
		},
	})
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("%+v\n", createMessageResponse.ConversationID)
}

Request fields

The greenflashpublicapi 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 `json:"...,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, greenflashpublicapi.String(string), greenflashpublicapi.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 := greenflashpublicapi.ExampleParams{
	ID:   "id_xxx",                          // required property
	Name: greenflashpublicapi.String("..."), // optional property

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

	Origin: greenflashpublicapi.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[greenflashpublicapi.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 := greenflashpublicapi.NewClient(
	// Adds a header to every request made by the client
	option.WithHeader("X-Some-Header", "custom_header_info"),
)

client.Messages.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:

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.:

Errors

When the API returns a non-success status code, we return an error with type *greenflashpublicapi.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.Messages.New(context.TODO(), greenflashpublicapi.MessageNewParams{
	CreateMessageParams: greenflashpublicapi.CreateMessageParams{
		ExternalUserID: "user-123",
		Messages:       []greenflashpublicapi.MessageItemParam{{}, {}, {}, {}, {}},
	},
})
if err != nil {
	var apierr *greenflashpublicapi.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 "/messages": 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.Messages.New(
	ctx,
	greenflashpublicapi.MessageNewParams{
		CreateMessageParams: greenflashpublicapi.CreateMessageParams{
			ExternalUserID: "user-123",
			Messages:       []greenflashpublicapi.MessageItemParam{{}, {}, {}, {}, {}},
		},
	},
	// 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 greenflashpublicapi.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 := greenflashpublicapi.NewClient(
	option.WithMaxRetries(0), // default is 2
)

// Override per-request:
client.Messages.New(
	context.TODO(),
	greenflashpublicapi.MessageNewParams{
		CreateMessageParams: greenflashpublicapi.CreateMessageParams{
			ExternalUserID: "user-123",
			Messages:       []greenflashpublicapi.MessageItemParam{{}, {}, {}, {}, {}},
		},
	},
	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
createMessageResponse, err := client.Messages.New(
	context.TODO(),
	greenflashpublicapi.MessageNewParams{
		CreateMessageParams: greenflashpublicapi.CreateMessageParams{
			ExternalUserID: "user-123",
			Messages:       []greenflashpublicapi.MessageItemParam{{}, {}, {}, {}, {}},
		},
	},
	option.WithResponseInto(&response),
)
if err != nil {
	// handle error
}
fmt.Printf("%+v\n", createMessageResponse)

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: greenflashpublicapi.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 := greenflashpublicapi.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 (GREENFLASH_API_KEY, GREENFLASH_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 Client

type Client struct {

	// Capture interactions between users and AI
	Messages MessageService
	// Capture interactions between users and AI
	Interactions InteractionService
	// Manage users
	Users UserService
	// Capture interactions between users and AI
	Ratings RatingService
	// Manage users
	Organizations OrganizationService
	// Manage prompts
	Prompts PromptService
	// Capture business events
	Events EventService
	// contains filtered or unexported fields
}

Client creates a struct with services and top level methods that help with interacting with the Greenflash 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 (GREENFLASH_API_KEY, GREENFLASH_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 ComponentInputParam

type ComponentInputParam struct {
	// The content of the component.
	Content string `json:"content" api:"required"`
	// The Greenflash component ID.
	ComponentID param.Opt[string] `json:"componentId,omitzero" format:"uuid"`
	// Your external identifier for the component.
	ExternalComponentID param.Opt[string] `json:"externalComponentId,omitzero"`
	// Whether the component content changes dynamically.
	IsDynamic param.Opt[bool] `json:"isDynamic,omitzero"`
	// Component name.
	Name param.Opt[string] `json:"name,omitzero"`
	// Component source: customer, participant, greenflash, or agent.
	//
	// Any of "customer", "participant", "greenflash", "agent".
	Source ComponentInputSource `json:"source,omitzero"`
	// Component type: system, user, tool, guardrail, rag, agent, or a custom type
	// (other).
	//
	// Any of "system", "user", "tool", "guardrail", "rag", "agent", "other".
	Type ComponentInputType `json:"type,omitzero"`
	// contains filtered or unexported fields
}

The property Content is required.

func (ComponentInputParam) MarshalJSON

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

func (*ComponentInputParam) UnmarshalJSON

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

type ComponentInputSource

type ComponentInputSource string

Component source: customer, participant, greenflash, or agent.

const (
	ComponentInputSourceCustomer    ComponentInputSource = "customer"
	ComponentInputSourceParticipant ComponentInputSource = "participant"
	ComponentInputSourceGreenflash  ComponentInputSource = "greenflash"
	ComponentInputSourceAgent       ComponentInputSource = "agent"
)

type ComponentInputType

type ComponentInputType string

Component type: system, user, tool, guardrail, rag, agent, or a custom type (other).

const (
	ComponentInputTypeSystem    ComponentInputType = "system"
	ComponentInputTypeUser      ComponentInputType = "user"
	ComponentInputTypeTool      ComponentInputType = "tool"
	ComponentInputTypeGuardrail ComponentInputType = "guardrail"
	ComponentInputTypeRag       ComponentInputType = "rag"
	ComponentInputTypeAgent     ComponentInputType = "agent"
	ComponentInputTypeOther     ComponentInputType = "other"
)

type ComponentUpdateParam

type ComponentUpdateParam struct {
	// Updated component content.
	Content string `json:"content" api:"required"`
	// The Greenflash component ID.
	ComponentID param.Opt[string] `json:"componentId,omitzero" format:"uuid"`
	// External component identifier.
	ExternalComponentID param.Opt[string] `json:"externalComponentId,omitzero"`
	// Dynamic flag.
	IsDynamic param.Opt[bool] `json:"isDynamic,omitzero"`
	// Component name.
	Name param.Opt[string] `json:"name,omitzero"`
	// Component source.
	//
	// Any of "customer", "participant", "greenflash", "agent".
	Source ComponentUpdateSource `json:"source,omitzero"`
	// Component type: system, user, tool, guardrail, rag, agent, or a custom type
	// (other).
	//
	// Any of "system", "user", "tool", "guardrail", "rag", "agent", "other".
	Type ComponentUpdateType `json:"type,omitzero"`
	// contains filtered or unexported fields
}

The property Content is required.

func (ComponentUpdateParam) MarshalJSON

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

func (*ComponentUpdateParam) UnmarshalJSON

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

type ComponentUpdateSource

type ComponentUpdateSource string

Component source.

const (
	ComponentUpdateSourceCustomer    ComponentUpdateSource = "customer"
	ComponentUpdateSourceParticipant ComponentUpdateSource = "participant"
	ComponentUpdateSourceGreenflash  ComponentUpdateSource = "greenflash"
	ComponentUpdateSourceAgent       ComponentUpdateSource = "agent"
)

type ComponentUpdateType

type ComponentUpdateType string

Component type: system, user, tool, guardrail, rag, agent, or a custom type (other).

const (
	ComponentUpdateTypeSystem    ComponentUpdateType = "system"
	ComponentUpdateTypeUser      ComponentUpdateType = "user"
	ComponentUpdateTypeTool      ComponentUpdateType = "tool"
	ComponentUpdateTypeGuardrail ComponentUpdateType = "guardrail"
	ComponentUpdateTypeRag       ComponentUpdateType = "rag"
	ComponentUpdateTypeAgent     ComponentUpdateType = "agent"
	ComponentUpdateTypeOther     ComponentUpdateType = "other"
)

type CreateEventParams

type CreateEventParams struct {
	// The specific name or category of the event being tracked (e.g., "trial_started",
	// "signup", "feature_usage"). This helps categorize events for analysis and often
	// pairs with "value" to define the outcome.
	EventType string `json:"eventType" api:"required"`
	// The unique identifier of the Greenflash product associated with this event. This
	// links the event to a specific product context.
	ProductID string `json:"productId" api:"required" format:"uuid"`
	// The specific value associated with the event (e.g., "99.00", "5",
	// "premium_plan"). This pairs with "valueType" and "eventType" to define the
	// magnitude or content of the event.
	Value string `json:"value" api:"required"`
	// The unique Greenflash identifier for the conversation. Links the event to a
	// specific chat session in Greenflash.
	ConversationID param.Opt[string] `json:"conversationId,omitzero" format:"uuid"`
	// The ISO 8601 timestamp of when the event actually occurred. Defaults to the
	// current time if not provided. Useful for backdating historical events.
	EventAt param.Opt[time.Time] `json:"eventAt,omitzero" format:"date-time"`
	// Your system's unique identifier for the conversation or thread where this event
	// occurred.
	ExternalConversationID param.Opt[string] `json:"externalConversationId,omitzero"`
	// Your system's unique identifier for the organization associated with this event.
	// Used to map events to your customer accounts.
	ExternalOrganizationID param.Opt[string] `json:"externalOrganizationId,omitzero"`
	// Your system's unique identifier for the user associated with this event. Used to
	// map Greenflash events back to your user records.
	ExternalUserID param.Opt[string] `json:"externalUserId,omitzero"`
	// When true, bypasses sampling and ensures this event is always ingested
	// regardless of sampleRate. Use for critical events that must be captured.
	ForceSample param.Opt[bool] `json:"forceSample,omitzero"`
	// A unique key for idempotency. If you retry a request with the same insertId, it
	// prevents creating a duplicate event record.
	InsertID param.Opt[string] `json:"insertId,omitzero"`
	// The unique Greenflash identifier for the organization. Provide this if you have
	// the Greenflash Organization ID.
	OrganizationID param.Opt[string] `json:"organizationId,omitzero" format:"uuid"`
	// A precise numeric score between -1.0 and 1.0 for direct control over the quality
	// impact. If omitted, it is automatically derived from the "influence" field.
	QualityImpactScore param.Opt[float64] `json:"qualityImpactScore,omitzero"`
	// Controls the percentage of requests that are ingested (0.0 to 1.0). For example,
	// 0.1 means 10% of events will be stored. Defaults to 1.0 (all events ingested).
	// Sampling is deterministic based on event type and organization.
	SampleRate param.Opt[float64] `json:"sampleRate,omitzero"`
	// The unique Greenflash identifier for the user. Provide this if you already have
	// the Greenflash User ID; otherwise, use "externalUserId".
	UserID param.Opt[string] `json:"userId,omitzero" format:"uuid"`
	// A high-level categorization of how this event generally "changed things" or
	// influenced quality (positive, negative, or neutral). Use this for broad
	// classification of outcomes.
	//
	// Any of "positive", "negative", "neutral".
	Influence CreateEventParamsInfluence `json:"influence,omitzero"`
	// A key-value object for storing additional, unstructured context about the event
	// (e.g., { source: "web_app", campaign_id: "123" }). Useful for custom filtering.
	Properties map[string]any `json:"properties,omitzero"`
	// Defines the format of the "value" field (currency, numeric, or text). This
	// ensures the value is interpreted and processed correctly.
	//
	// Any of "currency", "numeric", "text", "boolean".
	ValueType CreateEventParamsValueType `json:"valueType,omitzero"`
	// contains filtered or unexported fields
}

Request payload for creating events.

The properties EventType, ProductID, Value are required.

func (CreateEventParams) MarshalJSON

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

func (*CreateEventParams) UnmarshalJSON

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

type CreateEventParamsInfluence

type CreateEventParamsInfluence string

A high-level categorization of how this event generally "changed things" or influenced quality (positive, negative, or neutral). Use this for broad classification of outcomes.

const (
	CreateEventParamsInfluencePositive CreateEventParamsInfluence = "positive"
	CreateEventParamsInfluenceNegative CreateEventParamsInfluence = "negative"
	CreateEventParamsInfluenceNeutral  CreateEventParamsInfluence = "neutral"
)

type CreateEventParamsValueType

type CreateEventParamsValueType string

Defines the format of the "value" field (currency, numeric, or text). This ensures the value is interpreted and processed correctly.

const (
	CreateEventParamsValueTypeCurrency CreateEventParamsValueType = "currency"
	CreateEventParamsValueTypeNumeric  CreateEventParamsValueType = "numeric"
	CreateEventParamsValueTypeText     CreateEventParamsValueType = "text"
	CreateEventParamsValueTypeBoolean  CreateEventParamsValueType = "boolean"
)

type CreateEventResponse

type CreateEventResponse struct {
	// The unique Greenflash ID of the event record that was created.
	EventID string `json:"eventId" api:"required"`
	// Whether the API call was successful.
	Success bool `json:"success" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EventID     respjson.Field
		Success     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Success response for event creation.

func (CreateEventResponse) RawJSON

func (r CreateEventResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CreateEventResponse) UnmarshalJSON

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

type CreateMessageParams

type CreateMessageParams struct {
	// Your external user ID that will be mapped to a user in our system.
	ExternalUserID string `json:"externalUserId" api:"required"`
	// Array of conversation messages.
	Messages []MessageItemParam `json:"messages,omitzero" api:"required"`
	// The Greenflash conversation ID. When provided, updates an existing conversation
	// instead of creating a new one. Either conversationId, externalConversationId,
	// productId must be provided.
	ConversationID param.Opt[string] `json:"conversationId,omitzero" format:"uuid"`
	// Your external identifier for the conversation. Either conversationId,
	// externalConversationId, productId must be provided.
	ExternalConversationID param.Opt[string] `json:"externalConversationId,omitzero"`
	// Your unique identifier for the organization this user belongs to. If provided,
	// the user will be associated with this organization.
	ExternalOrganizationID param.Opt[string] `json:"externalOrganizationId,omitzero"`
	// When true, bypasses sampling and ensures this request is always ingested
	// regardless of sampleRate. Use for critical conversations that must be captured.
	ForceSample param.Opt[bool] `json:"forceSample,omitzero"`
	// The AI model used for the conversation.
	Model param.Opt[string] `json:"model,omitzero"`
	// The Greenflash product this conversation belongs to. Either conversationId,
	// externalConversationId, productId must be provided.
	ProductID param.Opt[string] `json:"productId,omitzero" format:"uuid"`
	// Controls the percentage of requests that are ingested (0.0 to 1.0). For example,
	// 0.1 means 10% of requests will be stored. Defaults to 1.0 (all requests
	// ingested). Sampling is deterministic based on conversation ID.
	SampleRate param.Opt[float64] `json:"sampleRate,omitzero"`
	// Additional data about the conversation.
	Properties map[string]any `json:"properties,omitzero"`
	// System prompt for the conversation. Can be a simple string or a prompt object
	// with components.
	SystemPrompt SystemPromptUnionParam `json:"systemPrompt,omitzero"`
	// contains filtered or unexported fields
}

Request payload for logging conversations and messages.

The properties ExternalUserID, Messages are required.

func (CreateMessageParams) MarshalJSON

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

func (*CreateMessageParams) UnmarshalJSON

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

type CreateMessageResponse

type CreateMessageResponse struct {
	// The ID of the conversation that was created or updated.
	ConversationID string `json:"conversationId" api:"required" format:"uuid"`
	// The messages that were processed.
	Messages []CreateMessageResponseMessage `json:"messages" api:"required"`
	// Whether the API call was successful.
	Success bool `json:"success" api:"required"`
	// The component IDs used internally to track the system prompt components.
	SystemPromptComponentIDs []string `json:"systemPromptComponentIds" api:"required" format:"uuid"`
	// The prompt ID used internally to track the system prompt.
	SystemPromptPromptID string `json:"systemPromptPromptId" api:"required" format:"uuid"`
	// Template variables used or detected for this conversation.
	PromptVariables map[string]string `json:"promptVariables"`
	// Template match info when content was auto-matched against an existing template.
	TemplateMatch CreateMessageResponseTemplateMatch `json:"templateMatch"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ConversationID           respjson.Field
		Messages                 respjson.Field
		Success                  respjson.Field
		SystemPromptComponentIDs respjson.Field
		SystemPromptPromptID     respjson.Field
		PromptVariables          respjson.Field
		TemplateMatch            respjson.Field
		ExtraFields              map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Success response for message logging.

func (CreateMessageResponse) RawJSON

func (r CreateMessageResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CreateMessageResponse) UnmarshalJSON

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

type CreateMessageResponseMessage

type CreateMessageResponseMessage struct {
	// The internal Greenflash message ID.
	MessageID string `json:"messageId" api:"required"`
	// The type of the message that was created.
	MessageType string `json:"messageType" api:"required"`
	// Whether the message was newly created or deduplicated. Messages with an
	// externalMessageId that already exists in the conversation are automatically
	// skipped and returned with status "deduplicated".
	//
	// Any of "created", "deduplicated".
	Status string `json:"status" api:"required"`
	// Your external identifier for the message, if provided.
	ExternalMessageID string `json:"externalMessageId"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		MessageID         respjson.Field
		MessageType       respjson.Field
		Status            respjson.Field
		ExternalMessageID respjson.Field
		ExtraFields       map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CreateMessageResponseMessage) RawJSON

Returns the unmodified JSON received from the API

func (*CreateMessageResponseMessage) UnmarshalJSON

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

type CreateMessageResponseTemplateMatch

type CreateMessageResponseTemplateMatch struct {
	Matched bool `json:"matched" api:"required"`
	// Any of "exact", "high", "medium".
	Confidence        string            `json:"confidence"`
	DetectedVariables map[string]string `json:"detectedVariables"`
	PromptID          string            `json:"promptId" format:"uuid"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Matched           respjson.Field
		Confidence        respjson.Field
		DetectedVariables respjson.Field
		PromptID          respjson.Field
		ExtraFields       map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Template match info when content was auto-matched against an existing template.

func (CreateMessageResponseTemplateMatch) RawJSON

Returns the unmodified JSON received from the API

func (*CreateMessageResponseTemplateMatch) UnmarshalJSON

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

type CreateOrganizationParams

type CreateOrganizationParams struct {
	// Your unique identifier for the organization. Use this same ID in other API calls
	// to reference this organization.
	ExternalOrganizationID string `json:"externalOrganizationId" api:"required"`
	// The organization's name.
	Name param.Opt[string] `json:"name,omitzero"`
	// Custom organization properties.
	Properties map[string]any `json:"properties,omitzero"`
	// contains filtered or unexported fields
}

Request payload for creating a new organization.

The property ExternalOrganizationID is required.

func (CreateOrganizationParams) MarshalJSON

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

func (*CreateOrganizationParams) UnmarshalJSON

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

type CreateOrganizationResponse

type CreateOrganizationResponse struct {
	// The organization that was created or updated.
	Organization TenantOrganization `json:"organization" api:"required"`
	// Whether the API call was successful.
	Success bool `json:"success" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Organization respjson.Field
		Success      respjson.Field
		ExtraFields  map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Success response for organization creation.

func (CreateOrganizationResponse) RawJSON

func (r CreateOrganizationResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CreateOrganizationResponse) UnmarshalJSON

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

type CreatePromptParams

type CreatePromptParams struct {
	// Array of component objects.
	Components []ComponentInputParam `json:"components,omitzero" api:"required"`
	// Prompt name.
	Name string `json:"name" api:"required"`
	// Product this prompt will map to.
	ProductID string `json:"productId" api:"required" format:"uuid"`
	// Role key in the product mapping (e.g. "agent tool").
	Role string `json:"role" api:"required"`
	// Prompt description.
	Description param.Opt[string] `json:"description,omitzero"`
	// Your external identifier for the prompt.
	ExternalPromptID param.Opt[string] `json:"externalPromptId,omitzero"`
	// Prompt source.
	//
	// Any of "customer", "participant", "greenflash", "agent".
	Source CreatePromptParamsSource `json:"source,omitzero"`
	// contains filtered or unexported fields
}

The properties Components, Name, ProductID, Role are required.

func (CreatePromptParams) MarshalJSON

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

func (*CreatePromptParams) UnmarshalJSON

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

type CreatePromptParamsSource

type CreatePromptParamsSource string

Prompt source.

const (
	CreatePromptParamsSourceCustomer    CreatePromptParamsSource = "customer"
	CreatePromptParamsSourceParticipant CreatePromptParamsSource = "participant"
	CreatePromptParamsSourceGreenflash  CreatePromptParamsSource = "greenflash"
	CreatePromptParamsSourceAgent       CreatePromptParamsSource = "agent"
)

type CreatePromptResponse

type CreatePromptResponse struct {
	// The IDs of the created prompt components.
	ComponentIDs []string `json:"componentIds" api:"required" format:"uuid"`
	// The created prompt ID.
	PromptID string `json:"promptId" api:"required" format:"uuid"`
	// The created version ID. Version is created but not activated (activation happens
	// via UI or Messages API).
	VersionID string `json:"versionId" api:"required" format:"uuid"`
	// The external prompt ID.
	ExternalPromptID string `json:"externalPromptId"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ComponentIDs     respjson.Field
		PromptID         respjson.Field
		VersionID        respjson.Field
		ExternalPromptID respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CreatePromptResponse) RawJSON

func (r CreatePromptResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CreatePromptResponse) UnmarshalJSON

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

type CreateUserParams

type CreateUserParams struct {
	// Your unique identifier for the user. Use this same ID in other API calls to
	// reference this user.
	ExternalUserID string `json:"externalUserId" api:"required"`
	// Whether to anonymize the user's personal information. Defaults to false.
	Anonymized param.Opt[bool] `json:"anonymized,omitzero"`
	// The user's email address.
	Email param.Opt[string] `json:"email,omitzero" format:"email"`
	// Your unique identifier for the organization this user belongs to. If provided,
	// the user will be associated with this organization.
	ExternalOrganizationID param.Opt[string] `json:"externalOrganizationId,omitzero"`
	// The user's full name.
	Name param.Opt[string] `json:"name,omitzero"`
	// The Greenflash organization ID that the user belongs to.
	OrganizationID param.Opt[string] `json:"organizationId,omitzero" format:"uuid"`
	// The user's phone number.
	Phone param.Opt[string] `json:"phone,omitzero"`
	// Additional data about the user (e.g., plan type, preferences).
	Properties map[string]any `json:"properties,omitzero"`
	// contains filtered or unexported fields
}

Request payload for creating a new user profile.

The property ExternalUserID is required.

func (CreateUserParams) MarshalJSON

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

func (*CreateUserParams) UnmarshalJSON

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

type CreateUserResponse

type CreateUserResponse struct {
	// The user profile.
	Participant Participant `json:"participant" api:"required"`
	// Whether the API call was successful.
	Success bool `json:"success" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Participant respjson.Field
		Success     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Success response for user creation.

func (CreateUserResponse) RawJSON

func (r CreateUserResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CreateUserResponse) UnmarshalJSON

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

type DeletePromptResponse

type DeletePromptResponse struct {
	// ISO 8601 timestamp when archived.
	ArchivedAt string `json:"archivedAt" api:"required"`
	// The archived prompt ID.
	PromptID string `json:"promptId" api:"required" format:"uuid"`
	// The external prompt ID.
	ExternalPromptID string `json:"externalPromptId"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ArchivedAt       respjson.Field
		PromptID         respjson.Field
		ExternalPromptID respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (DeletePromptResponse) RawJSON

func (r DeletePromptResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*DeletePromptResponse) UnmarshalJSON

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

type Error

type Error = apierror.Error

type EventNewParams

type EventNewParams struct {
	// Request payload for creating events.
	CreateEventParams CreateEventParams
	// contains filtered or unexported fields
}

func (EventNewParams) MarshalJSON

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

func (*EventNewParams) UnmarshalJSON

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

type EventService

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

Capture business events

EventService contains methods and other services that help with interacting with the Greenflash 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

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) New

Track timestamped events representing user or organization actions. Events are used to track important business outcomes (signups, conversions, upgrades, cancellations, etc.) and integrate them into Greenflash's quality metrics. Each event can be optionally linked to a conversation, user, and organization.

type GetInteractionAnalyticsResponse

type GetInteractionAnalyticsResponse struct {
	// Average sentiment across user messages.
	AverageUserSentiment GetInteractionAnalyticsResponseAverageUserSentiment `json:"averageUserSentiment" api:"required"`
	// How sentiment changed during the interaction.
	ChangeInUserSentiment GetInteractionAnalyticsResponseChangeInUserSentiment `json:"changeInUserSentiment" api:"required"`
	// Commercial intent detected.
	CommercialIntent GetInteractionAnalyticsResponseCommercialIntent `json:"commercialIntent" api:"required"`
	// Quality index score for the interaction.
	ConversationQualityIndex float64 `json:"conversationQualityIndex" api:"required"`
	// Frustration level detected.
	Frustration GetInteractionAnalyticsResponseFrustration `json:"frustration" api:"required"`
	// Number of messages in the interaction.
	MessageCount float64 `json:"messageCount" api:"required"`
	// Most common emotion expressed by user.
	MostCommonUserEmotion string `json:"mostCommonUserEmotion" api:"required"`
	// User rating for this interaction.
	Rating float64 `json:"rating" api:"required"`
	// Struggle level detected.
	Struggle GetInteractionAnalyticsResponseStruggle `json:"struggle" api:"required"`
	// Summary of the interaction.
	Summary string `json:"summary" api:"required"`
	// Main topic discussed.
	Topic string `json:"topic" api:"required"`
	// Keywords extracted (insights mode only).
	Keywords []string `json:"keywords"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		AverageUserSentiment     respjson.Field
		ChangeInUserSentiment    respjson.Field
		CommercialIntent         respjson.Field
		ConversationQualityIndex respjson.Field
		Frustration              respjson.Field
		MessageCount             respjson.Field
		MostCommonUserEmotion    respjson.Field
		Rating                   respjson.Field
		Struggle                 respjson.Field
		Summary                  respjson.Field
		Topic                    respjson.Field
		Keywords                 respjson.Field
		ExtraFields              map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (GetInteractionAnalyticsResponse) RawJSON

Returns the unmodified JSON received from the API

func (*GetInteractionAnalyticsResponse) UnmarshalJSON

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

type GetInteractionAnalyticsResponseAverageUserSentiment

type GetInteractionAnalyticsResponseAverageUserSentiment struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Average sentiment across user messages.

func (GetInteractionAnalyticsResponseAverageUserSentiment) RawJSON

Returns the unmodified JSON received from the API

func (*GetInteractionAnalyticsResponseAverageUserSentiment) UnmarshalJSON

type GetInteractionAnalyticsResponseChangeInUserSentiment

type GetInteractionAnalyticsResponseChangeInUserSentiment struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

How sentiment changed during the interaction.

func (GetInteractionAnalyticsResponseChangeInUserSentiment) RawJSON

Returns the unmodified JSON received from the API

func (*GetInteractionAnalyticsResponseChangeInUserSentiment) UnmarshalJSON

type GetInteractionAnalyticsResponseCommercialIntent

type GetInteractionAnalyticsResponseCommercialIntent struct {
	PrimarySignal string  `json:"primarySignal" api:"required"`
	Score         float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		PrimarySignal respjson.Field
		Score         respjson.Field
		ExtraFields   map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Commercial intent detected.

func (GetInteractionAnalyticsResponseCommercialIntent) RawJSON

Returns the unmodified JSON received from the API

func (*GetInteractionAnalyticsResponseCommercialIntent) UnmarshalJSON

type GetInteractionAnalyticsResponseFrustration

type GetInteractionAnalyticsResponseFrustration struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Frustration level detected.

func (GetInteractionAnalyticsResponseFrustration) RawJSON

Returns the unmodified JSON received from the API

func (*GetInteractionAnalyticsResponseFrustration) UnmarshalJSON

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

type GetInteractionAnalyticsResponseStruggle

type GetInteractionAnalyticsResponseStruggle struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Struggle level detected.

func (GetInteractionAnalyticsResponseStruggle) RawJSON

Returns the unmodified JSON received from the API

func (*GetInteractionAnalyticsResponseStruggle) UnmarshalJSON

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

type GetOrganizationAnalyticsResponse

type GetOrganizationAnalyticsResponse struct {
	// Distribution of sentiment changes.
	AverageChangeInUserSentiment GetOrganizationAnalyticsResponseAverageChangeInUserSentiment `json:"averageChangeInUserSentiment" api:"required"`
	// Average commercial intent.
	AverageCommercialIntent GetOrganizationAnalyticsResponseAverageCommercialIntent `json:"averageCommercialIntent" api:"required"`
	// Average conversation quality index.
	AverageConversationQualityIndex float64 `json:"averageConversationQualityIndex" api:"required"`
	// Average conversation rating.
	AverageConversationRating float64 `json:"averageConversationRating" api:"required"`
	// Average frustration level.
	AverageFrustration GetOrganizationAnalyticsResponseAverageFrustration `json:"averageFrustration" api:"required"`
	// Average struggle level.
	AverageStruggle GetOrganizationAnalyticsResponseAverageStruggle `json:"averageStruggle" api:"required"`
	// Average sentiment across all conversations.
	AverageUserSentiment GetOrganizationAnalyticsResponseAverageUserSentiment `json:"averageUserSentiment" api:"required"`
	// Summary of the organization analytics.
	Summary GetOrganizationAnalyticsResponseSummary `json:"summary" api:"required"`
	// Total number of conversations analyzed.
	TotalConversations float64 `json:"totalConversations" api:"required"`
	// Keywords extracted (insights mode only).
	Keywords []GetOrganizationAnalyticsResponseKeyword `json:"keywords"`
	// Topics discussed (insights mode only).
	Topics []GetOrganizationAnalyticsResponseTopic `json:"topics"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		AverageChangeInUserSentiment    respjson.Field
		AverageCommercialIntent         respjson.Field
		AverageConversationQualityIndex respjson.Field
		AverageConversationRating       respjson.Field
		AverageFrustration              respjson.Field
		AverageStruggle                 respjson.Field
		AverageUserSentiment            respjson.Field
		Summary                         respjson.Field
		TotalConversations              respjson.Field
		Keywords                        respjson.Field
		Topics                          respjson.Field
		ExtraFields                     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (GetOrganizationAnalyticsResponse) RawJSON

Returns the unmodified JSON received from the API

func (*GetOrganizationAnalyticsResponse) UnmarshalJSON

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

type GetOrganizationAnalyticsResponseAverageChangeInUserSentiment

type GetOrganizationAnalyticsResponseAverageChangeInUserSentiment struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Distribution of sentiment changes.

func (GetOrganizationAnalyticsResponseAverageChangeInUserSentiment) RawJSON

Returns the unmodified JSON received from the API

func (*GetOrganizationAnalyticsResponseAverageChangeInUserSentiment) UnmarshalJSON

type GetOrganizationAnalyticsResponseAverageCommercialIntent

type GetOrganizationAnalyticsResponseAverageCommercialIntent struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Average commercial intent.

func (GetOrganizationAnalyticsResponseAverageCommercialIntent) RawJSON

Returns the unmodified JSON received from the API

func (*GetOrganizationAnalyticsResponseAverageCommercialIntent) UnmarshalJSON

type GetOrganizationAnalyticsResponseAverageFrustration

type GetOrganizationAnalyticsResponseAverageFrustration struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Average frustration level.

func (GetOrganizationAnalyticsResponseAverageFrustration) RawJSON

Returns the unmodified JSON received from the API

func (*GetOrganizationAnalyticsResponseAverageFrustration) UnmarshalJSON

type GetOrganizationAnalyticsResponseAverageStruggle

type GetOrganizationAnalyticsResponseAverageStruggle struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Average struggle level.

func (GetOrganizationAnalyticsResponseAverageStruggle) RawJSON

Returns the unmodified JSON received from the API

func (*GetOrganizationAnalyticsResponseAverageStruggle) UnmarshalJSON

type GetOrganizationAnalyticsResponseAverageUserSentiment

type GetOrganizationAnalyticsResponseAverageUserSentiment struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Average sentiment across all conversations.

func (GetOrganizationAnalyticsResponseAverageUserSentiment) RawJSON

Returns the unmodified JSON received from the API

func (*GetOrganizationAnalyticsResponseAverageUserSentiment) UnmarshalJSON

type GetOrganizationAnalyticsResponseKeyword

type GetOrganizationAnalyticsResponseKeyword struct {
	Count float64 `json:"count" api:"required"`
	Name  string  `json:"name" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Count       respjson.Field
		Name        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (GetOrganizationAnalyticsResponseKeyword) RawJSON

Returns the unmodified JSON received from the API

func (*GetOrganizationAnalyticsResponseKeyword) UnmarshalJSON

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

type GetOrganizationAnalyticsResponseSummary

type GetOrganizationAnalyticsResponseSummary struct {
	Analysis string `json:"analysis" api:"required"`
	Reason   string `json:"reason" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Analysis    respjson.Field
		Reason      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Summary of the organization analytics.

func (GetOrganizationAnalyticsResponseSummary) RawJSON

Returns the unmodified JSON received from the API

func (*GetOrganizationAnalyticsResponseSummary) UnmarshalJSON

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

type GetOrganizationAnalyticsResponseTopic

type GetOrganizationAnalyticsResponseTopic struct {
	Count float64 `json:"count" api:"required"`
	Name  string  `json:"name" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Count       respjson.Field
		Name        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (GetOrganizationAnalyticsResponseTopic) RawJSON

Returns the unmodified JSON received from the API

func (*GetOrganizationAnalyticsResponseTopic) UnmarshalJSON

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

type GetPromptResponse

type GetPromptResponse struct {
	// The prompt with variables interpolated from query parameters.
	ComposedPrompt string `json:"composedPrompt" api:"required"`
	// The full prompt object with components.
	Prompt Prompt `json:"prompt" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ComposedPrompt respjson.Field
		Prompt         respjson.Field
		ExtraFields    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (GetPromptResponse) RawJSON

func (r GetPromptResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*GetPromptResponse) UnmarshalJSON

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

type GetUserAnalyticsResponse

type GetUserAnalyticsResponse struct {
	// Distribution of sentiment changes.
	AverageChangeInUserSentiment GetUserAnalyticsResponseAverageChangeInUserSentiment `json:"averageChangeInUserSentiment" api:"required"`
	// Average commercial intent.
	AverageCommercialIntent GetUserAnalyticsResponseAverageCommercialIntent `json:"averageCommercialIntent" api:"required"`
	// Average conversation quality index.
	AverageConversationQualityIndex float64 `json:"averageConversationQualityIndex" api:"required"`
	// Average conversation rating.
	AverageConversationRating float64 `json:"averageConversationRating" api:"required"`
	// Average frustration level.
	AverageFrustration GetUserAnalyticsResponseAverageFrustration `json:"averageFrustration" api:"required"`
	// Average struggle level.
	AverageStruggle GetUserAnalyticsResponseAverageStruggle `json:"averageStruggle" api:"required"`
	// Average sentiment across all conversations.
	AverageUserSentiment GetUserAnalyticsResponseAverageUserSentiment `json:"averageUserSentiment" api:"required"`
	// Structured participant profile summary.
	Summary GetUserAnalyticsResponseSummary `json:"summary" api:"required"`
	// Total number of conversations analyzed.
	TotalConversations float64 `json:"totalConversations" api:"required"`
	// Keywords extracted (insights mode only).
	Keywords []GetUserAnalyticsResponseKeyword `json:"keywords"`
	// Topics discussed (insights mode only).
	Topics []GetUserAnalyticsResponseTopic `json:"topics"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		AverageChangeInUserSentiment    respjson.Field
		AverageCommercialIntent         respjson.Field
		AverageConversationQualityIndex respjson.Field
		AverageConversationRating       respjson.Field
		AverageFrustration              respjson.Field
		AverageStruggle                 respjson.Field
		AverageUserSentiment            respjson.Field
		Summary                         respjson.Field
		TotalConversations              respjson.Field
		Keywords                        respjson.Field
		Topics                          respjson.Field
		ExtraFields                     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (GetUserAnalyticsResponse) RawJSON

func (r GetUserAnalyticsResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponse) UnmarshalJSON

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

type GetUserAnalyticsResponseAverageChangeInUserSentiment

type GetUserAnalyticsResponseAverageChangeInUserSentiment struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Distribution of sentiment changes.

func (GetUserAnalyticsResponseAverageChangeInUserSentiment) RawJSON

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseAverageChangeInUserSentiment) UnmarshalJSON

type GetUserAnalyticsResponseAverageCommercialIntent

type GetUserAnalyticsResponseAverageCommercialIntent struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Average commercial intent.

func (GetUserAnalyticsResponseAverageCommercialIntent) RawJSON

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseAverageCommercialIntent) UnmarshalJSON

type GetUserAnalyticsResponseAverageFrustration

type GetUserAnalyticsResponseAverageFrustration struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Average frustration level.

func (GetUserAnalyticsResponseAverageFrustration) RawJSON

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseAverageFrustration) UnmarshalJSON

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

type GetUserAnalyticsResponseAverageStruggle

type GetUserAnalyticsResponseAverageStruggle struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Average struggle level.

func (GetUserAnalyticsResponseAverageStruggle) RawJSON

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseAverageStruggle) UnmarshalJSON

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

type GetUserAnalyticsResponseAverageUserSentiment

type GetUserAnalyticsResponseAverageUserSentiment struct {
	Label string  `json:"label" api:"required"`
	Score float64 `json:"score" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Label       respjson.Field
		Score       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Average sentiment across all conversations.

func (GetUserAnalyticsResponseAverageUserSentiment) RawJSON

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseAverageUserSentiment) UnmarshalJSON

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

type GetUserAnalyticsResponseKeyword

type GetUserAnalyticsResponseKeyword struct {
	Count float64 `json:"count" api:"required"`
	Name  string  `json:"name" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Count       respjson.Field
		Name        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (GetUserAnalyticsResponseKeyword) RawJSON

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseKeyword) UnmarshalJSON

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

type GetUserAnalyticsResponseSummary

type GetUserAnalyticsResponseSummary struct {
	// Behavioral patterns observed across conversations.
	BehavioralPatterns []GetUserAnalyticsResponseSummaryBehavioralPattern `json:"behavioralPatterns" api:"required"`
	// Engagement profile.
	Engagement GetUserAnalyticsResponseSummaryEngagement `json:"engagement" api:"required"`
	// Transparency about what data drove the analysis.
	Methodology string `json:"methodology" api:"required"`
	// Product-specific observations (when business context is available).
	ProductAlignment GetUserAnalyticsResponseSummaryProductAlignment `json:"productAlignment" api:"required"`
	// Executive summary of the participant.
	ProfileSummary string `json:"profileSummary" api:"required"`
	// Key signals the product owner should know about.
	Signals []GetUserAnalyticsResponseSummarySignal `json:"signals" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		BehavioralPatterns respjson.Field
		Engagement         respjson.Field
		Methodology        respjson.Field
		ProductAlignment   respjson.Field
		ProfileSummary     respjson.Field
		Signals            respjson.Field
		ExtraFields        map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Structured participant profile summary.

func (GetUserAnalyticsResponseSummary) RawJSON

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseSummary) UnmarshalJSON

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

type GetUserAnalyticsResponseSummaryBehavioralPattern added in v0.1.0

type GetUserAnalyticsResponseSummaryBehavioralPattern struct {
	// Specific examples from conversations.
	Evidence string `json:"evidence" api:"required"`
	// How often this pattern appears.
	//
	// Any of "recurring", "occasional", "rare".
	Frequency string `json:"frequency" api:"required"`
	// What the participant consistently does.
	Pattern string `json:"pattern" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Evidence    respjson.Field
		Frequency   respjson.Field
		Pattern     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (GetUserAnalyticsResponseSummaryBehavioralPattern) RawJSON added in v0.1.0

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseSummaryBehavioralPattern) UnmarshalJSON added in v0.1.0

type GetUserAnalyticsResponseSummaryEngagement added in v0.1.0

type GetUserAnalyticsResponseSummaryEngagement struct {
	// Explanation of the engagement assessment.
	Description string `json:"description" api:"required"`
	// Engagement level classification.
	//
	// Any of "power_user", "regular", "casual", "at_risk", "churning".
	Level string `json:"level" api:"required"`
	// Engagement trend direction.
	//
	// Any of "growing", "stable", "declining".
	Trajectory string `json:"trajectory" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Description respjson.Field
		Level       respjson.Field
		Trajectory  respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Engagement profile.

func (GetUserAnalyticsResponseSummaryEngagement) RawJSON added in v0.1.0

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseSummaryEngagement) UnmarshalJSON added in v0.1.0

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

type GetUserAnalyticsResponseSummaryProductAlignment added in v0.1.0

type GetUserAnalyticsResponseSummaryProductAlignment struct {
	// Where the product isn't serving them.
	Gaps []string `json:"gaps" api:"required"`
	// What's working well for this participant.
	Strengths []string `json:"strengths" api:"required"`
	// How the participant relates to product goals.
	Summary string `json:"summary" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Gaps        respjson.Field
		Strengths   respjson.Field
		Summary     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Product-specific observations (when business context is available).

func (GetUserAnalyticsResponseSummaryProductAlignment) RawJSON added in v0.1.0

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseSummaryProductAlignment) UnmarshalJSON added in v0.1.0

type GetUserAnalyticsResponseSummarySignal added in v0.1.0

type GetUserAnalyticsResponseSummarySignal struct {
	// Evidence-based description.
	Description string `json:"description" api:"required"`
	// Signal priority.
	//
	// Any of "high", "medium", "low".
	Priority string `json:"priority" api:"required"`
	// Short headline.
	Title string `json:"title" api:"required"`
	// Signal category.
	//
	// Any of "opportunity", "risk", "insight".
	Type string `json:"type" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Description respjson.Field
		Priority    respjson.Field
		Title       respjson.Field
		Type        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (GetUserAnalyticsResponseSummarySignal) RawJSON added in v0.1.0

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseSummarySignal) UnmarshalJSON added in v0.1.0

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

type GetUserAnalyticsResponseTopic

type GetUserAnalyticsResponseTopic struct {
	Count float64 `json:"count" api:"required"`
	Name  string  `json:"name" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Count       respjson.Field
		Name        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (GetUserAnalyticsResponseTopic) RawJSON

Returns the unmodified JSON received from the API

func (*GetUserAnalyticsResponseTopic) UnmarshalJSON

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

type InteractionGetInteractionAnalyticsParams

type InteractionGetInteractionAnalyticsParams struct {
	// Analysis mode: "simple" returns only numeric aggregates (no rate limiting),
	// "insights" includes topics, keywords, and recommendations (rate limited per
	// tenant plan).
	//
	// Any of "simple", "insights".
	Mode InteractionGetInteractionAnalyticsParamsMode `query:"mode,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (InteractionGetInteractionAnalyticsParams) URLQuery

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

type InteractionGetInteractionAnalyticsParamsMode

type InteractionGetInteractionAnalyticsParamsMode string

Analysis mode: "simple" returns only numeric aggregates (no rate limiting), "insights" includes topics, keywords, and recommendations (rate limited per tenant plan).

const (
	InteractionGetInteractionAnalyticsParamsModeSimple   InteractionGetInteractionAnalyticsParamsMode = "simple"
	InteractionGetInteractionAnalyticsParamsModeInsights InteractionGetInteractionAnalyticsParamsMode = "insights"
)

type InteractionListParams

type InteractionListParams struct {
	// Maximum number of results to return.
	Limit param.Opt[float64] `query:"limit,omitzero" json:"-"`
	// Offset for pagination.
	Offset param.Opt[float64] `query:"offset,omitzero" json:"-"`
	// Page number
	Page param.Opt[float64] `query:"page,omitzero" json:"-"`
	// Filter interactions by product ID.
	ProductID param.Opt[string] `query:"productId,omitzero" format:"uuid" json:"-"`
	// Filter interactions by version ID.
	VersionID param.Opt[string] `query:"versionId,omitzero" format:"uuid" json:"-"`
	// contains filtered or unexported fields
}

func (InteractionListParams) URLQuery

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

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

type InteractionService

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

Capture interactions between users and AI

InteractionService contains methods and other services that help with interacting with the Greenflash 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 NewInteractionService method instead.

func NewInteractionService

func NewInteractionService(opts ...option.RequestOption) (r InteractionService)

NewInteractionService 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 (*InteractionService) GetInteractionAnalytics

func (r *InteractionService) GetInteractionAnalytics(ctx context.Context, interactionID string, query InteractionGetInteractionAnalyticsParams, opts ...option.RequestOption) (res *GetInteractionAnalyticsResponse, err error)

Understand what happened in a specific conversation with AI-powered analysis. See sentiment shifts, detect frustration, identify commercial intent, and get actionable insights.

**⚠️ Requires Growth+ plan or higher**

**Two modes available:**

  • **simple mode**: Get just the numbers—sentiment scores, frustration levels, and key metrics. Perfect for dashboards and quick checks. No rate limiting.
  • **insights mode** (default): Dive deeper with detailed keywords, insights, and AI-generated suggestions for improvement. Rate limited based on your plan's `maxAnalysesPerHour`.

Returns 404 if the conversation doesn't exist or hasn't been analyzed yet.

func (*InteractionService) List

Browse through all conversations in your workspace to understand how users are interacting with your AI. Filter by product or version to focus on specific areas of your application.

type ListInteractionsResponse

type ListInteractionsResponse []ListInteractionsResponseItem

type ListInteractionsResponseItem

type ListInteractionsResponseItem struct {
	// The interaction ID.
	ID string `json:"id" api:"required" format:"uuid"`
	// When the interaction was created.
	CreatedAt time.Time `json:"createdAt" api:"required" format:"date-time"`
	// Your external identifier for the interaction.
	ExternalID string `json:"externalId" api:"required"`
	// Your external identifier for the participant.
	ExternalParticipantID string `json:"externalParticipantId" api:"required"`
	// User feedback text.
	Feedback string `json:"feedback" api:"required"`
	// The AI model used.
	Model string `json:"model" api:"required"`
	// Your external identifier for the organization.
	OrganizationExternalID string `json:"organizationExternalId" api:"required"`
	// The organization ID.
	OrganizationID string `json:"organizationId" api:"required" format:"uuid"`
	// The user who participated in this interaction.
	ParticipantID string `json:"participantId" api:"required" format:"uuid"`
	// The product ID.
	ProductID string `json:"productId" api:"required" format:"uuid"`
	// User rating for this interaction.
	Rating float64 `json:"rating" api:"required"`
	// Maximum rating value.
	RatingMax float64 `json:"ratingMax" api:"required"`
	// Minimum rating value.
	RatingMin float64 `json:"ratingMin" api:"required"`
	// When the interaction was last updated.
	UpdatedAt time.Time `json:"updatedAt" api:"required" format:"date-time"`
	// The version ID.
	VersionID string `json:"versionId" api:"required" format:"uuid"`
	// Custom interaction properties.
	Properties map[string]any `json:"properties"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID                     respjson.Field
		CreatedAt              respjson.Field
		ExternalID             respjson.Field
		ExternalParticipantID  respjson.Field
		Feedback               respjson.Field
		Model                  respjson.Field
		OrganizationExternalID respjson.Field
		OrganizationID         respjson.Field
		ParticipantID          respjson.Field
		ProductID              respjson.Field
		Rating                 respjson.Field
		RatingMax              respjson.Field
		RatingMin              respjson.Field
		UpdatedAt              respjson.Field
		VersionID              respjson.Field
		Properties             respjson.Field
		ExtraFields            map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ListInteractionsResponseItem) RawJSON

Returns the unmodified JSON received from the API

func (*ListInteractionsResponseItem) UnmarshalJSON

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

type ListOrganizationsResponse

type ListOrganizationsResponse []TenantOrganization

type ListPromptsResponse

type ListPromptsResponse []SlimPrompt

type ListUsersResponse

type ListUsersResponse []Participant

type LogRatingParams

type LogRatingParams struct {
	// The Greenflash product ID to rate.
	ProductID string `json:"productId" api:"required" format:"uuid"`
	// The rating value. Must be between ratingMin and ratingMax (inclusive).
	Rating float64 `json:"rating" api:"required"`
	// The maximum possible rating value (e.g., 5 for a 1-5 scale).
	RatingMax float64 `json:"ratingMax" api:"required"`
	// The minimum possible rating value (e.g., 1 for a 1-5 scale).
	RatingMin float64 `json:"ratingMin" api:"required"`
	// The Greenflash conversation ID to rate. Either conversationId,
	// externalConversationId, messageId, or externalMessageId must be provided.
	ConversationID param.Opt[string] `json:"conversationId,omitzero" format:"uuid"`
	// Your external conversation identifier to rate. Either conversationId,
	// externalConversationId, messageId, or externalMessageId must be provided.
	ExternalConversationID param.Opt[string] `json:"externalConversationId,omitzero"`
	// Your external message identifier to rate. Either conversationId,
	// externalConversationId, messageId, or externalMessageId must be provided.
	ExternalMessageID param.Opt[string] `json:"externalMessageId,omitzero"`
	// Optional text feedback accompanying the rating.
	Feedback param.Opt[string] `json:"feedback,omitzero"`
	// The Greenflash message ID to rate. Either conversationId,
	// externalConversationId, messageId, or externalMessageId must be provided.
	MessageID param.Opt[string] `json:"messageId,omitzero"`
	// When the rating was given. Defaults to current time if not provided.
	RatedAt param.Opt[time.Time] `json:"ratedAt,omitzero" format:"date"`
	// contains filtered or unexported fields
}

Request payload for logging ratings.

The properties ProductID, Rating, RatingMax, RatingMin are required.

func (LogRatingParams) MarshalJSON

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

func (*LogRatingParams) UnmarshalJSON

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

type LogRatingResponse

type LogRatingResponse struct {
	// Whether the API call was successful.
	Success bool `json:"success" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Success     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Success response for rating logging.

func (LogRatingResponse) RawJSON

func (r LogRatingResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*LogRatingResponse) UnmarshalJSON

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

type MessageItemMessageType

type MessageItemMessageType string

Detailed message type for agentic workflows. Cannot be used with role. Available types: user_message, assistant_message, system_message, thought, tool_call, observation, final_response, retrieval, memory_read, memory_write, chain_start, chain_end, embedding, tool_error, callback, llm, task, workflow

const (
	MessageItemMessageTypeUserMessage      MessageItemMessageType = "user_message"
	MessageItemMessageTypeAssistantMessage MessageItemMessageType = "assistant_message"
	MessageItemMessageTypeSystemMessage    MessageItemMessageType = "system_message"
	MessageItemMessageTypeThought          MessageItemMessageType = "thought"
	MessageItemMessageTypeToolCall         MessageItemMessageType = "tool_call"
	MessageItemMessageTypeObservation      MessageItemMessageType = "observation"
	MessageItemMessageTypeFinalResponse    MessageItemMessageType = "final_response"
	MessageItemMessageTypeRetrieval        MessageItemMessageType = "retrieval"
	MessageItemMessageTypeMemoryRead       MessageItemMessageType = "memory_read"
	MessageItemMessageTypeMemoryWrite      MessageItemMessageType = "memory_write"
	MessageItemMessageTypeChainStart       MessageItemMessageType = "chain_start"
	MessageItemMessageTypeChainEnd         MessageItemMessageType = "chain_end"
	MessageItemMessageTypeEmbedding        MessageItemMessageType = "embedding"
	MessageItemMessageTypeToolError        MessageItemMessageType = "tool_error"
	MessageItemMessageTypeCallback         MessageItemMessageType = "callback"
	MessageItemMessageTypeLlm              MessageItemMessageType = "llm"
	MessageItemMessageTypeTask             MessageItemMessageType = "task"
	MessageItemMessageTypeWorkflow         MessageItemMessageType = "workflow"
)

type MessageItemParam

type MessageItemParam struct {
	// Additional context (e.g., RAG data) used to generate the message.
	Context param.Opt[string] `json:"context,omitzero"`
	// The message content. Required for language-based analyses.
	Content param.Opt[string] `json:"content,omitzero"`
	// When this message was created. If not provided, messages get sequential
	// timestamps. Use for importing historical data.
	CreatedAt param.Opt[time.Time] `json:"createdAt,omitzero" format:"date"`
	// Your external identifier for this message. Used to reference the message in
	// other API calls.
	ExternalMessageID param.Opt[string] `json:"externalMessageId,omitzero"`
	// The AI model used for this specific message. Use for multi-agent scenarios where
	// different messages use different models. Overrides the conversation-level model
	// for this message.
	Model param.Opt[string] `json:"model,omitzero"`
	// The external ID of the parent message for threading. Cannot be used with
	// parentMessageId.
	ParentExternalMessageID param.Opt[string] `json:"parentExternalMessageId,omitzero"`
	// The internal ID of the parent message for threading. Cannot be used with
	// parentExternalMessageId.
	ParentMessageID param.Opt[string] `json:"parentMessageId,omitzero" format:"uuid"`
	// Name of the tool being called. Required for tool_call messages.
	ToolName param.Opt[string] `json:"toolName,omitzero"`
	// Structured input data for tool calls, retrievals, or other operations.
	Input map[string]any `json:"input,omitzero"`
	// Detailed message type for agentic workflows. Cannot be used with role. Available
	// types: user_message, assistant_message, system_message, thought, tool_call,
	// observation, final_response, retrieval, memory_read, memory_write, chain_start,
	// chain_end, embedding, tool_error, callback, llm, task, workflow
	//
	// Any of "user_message", "assistant_message", "system_message", "thought",
	// "tool_call", "observation", "final_response", "retrieval", "memory_read",
	// "memory_write", "chain_start", "chain_end", "embedding", "tool_error",
	// "callback", "llm", "task", "workflow".
	MessageType MessageItemMessageType `json:"messageType,omitzero"`
	// Structured output data from tool calls, retrievals, or other operations.
	Output map[string]any `json:"output,omitzero"`
	// Custom message properties.
	Properties map[string]any `json:"properties,omitzero"`
	// Simple message role for basic chat: user, assistant, or system. Cannot be used
	// with messageType.
	//
	// Any of "user", "assistant", "system".
	Role MessageItemRole `json:"role,omitzero"`
	// contains filtered or unexported fields
}

func (MessageItemParam) MarshalJSON

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

func (*MessageItemParam) UnmarshalJSON

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

type MessageItemRole

type MessageItemRole string

Simple message role for basic chat: user, assistant, or system. Cannot be used with messageType.

const (
	MessageItemRoleUser      MessageItemRole = "user"
	MessageItemRoleAssistant MessageItemRole = "assistant"
	MessageItemRoleSystem    MessageItemRole = "system"
)

type MessageNewParams

type MessageNewParams struct {
	// Request payload for logging conversations and messages.
	CreateMessageParams CreateMessageParams
	// contains filtered or unexported fields
}

func (MessageNewParams) MarshalJSON

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

func (*MessageNewParams) UnmarshalJSON

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

type MessageService

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

Capture interactions between users and AI

MessageService contains methods and other services that help with interacting with the Greenflash 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 NewMessageService method instead.

func NewMessageService

func NewMessageService(opts ...option.RequestOption) (r MessageService)

NewMessageService 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 (*MessageService) New

Send us your AI conversations so we can analyze them for you. Works with everything from simple chatbots to complex agentic systems.

**Getting Started (Simple Chat):** Just provide the `role` ("user", "assistant", or "system") and `content` for each message, along with an `externalConversationId` and your `productId`. That's it!

**Advanced Usage (Agentic Workflows):** Capture the full execution trace of your AI agents using `messageType` for tool calls, thoughts, observations, and more. Include structured data via `input`/`output` fields to track what your agents are doing.

**Key Features:**

  • **Automatic Ordering:** Messages are stored with sequential timestamps, or provide your own `createdAt` timestamps for historical data.
  • **Threading:** Create nested conversations by referencing parent messages using `parentMessageId` or `parentExternalMessageId`.
  • **Organization Tracking:** Associate users with organizations via `externalOrganizationId`. We'll create the organization automatically if it doesn't exist.
  • **Automatic De-duplication:** Messages with an `externalMessageId` that already exists in the conversation are automatically skipped. This allows you to safely resend a batch of messages with new messages appended — previously ingested messages will be deduplicated and only new messages will be inserted. Each message in the response includes a `status` field ("created" or "deduplicated") so you know what happened.

Perfect for understanding how your AI is performing in production and identifying areas for improvement.

type OrganizationGetOrganizationAnalyticsParams

type OrganizationGetOrganizationAnalyticsParams struct {
	// Filter analytics by product ID.
	ProductID param.Opt[string] `query:"productId,omitzero" format:"uuid" json:"-"`
	// Filter analytics by version ID.
	VersionID param.Opt[string] `query:"versionId,omitzero" format:"uuid" json:"-"`
	// Analysis mode: "simple" returns only numeric aggregates (no rate limiting),
	// "insights" includes topics, keywords, and recommendations (rate limited per
	// tenant plan).
	//
	// Any of "simple", "insights".
	Mode OrganizationGetOrganizationAnalyticsParamsMode `query:"mode,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (OrganizationGetOrganizationAnalyticsParams) URLQuery

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

type OrganizationGetOrganizationAnalyticsParamsMode

type OrganizationGetOrganizationAnalyticsParamsMode string

Analysis mode: "simple" returns only numeric aggregates (no rate limiting), "insights" includes topics, keywords, and recommendations (rate limited per tenant plan).

const (
	OrganizationGetOrganizationAnalyticsParamsModeSimple   OrganizationGetOrganizationAnalyticsParamsMode = "simple"
	OrganizationGetOrganizationAnalyticsParamsModeInsights OrganizationGetOrganizationAnalyticsParamsMode = "insights"
)

type OrganizationListParams

type OrganizationListParams struct {
	// Maximum number of results to return.
	Limit param.Opt[float64] `query:"limit,omitzero" json:"-"`
	// Offset for pagination.
	Offset param.Opt[float64] `query:"offset,omitzero" json:"-"`
	// Page number (used to derive offset = (page-1)\*limit).
	Page param.Opt[float64] `query:"page,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (OrganizationListParams) URLQuery

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

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

type OrganizationNewParams

type OrganizationNewParams struct {
	// Request payload for creating a new organization.
	CreateOrganizationParams CreateOrganizationParams
	// contains filtered or unexported fields
}

func (OrganizationNewParams) MarshalJSON

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

func (*OrganizationNewParams) UnmarshalJSON

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

type OrganizationService

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

Manage users

OrganizationService contains methods and other services that help with interacting with the Greenflash 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 NewOrganizationService method instead.

func NewOrganizationService

func NewOrganizationService(opts ...option.RequestOption) (r OrganizationService)

NewOrganizationService 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 (*OrganizationService) GetOrganizationAnalytics

func (r *OrganizationService) GetOrganizationAnalytics(ctx context.Context, organizationID string, query OrganizationGetOrganizationAnalyticsParams, opts ...option.RequestOption) (res *GetOrganizationAnalyticsResponse, err error)

See how an entire organization (company, team, etc.) engages with your AI across all their users and conversations. Spot trends, measure satisfaction, and identify opportunities to improve the experience for your biggest customers.

**⚠️ Requires Growth+ plan or higher**

**Two modes available:**

  • **simple mode**: Get organization-wide metrics like average sentiment, frustration levels, commercial intent, and quality scores. Perfect for executive dashboards and health monitoring. No rate limiting.
  • **insights mode** (default): Dive into detailed patterns, common topics, and AI-generated recommendations for improving this organization's experience. Rate limited based on your plan's `maxAnalysesPerHour`.

If analytics don't exist yet, they'll be generated in real-time from the organization's conversations (this may take a few seconds). Returns 404 if the organization doesn't exist or has no conversations.

func (*OrganizationService) List

Browse through all the organizations (companies, teams, etc.) in your workspace. Search for specific organizations or paginate through the full list. Perfect for building admin dashboards or organization management interfaces.

The response includes a `Link` header with URLs for next/previous pages, making pagination straightforward.

func (*OrganizationService) New

Group your users by company, team, or any organizational structure that makes sense for your business.

Provide an `externalOrganizationId` to identify the organization—your ID from your own system. Don't worry about whether it already exists; we'll create it if it's new or update it if it already exists. This makes syncing organization data effortless.

Reference this organization when creating users (via `/users`) or logging messages (via `/messages`) using the same `externalOrganizationId`. Perfect for B2B products where you need to track which company each user belongs to.

func (*OrganizationService) Update

Update specific fields of an existing organization without changing everything.

The `organizationId` in the URL path should be your `externalOrganizationId`. Only the fields you include in your request will be updated—everything else stays the same. Perfect for targeted updates like renaming a company or updating properties.

Prefer a simpler approach? Use `POST /organizations` instead—it automatically creates or updates the organization, so you don't need to know if it exists yet.

type OrganizationUpdateParams

type OrganizationUpdateParams struct {
	// Request payload for updating an organization.
	UpdateOrganizationParams UpdateOrganizationParams
	// contains filtered or unexported fields
}

func (OrganizationUpdateParams) MarshalJSON

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

func (*OrganizationUpdateParams) UnmarshalJSON

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

type Participant

type Participant struct {
	// The Greenflash participant ID.
	ID string `json:"id" api:"required"`
	// Whether the participant's personal information is anonymized.
	Anonymized bool `json:"anonymized" api:"required"`
	// Your external user ID (matches the externalUserId from the request).
	ExternalID string `json:"externalId" api:"required"`
	// Your external identifier for the user's organization.
	ExternalOrganizationID string `json:"externalOrganizationId" api:"required"`
	// The internal organization ID that the user belongs to.
	OrganizationID string `json:"organizationId" api:"required" format:"uuid"`
	// Additional data about the participant.
	Properties map[string]any `json:"properties" api:"required"`
	// When the participant was first created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// The participant's email address.
	Email string `json:"email"`
	// The participant's full name.
	Name string `json:"name"`
	// The participant's phone number.
	Phone string `json:"phone"`
	// When the participant was last updated.
	UpdatedAt time.Time `json:"updatedAt" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID                     respjson.Field
		Anonymized             respjson.Field
		ExternalID             respjson.Field
		ExternalOrganizationID respjson.Field
		OrganizationID         respjson.Field
		Properties             respjson.Field
		CreatedAt              respjson.Field
		Email                  respjson.Field
		Name                   respjson.Field
		Phone                  respjson.Field
		UpdatedAt              respjson.Field
		ExtraFields            map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

The user profile.

func (Participant) RawJSON

func (r Participant) RawJSON() string

Returns the unmodified JSON received from the API

func (*Participant) UnmarshalJSON

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

type Prompt

type Prompt struct {
	// The Greenflash prompt ID.
	ID string `json:"id" api:"required" format:"uuid"`
	// ISO 8601 timestamp when archived, or null if active.
	ArchivedAt string `json:"archivedAt" api:"required"`
	// Array of prompt components that make up this prompt.
	Components []PromptComponent `json:"components" api:"required"`
	// ISO 8601 timestamp when created.
	CreatedAt string `json:"createdAt" api:"required"`
	// Prompt description.
	Description string `json:"description" api:"required"`
	// Prompt name.
	Name string `json:"name" api:"required"`
	// The product ID this prompt is associated with.
	ProductID string `json:"productId" api:"required" format:"uuid"`
	// Prompt source.
	Source string `json:"source" api:"required"`
	// ISO 8601 timestamp when last updated.
	UpdatedAt string `json:"updatedAt" api:"required"`
	// Your external identifier for the prompt.
	ExternalPromptID string `json:"externalPromptId"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID               respjson.Field
		ArchivedAt       respjson.Field
		Components       respjson.Field
		CreatedAt        respjson.Field
		Description      respjson.Field
		Name             respjson.Field
		ProductID        respjson.Field
		Source           respjson.Field
		UpdatedAt        respjson.Field
		ExternalPromptID respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

The full prompt object with components.

func (Prompt) RawJSON

func (r Prompt) RawJSON() string

Returns the unmodified JSON received from the API

func (*Prompt) UnmarshalJSON

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

type PromptComponent

type PromptComponent struct {
	// The Greenflash component ID.
	ID string `json:"id" api:"required" format:"uuid"`
	// The content of the component.
	Content string `json:"content" api:"required"`
	// ISO 8601 timestamp when created.
	CreatedAt string `json:"createdAt" api:"required"`
	// Whether the component content changes dynamically.
	IsDynamic bool `json:"isDynamic" api:"required"`
	// Component name.
	Name string `json:"name" api:"required"`
	// Component source (e.g., customer, participant, greenflash).
	Source string `json:"source" api:"required"`
	// ISO 8601 timestamp when last updated.
	UpdatedAt string `json:"updatedAt" api:"required"`
	// Your external identifier for the component.
	ExternalComponentID string `json:"externalComponentId"`
	// Component type: system, user, tool, guardrail, rag, agent, or a custom type
	// (other).
	//
	// Any of "system", "user", "tool", "guardrail", "rag", "agent", "other".
	Type PromptComponentType `json:"type"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID                  respjson.Field
		Content             respjson.Field
		CreatedAt           respjson.Field
		IsDynamic           respjson.Field
		Name                respjson.Field
		Source              respjson.Field
		UpdatedAt           respjson.Field
		ExternalComponentID respjson.Field
		Type                respjson.Field
		ExtraFields         map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (PromptComponent) RawJSON

func (r PromptComponent) RawJSON() string

Returns the unmodified JSON received from the API

func (*PromptComponent) UnmarshalJSON

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

type PromptComponentType

type PromptComponentType string

Component type: system, user, tool, guardrail, rag, agent, or a custom type (other).

const (
	PromptComponentTypeSystem    PromptComponentType = "system"
	PromptComponentTypeUser      PromptComponentType = "user"
	PromptComponentTypeTool      PromptComponentType = "tool"
	PromptComponentTypeGuardrail PromptComponentType = "guardrail"
	PromptComponentTypeRag       PromptComponentType = "rag"
	PromptComponentTypeAgent     PromptComponentType = "agent"
	PromptComponentTypeOther     PromptComponentType = "other"
)

type PromptListParams

type PromptListParams struct {
	// Filter to only show prompts that are part of active versions. When true, only
	// returns prompts associated with versions where isActive=true.
	ActiveOnly param.Opt[bool] `query:"activeOnly,omitzero" json:"-"`
	// Include archived prompts.
	IncludeArchived param.Opt[bool] `query:"includeArchived,omitzero" json:"-"`
	// Page size limit (cursor-based pagination). Use either limit/cursor OR
	// page/pageSize, not both.
	Limit param.Opt[float64] `query:"limit,omitzero" json:"-"`
	// Page number (page-based pagination). Use either page/pageSize OR limit/cursor,
	// not both.
	Page param.Opt[float64] `query:"page,omitzero" json:"-"`
	// Number of items per page (page-based pagination). Use either page/pageSize OR
	// limit/cursor, not both.
	PageSize param.Opt[float64] `query:"pageSize,omitzero" json:"-"`
	// Filter prompts by product ID.
	ProductID param.Opt[string] `query:"productId,omitzero" format:"uuid" json:"-"`
	// Filter prompts by specific version ID.
	VersionID param.Opt[string] `query:"versionId,omitzero" format:"uuid" json:"-"`
	// contains filtered or unexported fields
}

func (PromptListParams) URLQuery

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

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

type PromptNewParams

type PromptNewParams struct {
	CreatePromptParams CreatePromptParams
	// contains filtered or unexported fields
}

func (PromptNewParams) MarshalJSON

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

func (*PromptNewParams) UnmarshalJSON

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

type PromptService

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

Manage prompts

PromptService contains methods and other services that help with interacting with the Greenflash 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 NewPromptService method instead.

func NewPromptService

func NewPromptService(opts ...option.RequestOption) (r PromptService)

NewPromptService 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 (*PromptService) Delete

func (r *PromptService) Delete(ctx context.Context, id string, opts ...option.RequestOption) (res *DeletePromptResponse, err error)

Archive a prompt you no longer need. Archived prompts are soft-deleted (we set an `archived_at` timestamp) so you can still access them for historical data.

**Safety First:**

  • Can't archive a prompt that's currently active. You must activate a different version first.
  • Historical data is preserved—old conversations continue to reference archived prompts so your message history stays intact.
  • Archived prompts remain accessible for reporting and analysis.

func (*PromptService) Get

func (r *PromptService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *GetPromptResponse, err error)

Retrieve a prompt and optionally personalize it with dynamic variables. Perfect for fetching the prompt you want to use right before sending it to your AI.

**Dynamic Variables:** Use handlebars-style placeholders like `{{userName}}` in your prompt, then pass query parameters to fill them in.

**Example:** Calling `/prompts/abc-123?userName=Alice&productName=Premium` will replace `{{userName}}` with "Alice" and `{{productName}}` with "Premium" in the returned prompt.

func (*PromptService) List

Browse through all your prompts to see what you're using across your AI applications. Returns all prompts by default (both active and inactive versions), or filter by product or version to narrow down the results.

**Filtering & Pagination:**

  • Filter by `productId` to see prompts for a specific product
  • Filter by `versionId` to see a specific version
  • Choose your pagination style: cursor-based (`limit` + `cursor`) or page-based (`page` + `pageSize`)
  • Check the `Link` header for easy pagination navigation

**Note:** This returns lightweight data with just component IDs. Use `GET /prompts/:id` to fetch the full prompt content.

func (*PromptService) New

Create a new prompt that you can use across your AI applications. Build prompts from one or more components, and use handlebars-style variables like `{{userName}}` for personalization.

**Safe by Default:** Creating a prompt creates a new version but doesn't activate it. Your production prompts stay unchanged until you explicitly activate the new version (via the UI or when you reference it in the Messages API). This lets you test and prepare new prompts without risk.

**Versioning:** Every prompt is immutable and versioned with fingerprinting, so you can safely iterate and track changes over time.

func (*PromptService) Update

Update a prompt with new content or properties. Your production prompt stays safe—updates create new versions without affecting what's currently active.

**How it Works:**

  • **Updating components:** Creates a new immutable version with fingerprinting. The new version is created but NOT activated, so you can test before going live.
  • **Updating only properties (name/description):** Updates the prompt in-place without creating a new version.

**Version Safety:** Old versions always point to their original prompts, preserving your message history and allowing you to roll back if needed.

type PromptUpdateParams

type PromptUpdateParams struct {
	UpdatePromptParams UpdatePromptParams
	// contains filtered or unexported fields
}

func (PromptUpdateParams) MarshalJSON

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

func (*PromptUpdateParams) UnmarshalJSON

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

type RatingLogParams

type RatingLogParams struct {
	// Request payload for logging ratings.
	LogRatingParams LogRatingParams
	// contains filtered or unexported fields
}

func (RatingLogParams) MarshalJSON

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

func (*RatingLogParams) UnmarshalJSON

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

type RatingService

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

Capture interactions between users and AI

RatingService contains methods and other services that help with interacting with the Greenflash 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 NewRatingService method instead.

func NewRatingService

func NewRatingService(opts ...option.RequestOption) (r RatingService)

NewRatingService 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 (*RatingService) Log

Record user feedback and ratings for conversations or individual messages.

Use this endpoint to collect feedback about response quality or overall conversation experiences. You can rate either a specific message (using `messageId` or `externalMessageId`) or an entire conversation (using `conversationId` or `externalConversationId`).

type SlimPrompt

type SlimPrompt struct {
	// The Greenflash prompt ID.
	ID string `json:"id" api:"required" format:"uuid"`
	// ISO 8601 timestamp when archived, or null if active.
	ArchivedAt string `json:"archivedAt" api:"required"`
	// Array of prompt component IDs that make up this prompt.
	Components []SlimPromptComponent `json:"components" api:"required"`
	// ISO 8601 timestamp when created.
	CreatedAt string `json:"createdAt" api:"required"`
	// Your external identifier for the prompt.
	ExternalPromptID string `json:"externalPromptId" api:"required"`
	// Prompt name.
	Name string `json:"name" api:"required"`
	// The product ID this prompt is associated with.
	ProductID string `json:"productId" api:"required" format:"uuid"`
	// ISO 8601 timestamp when last updated.
	UpdatedAt string `json:"updatedAt" api:"required"`
	// The version ID this prompt is associated with, or null if the prompt is not part
	// of any version.
	VersionID string `json:"versionId" api:"required" format:"uuid"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID               respjson.Field
		ArchivedAt       respjson.Field
		Components       respjson.Field
		CreatedAt        respjson.Field
		ExternalPromptID respjson.Field
		Name             respjson.Field
		ProductID        respjson.Field
		UpdatedAt        respjson.Field
		VersionID        respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SlimPrompt) RawJSON

func (r SlimPrompt) RawJSON() string

Returns the unmodified JSON received from the API

func (*SlimPrompt) UnmarshalJSON

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

type SlimPromptComponent

type SlimPromptComponent struct {
	// The Greenflash component ID.
	ID string `json:"id" api:"required" format:"uuid"`
	// Your external identifier for the component.
	ExternalComponentID string `json:"externalComponentId" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID                  respjson.Field
		ExternalComponentID respjson.Field
		ExtraFields         map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SlimPromptComponent) RawJSON

func (r SlimPromptComponent) RawJSON() string

Returns the unmodified JSON received from the API

func (*SlimPromptComponent) UnmarshalJSON

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

type SystemPromptSystemPromptObjectParam

type SystemPromptSystemPromptObjectParam struct {
	// Simple string content (shorthand for a single system component). Mutually
	// exclusive with components.
	Content param.Opt[string] `json:"content,omitzero"`
	// Your external identifier for the prompt. Can be used to reference an existing
	// prompt created via system prompt APIs.
	ExternalPromptID param.Opt[string] `json:"externalPromptId,omitzero"`
	// Greenflash's internal prompt ID. Can be used to reference an existing prompt
	// created via system prompt APIs.
	PromptID param.Opt[string] `json:"promptId,omitzero" format:"uuid"`
	// Array of component objects. When provided with promptId/externalPromptId, will
	// upsert the prompt. When omitted with promptId/externalPromptId, will reference
	// an existing prompt.
	Components []ComponentInputParam `json:"components,omitzero"`
	// Template variables for {{placeholder}} interpolation in component content.
	Variables map[string]string `json:"variables,omitzero"`
	// contains filtered or unexported fields
}

System prompt as a prompt object. Can reference an existing prompt by ID or define new components inline.

func (SystemPromptSystemPromptObjectParam) MarshalJSON

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

func (*SystemPromptSystemPromptObjectParam) UnmarshalJSON

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

type SystemPromptUnionParam

type SystemPromptUnionParam struct {
	OfString                         param.Opt[string]                    `json:",omitzero,inline"`
	OfSystemPromptSystemPromptObject *SystemPromptSystemPromptObjectParam `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 (SystemPromptUnionParam) MarshalJSON

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

func (*SystemPromptUnionParam) UnmarshalJSON

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

type TenantOrganization

type TenantOrganization struct {
	// The Greenflash organization ID.
	ID string `json:"id" api:"required"`
	// Custom organization properties.
	Properties map[string]any `json:"properties" api:"required"`
	// When the organization was first created.
	CreatedAt time.Time `json:"createdAt" format:"date-time"`
	// Your external organization ID.
	ExternalID string `json:"externalId"`
	// The organization name.
	Name string `json:"name"`
	// When the organization was last updated.
	UpdatedAt time.Time `json:"updatedAt" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID          respjson.Field
		Properties  respjson.Field
		CreatedAt   respjson.Field
		ExternalID  respjson.Field
		Name        respjson.Field
		UpdatedAt   respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

The organization that was created or updated.

func (TenantOrganization) RawJSON

func (r TenantOrganization) RawJSON() string

Returns the unmodified JSON received from the API

func (*TenantOrganization) UnmarshalJSON

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

type UpdateOrganizationParams

type UpdateOrganizationParams struct {
	// The organization's name.
	Name param.Opt[string] `json:"name,omitzero"`
	// Custom organization properties.
	Properties map[string]any `json:"properties,omitzero"`
	// contains filtered or unexported fields
}

Request payload for updating an organization.

func (UpdateOrganizationParams) MarshalJSON

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

func (*UpdateOrganizationParams) UnmarshalJSON

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

type UpdateOrganizationResponse

type UpdateOrganizationResponse struct {
	// The organization that was created or updated.
	Organization TenantOrganization `json:"organization" api:"required"`
	// Whether the API call was successful.
	Success bool `json:"success" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Organization respjson.Field
		Success      respjson.Field
		ExtraFields  map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Success response for organization update.

func (UpdateOrganizationResponse) RawJSON

func (r UpdateOrganizationResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*UpdateOrganizationResponse) UnmarshalJSON

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

type UpdatePromptParams

type UpdatePromptParams struct {
	// Updated prompt description.
	Description param.Opt[string] `json:"description,omitzero"`
	// Updated prompt name.
	Name param.Opt[string] `json:"name,omitzero"`
	// Role key in the product mapping.
	Role param.Opt[string] `json:"role,omitzero"`
	// Updated components (if provided, creates new immutable prompt and version).
	Components []ComponentUpdateParam `json:"components,omitzero"`
	// Prompt source.
	//
	// Any of "customer", "participant", "greenflash", "agent".
	Source UpdatePromptParamsSource `json:"source,omitzero"`
	// contains filtered or unexported fields
}

func (UpdatePromptParams) MarshalJSON

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

func (*UpdatePromptParams) UnmarshalJSON

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

type UpdatePromptParamsSource

type UpdatePromptParamsSource string

Prompt source.

const (
	UpdatePromptParamsSourceCustomer    UpdatePromptParamsSource = "customer"
	UpdatePromptParamsSourceParticipant UpdatePromptParamsSource = "participant"
	UpdatePromptParamsSourceGreenflash  UpdatePromptParamsSource = "greenflash"
	UpdatePromptParamsSourceAgent       UpdatePromptParamsSource = "agent"
)

type UpdatePromptResponse

type UpdatePromptResponse struct {
	// The updated prompt ID.
	PromptID string `json:"promptId" api:"required" format:"uuid"`
	// The version ID. Version is created/updated but not activated (activation happens
	// via UI). Null if only prompt metadata was updated without components.
	VersionID string `json:"versionId" api:"required" format:"uuid"`
	// The external prompt ID.
	ExternalPromptID string `json:"externalPromptId"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		PromptID         respjson.Field
		VersionID        respjson.Field
		ExternalPromptID respjson.Field
		ExtraFields      map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (UpdatePromptResponse) RawJSON

func (r UpdatePromptResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*UpdatePromptResponse) UnmarshalJSON

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

type UpdateUserParams

type UpdateUserParams struct {
	// Whether to anonymize the user's personal information.
	Anonymized param.Opt[bool] `json:"anonymized,omitzero"`
	// The user's email address.
	Email param.Opt[string] `json:"email,omitzero" format:"email"`
	// Your unique identifier for the organization this user belongs to. If provided,
	// the user will be associated with this organization.
	ExternalOrganizationID param.Opt[string] `json:"externalOrganizationId,omitzero"`
	// The user's full name.
	Name param.Opt[string] `json:"name,omitzero"`
	// The Greenflash organization ID that the user belongs to.
	OrganizationID param.Opt[string] `json:"organizationId,omitzero" format:"uuid"`
	// The user's phone number.
	Phone param.Opt[string] `json:"phone,omitzero"`
	// Additional data about the user (e.g., plan type, preferences).
	Properties map[string]any `json:"properties,omitzero"`
	// contains filtered or unexported fields
}

Request payload for updating an existing user profile.

func (UpdateUserParams) MarshalJSON

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

func (*UpdateUserParams) UnmarshalJSON

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

type UpdateUserResponse

type UpdateUserResponse struct {
	// The user profile.
	Participant Participant `json:"participant" api:"required"`
	// Whether the API call was successful.
	Success bool `json:"success" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Participant respjson.Field
		Success     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Success response for user update.

func (UpdateUserResponse) RawJSON

func (r UpdateUserResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*UpdateUserResponse) UnmarshalJSON

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

type UserGetUserAnalyticsParams

type UserGetUserAnalyticsParams struct {
	// Filter analytics by product ID.
	ProductID param.Opt[string] `query:"productId,omitzero" format:"uuid" json:"-"`
	// Filter analytics by version ID.
	VersionID param.Opt[string] `query:"versionId,omitzero" format:"uuid" json:"-"`
	// Analysis mode: "simple" returns only numeric aggregates (no rate limiting),
	// "insights" includes topics, keywords, and recommendations (rate limited per
	// tenant plan).
	//
	// Any of "simple", "insights".
	Mode UserGetUserAnalyticsParamsMode `query:"mode,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (UserGetUserAnalyticsParams) URLQuery

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

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

type UserGetUserAnalyticsParamsMode

type UserGetUserAnalyticsParamsMode string

Analysis mode: "simple" returns only numeric aggregates (no rate limiting), "insights" includes topics, keywords, and recommendations (rate limited per tenant plan).

const (
	UserGetUserAnalyticsParamsModeSimple   UserGetUserAnalyticsParamsMode = "simple"
	UserGetUserAnalyticsParamsModeInsights UserGetUserAnalyticsParamsMode = "insights"
)

type UserListParams

type UserListParams struct {
	// Maximum number of results to return.
	Limit param.Opt[float64] `query:"limit,omitzero" json:"-"`
	// Offset for pagination.
	Offset param.Opt[float64] `query:"offset,omitzero" json:"-"`
	// Filter users by organization ID.
	OrganizationID param.Opt[string] `query:"organizationId,omitzero" format:"uuid" json:"-"`
	// Page number (used to derive offset = (page-1)\*limit).
	Page param.Opt[float64] `query:"page,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (UserListParams) URLQuery

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

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

type UserNewParams

type UserNewParams struct {
	// Request payload for creating a new user profile.
	CreateUserParams CreateUserParams
	// contains filtered or unexported fields
}

func (UserNewParams) MarshalJSON

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

func (*UserNewParams) UnmarshalJSON

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

type UserService

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

Manage users

UserService contains methods and other services that help with interacting with the Greenflash 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 NewUserService method instead.

func NewUserService

func NewUserService(opts ...option.RequestOption) (r UserService)

NewUserService 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 (*UserService) GetUserAnalytics

func (r *UserService) GetUserAnalytics(ctx context.Context, userID string, query UserGetUserAnalyticsParams, opts ...option.RequestOption) (res *GetUserAnalyticsResponse, err error)

Understand how a specific user engages with your AI across all their conversations. Track their satisfaction, identify pain points, and spot opportunities to improve their experience.

**⚠️ Requires Growth+ plan or higher**

**Two modes available:**

  • **simple mode**: Get aggregate metrics like average sentiment, frustration levels, and conversation quality. Perfect for user dashboards. No rate limiting.
  • **insights mode** (default): Access detailed patterns, recurring topics, and AI-generated recommendations specific to this user. Rate limited based on your plan's `maxAnalysesPerHour`.

Returns 404 if the user doesn't exist or has no conversations yet.

func (*UserService) List

func (r *UserService) List(ctx context.Context, query UserListParams, opts ...option.RequestOption) (res *ListUsersResponse, err error)

Browse through all the users in your workspace. Filter by organization to see who belongs to specific teams or companies. Results are paginated for easy navigation through large user bases.

func (*UserService) New

func (r *UserService) New(ctx context.Context, body UserNewParams, opts ...option.RequestOption) (res *CreateUserResponse, err error)

Keep track of who's talking to your AI by creating user profiles with contact information and custom properties.

Provide an `externalUserId` to identify the user—your ID from your own system. Don't worry about whether they already exist; we'll create them if they're new or update their profile if they already exist. This makes syncing user data effortless.

You can then reference this user in other API calls using the same `externalUserId`.

Optionally associate users with an organization by providing an `externalOrganizationId`. If the organization doesn't exist yet, we'll create it automatically.

func (*UserService) Update

func (r *UserService) Update(ctx context.Context, userID string, body UserUpdateParams, opts ...option.RequestOption) (res *UpdateUserResponse, err error)

Update specific fields of an existing user profile without changing everything.

The `userId` in the URL path should be your `externalUserId`. Only the fields you include in your request will be updated—everything else stays the same. Perfect for targeted updates like changing an email address or adding new properties.

Prefer a simpler approach? Use `POST /users` instead—it automatically creates or updates the user, so you don't need to know if they exist yet.

Optionally associate the user with an organization by providing an `externalOrganizationId`. If the organization doesn't exist yet, we'll create it automatically.

type UserUpdateParams

type UserUpdateParams struct {
	// Request payload for updating an existing user profile.
	UpdateUserParams UpdateUserParams
	// contains filtered or unexported fields
}

func (UserUpdateParams) MarshalJSON

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

func (*UserUpdateParams) UnmarshalJSON

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

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