client

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2024 License: MIT Imports: 14 Imported by: 0

README

Gradient Labs Go

Go Reference

Go bindings for the Gradient Labs API.

Documentation

Overview

Package client implements Go bindings for the Gradient Labs API.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidWebhookSignature is returned when the authenticity of the webhook
	// could not be verified using its signature. You should respond with an HTTP
	// 401 status code.
	ErrInvalidWebhookSignature = fmt.Errorf("%s header is invalid", signatureHeader)

	// ErrUnknownWebhookType is returned when the webhook contained an event of an
	// unknwon type. You should generally log these and return an HTTP 200 status
	// code.
	ErrUnknownWebhookType = errors.New("unknown webhook type")
)

Functions

This section is empty.

Types

type ActionExecuteEvent added in v0.2.1

type ActionExecuteEvent struct {
	// Action is the name of the action to execute
	Action string `json:"action"`

	// Params are the arguments to execute the action with.
	Params json.RawMessage `json:"params"`

	// Conversation contains the details of the conversation the event relates to.
	Conversation WebhookConversation `json:"conversation"`
}

ActionExecuteEvent contains the data for a `action.execute` event.

type AddMessageParams

type AddMessageParams struct {
	// ID uniquely identifies this message within the conversation.
	//
	// Can be anything consisting of letters, numbers, or any of the following
	// characters: _ - + =.
	//
	// Tip: use something meaningful to your business.
	ID string `json:"id"`

	// Body contains the message text.
	Body string `json:"body"`

	// ParticipantID identifies the message sender.
	ParticipantID string `json:"participant_id"`

	// ParticipantType identifies the type of participant who sent this message.
	// This cannot be set to ParticipantTypeAI.
	ParticipantType ParticipantType `json:"participant_type"`

	// Created is the time at which the message was sent.
	Created time.Time `json:"created"`

	// Metadata is arbitrary metadata that will be attached to the message.
	Metadata any `json:"metadata"`

	// Attachments contains any files that were uploaded with this message.
	Attachments []*Attachment `json:"attachments,omitempty"`
}

AddMessageParams are the parameters to Client.AddMessage.

type AgentMessageEvent

type AgentMessageEvent struct {
	// Conversation contains the details of the conversation the event relates to.
	Conversation WebhookConversation `json:"conversation"`

	// Body contains the text of the message the agent wants to send.
	Body string `json:"body"`
}

AgentMessageEvent contains the data for an `agent.message` webhook event.

type AssignmentParams added in v0.1.3

type AssignmentParams struct {
	// AssigneeID optionally identifies the specific user that the conversation
	// is being assigned to.
	AssigneeID string `json:"assignee_id,omitempty"`

	// AssigneeType identifies the type of participant that this conversation is
	// being assigned to. Set this to ParticipantTypeAIAgent to assign the conversation
	// to the Gradient Labs AI agent.
	AssigneeType ParticipantType `json:"assignee_type"`

	// Timestamp optionally defines the time when the conversation was assigned.
	// If not given, this will default to the current time.
	Timestamp *time.Time `json:"timestamp,omitempty"`
}

type Attachment added in v0.1.1

type Attachment struct {
	// Type of file that was uploaded.
	Type AttachmentType `json:"type"`

	// FileName is the name of the file that was uploaded.
	FileName string `json:"file_name"`
}

Attachment represents a file that was uploaded with a message.

type AttachmentType added in v0.1.1

type AttachmentType string

AttachmentType identifies the type of file that has been attached to a message. Currently, our AI agent does not support processing attachments, and will hand the conversation off to a human agent if it encounters one.

const (
	// AttachmentTypeImage indicates that the attachment is an image.
	AttachmentTypeImage AttachmentType = "image"

	// AttachmentTypeFile indicates that the attachment is a generic file such as
	// a document.
	AttachmentTypeFile AttachmentType = "file"
)

type CancelParams added in v0.2.1

type CancelParams struct {
	// Timestamp optionally defines the time when the conversation was cancelled.
	// If not given, this will default to the current time.
	Timestamp *time.Time `json:"timestamp,omitempty"`
}

type Channel

type Channel string

Channel represents the way a customer is getting in touch. It will be used to determine how the agent formats responses, etc.

const (
	// ChannelWeb indicates the customer is getting in touch via a live instant
	// message chat.
	ChannelWeb Channel = "web"

	// ChannelEmail indicates the customer is getting in touch via an email.
	ChannelEmail Channel = "email"
)

type Client

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

Client provides access to the Gradient Labs API. Use NewClient to create one.

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient creates a client with the given options.

Note: the WithAPIKey option is required, as is WithWebhookSigningKey if you intend to receive webhooks.

func (*Client) AddConversationEvent added in v0.1.5

func (c *Client) AddConversationEvent(ctx context.Context, conversationID string, p *EventParams) error

AddConversationEvent records an event such as the customer started typing.

func (*Client) AddMessage

func (c *Client) AddMessage(ctx context.Context, conversationID string, p AddMessageParams) (*Message, error)

AddMessage records a message sent by the customer or a human agent.

func (*Client) AddResource added in v0.1.6

func (c *Client) AddResource(ctx context.Context, conversationID string, name string, resource any) error

AddResource adds (or updates) a resource to the conversation (e.g. the customer's order details) so the AI agent can handle customer-specific queries.

A resource can be any JSON document, as long it is smaller than 1MB. There are no strict requirements on the format/structure of the document, but we recommend making attribute names as descriptive as possible.

Over time, the AI agent will learn the structure of your resources - so while it's fine to add new attributes, you may want to consider using new resource names when removing attributes or changing the structure of your resources significantly.

Resource names are case-insensitive and can be anything consisting of letters, numbers, or any of the following characters: _ - + =.

Names should be descriptive handles that are the same for all conversations (e.g. "order-details" and "user-profile") not unique identifiers.

func (*Client) AssignConversation added in v0.1.3

func (c *Client) AssignConversation(ctx context.Context, conversationID string, p *AssignmentParams) error

AssignConversation assigns a conversation to a participant.

func (*Client) CancelConversation

func (c *Client) CancelConversation(ctx context.Context, conversationID string, p CancelParams) error

CancelConversation cancels the conversation.

This is intended for cases where the conversation is being explicitly cancelled or terminated. Use FinishConversation() when the conversation is has reached a natural 'end' state, such as it being resolved or closed due to inactivity.

func (*Client) FinishConversation added in v0.2.1

func (c *Client) FinishConversation(ctx context.Context, conversationID string, p FinishParams) error

FinishConversation finishes a conversation.

A conversation finishes when it has come to its natural conclusion. This could be because the customer's query has been resolved, a human agent or other automation has closed the chat, or because the chat is being closed due to inactivity.

func (*Client) ParseWebhook

func (c *Client) ParseWebhook(req *http.Request) (*Webhook, error)

ParseWebhook parses the request, verifies its signature, and returns the webhook data.

func (*Client) ReadConversation added in v0.1.3

func (c *Client) ReadConversation(ctx context.Context, conversationID string) (*Conversation, error)

ReadConversation returns a conversation.

func (*Client) StartConversation

func (c *Client) StartConversation(ctx context.Context, p StartConversationParams) (*Conversation, error)

StartConversation begins a conversation.

func (*Client) UpsertArticle added in v0.1.8

func (c *Client) UpsertArticle(ctx context.Context, p *UpsertArticleParams) error

UpsertArticle inserts or updates a help article

func (*Client) UpsertArticleTopic added in v0.1.8

func (c *Client) UpsertArticleTopic(ctx context.Context, p *UpsertArticleTopicParams) error

func (*Client) UpsertHandOffTarget added in v0.2.0

func (c *Client) UpsertHandOffTarget(ctx context.Context, p *UpsertHandOffTargetParams) error

UpsertHandOffTarget inserts or updates a hand-off target

func (*Client) VerifyWebhookRequest

func (c *Client) VerifyWebhookRequest(req *http.Request) error

VerifyWebhookRequest verifies the authenticity of the given request using its signature header. You do not need to call it if you're already using Client.ParseWebhook.

type Conversation

type Conversation struct {
	// ID uniquely identifies the conversation.
	//
	// Can be anything consisting of letters, numbers, or any of the following
	// characters: _ - + =.
	//
	// Tip: use something meaningful to your business (e.g. a ticket number).
	ID string `json:"id"`

	// CustomerID uniquely identifies the customer. Used to build historical
	// context of conversations the agent has had with this customer.
	CustomerID string `json:"customer_id"`

	// Channel represents the way a customer is getting in touch. It will be used
	// to determine how the agent formats responses, etc.
	Channel Channel `json:"channel"`

	// Metadata is arbitrary metadata that will be attached to the conversation.
	// It will be passed along with webhooks so can be used as action parameters.
	Metadata any `json:"metadata"`

	// Created is the time at which the conversation was created.
	Created time.Time `json:"created"`

	// Updated is the time at which the conversation was last updated.
	Updated time.Time `json:"updated"`

	// Status describes the current state of the conversation.
	Status Status `json:"status"`
}

Conversation represents a series of messages between a customer, human agent, and the AI Agent.

type ConversationEventType added in v0.1.5

type ConversationEventType string

ConversationEventType describes an event that occurred within the conversation.

const (
	// ConversationEventTypeTyping means the customer or human agent started typing.
	ConversationEventTypeTyping ConversationEventType = "typing"

	// ConversationEventTypeMessageDelivered means that a message has been delivered
	// to a participant
	ConversationEventTypeMessageDelivered ConversationEventType = "delivered"

	// ConversationEventTypeMessageDelivered means that a message has been read
	// by the participant it was delivered to
	ConversationEventTypeMessageRead ConversationEventType = "read"

	// ConversationEventTypeJoin means the customer or human agent joined the
	// conversation.
	ConversationEventTypeJoin ConversationEventType = "join"

	// ConversationEventTypeLeave means the customer or human agent left the
	// conversation.
	ConversationEventTypeLeave ConversationEventType = "leave"
)

type ConversationFinishedEvent

type ConversationFinishedEvent struct {
	// Conversation contains the details of the conversation the event relates to.
	Conversation WebhookConversation `json:"conversation"`

	// Reason is the code that describes why the agent wants to finish this
	// conversation.
	Reason string `json:"reason_code,omitempty"`

	// Intent is the most recent intent that was classified from the customer's
	// conversation, if any.
	Intent string `json:"intent,omitempty"`
}

ConversationFinishedEvent contains the data for a `conversation.finished` event.

type ConversationHandOffEvent

type ConversationHandOffEvent struct {
	// Conversation contains the details of the conversation the event relates to.
	Conversation WebhookConversation `json:"conversation"`

	// Target defines where the agent wants to hand this conversation to.
	Target string `json:"target,omitempty"`

	// Reason is the code that describes why the agent wants to hand off this
	// conversation.
	Reason string `json:"reason_code"`

	// Description is a human-legible description of the Reason code.
	Description string `json:"reason"`

	// Intent is the most recent intent that was classified from the customer's
	// conversation, if any.
	Intent string `json:"intent,omitempty"`
}

ConversationHandOffEvent contains the data for a `conversation.hand_off` event.

type EventParams added in v0.1.5

type EventParams struct {
	// Type identifies the type of event (see: ConversationEventType).
	Type ConversationEventType `json:"type"`

	// ParticipantID identifies the message sender.
	ParticipantID string `json:"participant_id"`

	// ParticipantType identifies the type of participant who sent this message.
	ParticipantType ParticipantType `json:"participant_type"`

	// MessageID optionally identifies the message that this event relates to
	MessageID *string `json:"message_id,omitempty"`

	// Timestamp optionally defines the time when the conversation was assigned.
	// If not given, this will default to the current time.
	Timestamp *time.Time `json:"timestamp,omitempty"`

	// IdempotencyKey optionally enables you to safely retry requests
	IdempotencyKey string `json:"idempotency_key,omitempty"`
}

type FinishParams added in v0.2.1

type FinishParams struct {
	// Timestamp optionally defines the time when the conversation ended.
	// If not given, this will default to the current time.
	Timestamp *time.Time `json:"timestamp,omitempty"`
}

type Message

type Message struct {
	// ID uniquely identifies this message within the conversation.
	//
	// Can be anything consisting of letters, numbers, or any of the following
	// characters: _ - + =.
	//
	// Tip: use something meaningful to your business.
	ID string `json:"id"`

	// Body contains the message text.
	Body string `json:"body"`

	// ParticipantID identifies the message sender.
	ParticipantID string `json:"participant_id"`

	// ParticipantType identifies the type of participant who sent this message.
	ParticipantType ParticipantType `json:"participant_type"`

	// Created is the time at which the message was sent.
	Created *time.Time `json:"created"`

	// Metadata is arbitrary metadata attached to the message.
	Metadata any `json:"metadata"`

	// Attachments contains any files that were uploaded with this message.
	Attachment []*Attachment `json:"attachments,omitempty"`
}

Message represents a message sent by a customer, human support agent, or the API agent.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option customises the Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the client's API key.

func WithTransport

func WithTransport(rt http.RoundTripper) Option

WithTransport customises the HTTP client's Transport, which is useful for observability (e.g. capturing trace spaces, metrics) and in unit tests.

func WithURL

func WithURL(url string) Option

WithURL overrides the default base URL.

func WithWebhookLeeway

func WithWebhookLeeway(leeway time.Duration) Option

WithWebhookLeeway determines the maximum age of webhook that will be accepted by Client.VerifyWebhookRequest.

func WithWebhookSigningKey

func WithWebhookSigningKey(key string) Option

WithWebhookSigningKey sets the client's webhook signing key. It will be used to verify webhook authenticity.

type ParticipantType

type ParticipantType string

ParticipantType identifies the type of participant who sent a message or is assigned to a conversation.

const (
	// ParticipantTypeCustomer is a  customer/end-user.
	ParticipantTypeCustomer ParticipantType = "Customer"

	// ParticipantTypeHumanAgent is a human support agent.
	ParticipantTypeHumanAgent ParticipantType = "Agent"

	// ParticipantTypeBot is an automation/bot other than the Gradient Labs AI agent.
	ParticipantTypeBot ParticipantType = "Bot"

	// ParticipantTypeAIAgent is the Gradient Labs AI agent.
	ParticipantTypeAIAgent ParticipantType = "AI Agent"
)

type PublicationStatus added in v0.1.8

type PublicationStatus string

PublicationStatus describes the status of a help article.

const (
	// PublicationStatusDraft means that the article is being written or
	// edited and is not published.
	PublicationStatusDraft PublicationStatus = "draft"

	// PublicationStatusPublished means that the article is published.
	PublicationStatusPublished PublicationStatus = "published"
)

type ResponseError

type ResponseError struct {
	StatusCode int
	Message    string
	Details    map[string]any
}

ResponseError represents an error response from the API.

func (*ResponseError) Error

func (re *ResponseError) Error() string

Error satisfies the error interface.

func (*ResponseError) TraceID

func (re *ResponseError) TraceID() string

TraceID returns the identifier that can be given to Gradient Labs technical support to investigate an error.

type StartConversationParams

type StartConversationParams struct {
	// ID uniquely identifies the conversation.
	//
	// Can be anything consisting of letters, numbers, or any of the following
	// characters: _ - + =.
	//
	// Tip: use something meaningful to your business (e.g. a ticket number).
	ID string `json:"id"`

	// CustomerID uniquely identifies the customer. Used to build historical
	// context of conversations the agent has had with this customer.
	CustomerID string `json:"customer_id"`

	// AssigneeID optionally identifies who the conversation is assigned to.
	AssigneeID string `json:"assignee_id,omitempty"`

	// AssigneeType optionally identifies which type of participant is currently
	// assigned to respond. Set this to ParticipantTypeAIAgent to assign the conversation
	// to the Gradient Labs AI when starting it.
	AssigneeType ParticipantType `json:"assignee_type,omitempty"`

	// Channel represents the way a customer is getting in touch. It will be used
	// to determine how the agent formats responses, etc.
	Channel Channel `json:"channel"`

	// Metadata is arbitrary metadata that will be attached to the conversation.
	// It will be passed along with webhooks so can be used as action parameters.
	Metadata any `json:"metadata"`

	// Created optionally defines the time when the conversation started.
	// If not given, this will default to the current time.
	Created *time.Time `json:"created,omitempty"`
}

StartConversationParams are the parameters to Client.StartConversation.

type Status

type Status string

Status describes the current state of the conversation.

const (
	// StatusObserving indicates the agent is following the conversation but not
	// participating (e.g. when it has been handed-off to a human).
	StatusObserving Status = "observing"

	// StatusActive indicates the agent is actively participating in the
	// conversation.
	StatusActive Status = "active"

	// StatusCancelled indicates the conversation has been prematurely brought to
	// a close (e.g. because a human has taken it over) and the AI agent can no
	// longer participate in it.
	StatusCancelled Status = "cancelled"

	// StatusFinished indicates the conversation has been closed because the
	// customer's issue has been resolved.
	StatusFinished Status = "finished"

	// StatusFailed indicates the agent encountered an irrecoverable error, such as
	// not being able to deliver a message to your webhook endpoint after multiple
	// retries.
	StatusFailed Status = "failed"
)

type UpsertArticleParams added in v0.1.8

type UpsertArticleParams struct {
	// AuthorID optionally identifies the user who last edited the article
	AuthorID string `json:"author_id"`

	// ID is your identifier of choice for this article.
	ID string `json:"id"`

	// Title is the article's title. It may be empty if the article is a draft.
	Title string `json:"title"`

	// Description is an article's tagline. It may be empty.
	Description string `json:"description"`

	// Body is the main contents of an article. It may be empty if the article is a draft.
	Body string `json:"body"`

	// Visibility describes who can access this article, ranging from the
	// whole world (public) through to employees only (internal).
	Visibility Visibility `json:"visibility"`

	// TopicID optionally identifies the topic that this
	// article is associated with. If given, you must have created
	// the topic first (see: UpsertArticleTopic)
	TopicID string `json:"topic_id"`

	// PublicationStatus describes whether this article is published or not.
	PublicationStatus PublicationStatus `json:"status"`

	// Data optionally gives additional meta-data about the article.
	Data json.RawMessage `json:"data"`

	// Created is when the article was first authored.
	Created time.Time `json:"created"`

	// LastEdited is when the article was last changed.
	LastEdited time.Time `json:"last_edited"`
}

type UpsertArticleTopicParams added in v0.1.8

type UpsertArticleTopicParams struct {
	// ID is your identifier for this topic
	ID string `json:"id"`

	// ParentID is the identifier for this topic's parent topic (if any).
	ParentID string `json:"parent_id"`

	// Name is the topic's name. This cannot be nil.
	Name string `json:"name"`

	// Description is an topic's tagline. It may be empty.
	Description string `json:"description"`

	// Visibility describes who can see this topic, ranging from the
	// whole world (public) through to employees only (internal).
	Visibility Visibility `json:"visibility"`

	// PublicationStatus describes whether this topic is published or not.
	PublicationStatus PublicationStatus `json:"status"`

	// Data optionally gives additional meta-data about the topic.
	Data json.RawMessage `json:"data"`

	// Created is when the topic was first created.
	Created time.Time `json:"created"`

	// LastEdited is when the topic was last changed.
	LastEdited time.Time `json:"last_edited"`
}

type UpsertHandOffTargetParams added in v0.2.0

type UpsertHandOffTargetParams struct {
	// ID is your identifier of choice for this hand-off target. Can be anything consisting
	// of letters, numbers, or any of the following characters: `_` `-` `+` `=`.
	ID string `json:"id"`

	// Name is the hand-off target’s name. This cannot be nil.
	Name string `json:"name"`
}

type Visibility added in v0.1.8

type Visibility string

Visibility describes who can view the given item (e.g. help article)

const (
	// VisibilityPublic means that the item is available to the general
	// public. For example, it is published on a public website.
	VisibilityPublic Visibility = "public"

	// VisibilityUsers means that the item is only available to the
	// company's customers. For example, it is only accessible via an
	// app after sign-up.
	VisibilityUsers Visibility = "users"

	// VisibilityInternal means that the item is only available to
	// the company's employees. For example, it is a procedure or SOP
	// that customers do not have access to.
	VisibilityInternal Visibility = "internal"
)

type Webhook

type Webhook struct {
	// ID uniquely identifies this event.
	ID string `json:"id"`

	// Type indicates the type of event.
	Type WebhookType `json:"type"`

	// SequenceNumber can be used to establish an order of webhook events.
	// For more information, see: https://api-docs.gradient-labs.ai/#sequence-numbers
	SequenceNumber int `json:"sequence_number"`

	// Timestamp is the time at which this event was generated.
	Timestamp time.Time `json:"timestamp"`

	// Data contains the event data. Use the helper methods (e.g.
	// Webhook.AgentMessage) to access it.
	Data any `json:"-"`
}

Webhook is an event delivered to your webhook endpoint.

func (Webhook) ActionExecute added in v0.2.1

func (w Webhook) ActionExecute() (*ActionExecuteEvent, bool)

func (Webhook) AgentMessage

func (w Webhook) AgentMessage() (*AgentMessageEvent, bool)

AgentMessage returns the data for an `agent.message` event.

func (Webhook) ConversationFinished

func (w Webhook) ConversationFinished() (*ConversationFinishedEvent, bool)

ConversationFinished returns the data for an `conversation.finished` event.

func (Webhook) ConversationHandOff

func (w Webhook) ConversationHandOff() (*ConversationHandOffEvent, bool)

ConversationHandOff returns the data for an `conversation.hand_off` event.

type WebhookConversation

type WebhookConversation struct {
	// ID is chosen unique identifier for this conversation.
	ID string `json:"id"`

	// CustomerID is your chosen identifier for the customer.
	CustomerID string `json:"customer_id"`

	// Metadata you attached to the conversation with Client.StartConversation.
	Metadata any `json:"metadata"`
}

WebhookConversation contains the details of the conversation the webhook relates to.

type WebhookType

type WebhookType string

WebhookType indicates the type of webhook event.

const (
	// WebhookTypeAgentMessage indicates the agent wants to send the customer a
	// message.
	WebhookTypeAgentMessage WebhookType = "agent.message"

	// WebhookTypeConversationHandOff indicates the agent is escalating or handing
	// the conversation off to a human agent.
	WebhookTypeConversationHandOff WebhookType = "conversation.hand_off"

	// WebhookTypeConversationFinished indicates the agent has concluded the
	// conversation with the customer and you should close any corresponding
	// ticket, etc.
	WebhookTypeConversationFinished WebhookType = "conversation.finished"

	// WebhookTypeAction indicates that the agent needs an action to
	// be executed (e.g., while following a procedure)
	WebhookTypeActionExecute WebhookType = "action.execute"
)

type WebhookVerifier

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

WebhookVerifier verifies the authenticity of requests to your webhook endpoint using the X-GradientLabs-Signature header.

func (WebhookVerifier) VerifyRequest

func (v WebhookVerifier) VerifyRequest(req *http.Request) error

VerifyRequest verifies the authenticity of the given request using its signature header.

func (WebhookVerifier) VerifySignature

func (v WebhookVerifier) VerifySignature(body []byte, sig string) error

VerifySignature is a lower level variant of VerifyRequest

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL