ai

package
v0.0.0-...-1d0f068 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2024 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterEmbedder

func RegisterEmbedder(name string, embedder Embedder)

RegisterEmbedder registers the actions for a specific embedder.

func RegisterGenerator

func RegisterGenerator(provider, name string, metadata *GeneratorMetadata, generator Generator)

RegisterGenerator registers the generator in the global registry.

func RegisterPrompt

func RegisterPrompt(provider, name string, prompt Prompt)

RegisterPrompt registers a prompt in the global registry.

func RegisterTool

func RegisterTool(name string, definition *ToolDefinition, metadata map[string]any, fn func(ctx context.Context, input map[string]any) (map[string]any, error))

RegisterTool registers a tool function.

func RunTool

func RunTool(ctx context.Context, name string, input map[string]any) (map[string]any, error)

RunTool looks up a tool registered by RegisterTool, runs it with the given input, and returns the result.

Types

type Candidate

type Candidate struct {
	Custom        any              `json:"custom,omitempty"`
	FinishMessage string           `json:"finishMessage,omitempty"`
	FinishReason  FinishReason     `json:"finishReason,omitempty"`
	Index         int              `json:"index,omitempty"`
	Message       *Message         `json:"message,omitempty"`
	Usage         *GenerationUsage `json:"usage,omitempty"`
}

A Candidate is one of several possible generated responses from a generation request. It contains a single generated message along with additional metadata about its generation. A generation request may result in multiple Candidates.

func (*Candidate) Text

func (c *Candidate) Text() (string, error)

Text returns the contents of a Candidate as a string. It returns an error if the candidate has no message.

type CandidateError

type CandidateError struct {
	Code    CandidateErrorCode `json:"code,omitempty"`
	Index   float64            `json:"index,omitempty"`
	Message string             `json:"message,omitempty"`
}

type CandidateErrorCode

type CandidateErrorCode string
const (
	CandidateErrorCodeBlocked CandidateErrorCode = "blocked"
	CandidateErrorCodeOther   CandidateErrorCode = "other"
	CandidateErrorCodeUnknown CandidateErrorCode = "unknown"
)

type Document

type Document struct {
	// The data that is part of this document.
	Content []*Part `json:"content,omitempty"`
	// The metadata for this document.
	Metadata map[string]any `json:"metadata,omitempty"`
}

A Document is a piece of data that can be embedded, indexed, or retrieved. It includes metadata. It can contain multiple parts.

func DocumentFromText

func DocumentFromText(text string, metadata map[string]any) *Document

DocumentFromText returns a Document containing a single plain text part. This takes ownership of the metadata map.

type DocumentStore

type DocumentStore interface {
	// Add a document to the database.
	Index(context.Context, *IndexerRequest) error
	// Retrieve matching documents from the database.
	Retrieve(context.Context, *RetrieverRequest) (*RetrieverResponse, error)
}

DocumentStore supports adding documents to a database, and retrieving documents from the database that are similar to a query document. Vector databases will implement this interface.

func DefineDocumentStore

func DefineDocumentStore(
	name string,
	index func(context.Context, *IndexerRequest) error,
	retrieve func(context.Context, *RetrieverRequest) (*RetrieverResponse, error),
) DocumentStore

DefineDocumentStore takes index and retrieve functions that access a document store and returns a new DocumentStore that wraps them in registered actions.

type EmbedRequest

type EmbedRequest struct {
	Document *Document `json:"input"`
	Options  any       `json:"options,omitempty"`
}

EmbedRequest is the data we pass to convert a document to a multidimensional vector.

type Embedder

type Embedder interface {
	Embed(context.Context, *EmbedRequest) ([]float32, error)
}

Embedder is the interface used to convert a document to a multidimensional vector. A DocumentStore will use a value of this type.

type FinishReason

type FinishReason string

FinishReason is the reason why a model stopped generating tokens.

const (
	FinishReasonStop    FinishReason = "stop"
	FinishReasonLength  FinishReason = "length"
	FinishReasonBlocked FinishReason = "blocked"
	FinishReasonOther   FinishReason = "other"
	FinishReasonUnknown FinishReason = "unknown"
)

type GenerateRequest

type GenerateRequest struct {
	Candidates int   `json:"candidates,omitempty"`
	Config     any   `json:"config,omitempty"`
	Context    []any `json:"context,omitempty"`
	// Messages is a list of messages to pass to the model. The first n-1 Messages
	// are treated as history. The last Message is the current request.
	Messages []*Message             `json:"messages,omitempty"`
	Output   *GenerateRequestOutput `json:"output,omitempty"`
	Tools    []*ToolDefinition      `json:"tools,omitempty"`
}

A GenerateRequest is a request to generate completions from a model.

type GenerateRequestOutput

type GenerateRequestOutput struct {
	Format OutputFormat   `json:"format,omitempty"`
	Schema map[string]any `json:"schema,omitempty"`
}

GenerateRequestOutput describes the structure that the model's output should conform to. If Format is OutputFormatJSON, then Schema can describe the desired form of the generated JSON.

type GenerateResponse

type GenerateResponse struct {
	Candidates []*Candidate     `json:"candidates,omitempty"`
	Custom     any              `json:"custom,omitempty"`
	LatencyMs  float64          `json:"latencyMs,omitempty"`
	Request    *GenerateRequest `json:"request,omitempty"`
	Usage      *GenerationUsage `json:"usage,omitempty"`
}

A GenerateResponse is a model's response to a GenerateRequest.

func Generate

Generate applies a Generator to some input, handling tool requests.

func (*GenerateResponse) Text

func (gr *GenerateResponse) Text() (string, error)

Text returns the contents of the first candidate in a GenerateResponse as a string. It returns an error if there are no candidates or if the candidate has no message.

type GenerateResponseChunk

type GenerateResponseChunk struct {
	Content []*Part `json:"content,omitempty"`
	Custom  any     `json:"custom,omitempty"`
	Index   float64 `json:"index,omitempty"`
}

type GenerationCommonConfig

type GenerationCommonConfig struct {
	MaxOutputTokens int      `json:"maxOutputTokens,omitempty"`
	StopSequences   []string `json:"stopSequences,omitempty"`
	Temperature     float64  `json:"temperature,omitempty"`
	TopK            int      `json:"topK,omitempty"`
	TopP            float64  `json:"topP,omitempty"`
	Version         string   `json:"version,omitempty"`
}

GenerationCommonConfig holds configuration for generation.

type GenerationUsage

type GenerationUsage struct {
	Custom           map[string]float64 `json:"custom,omitempty"`
	InputCharacters  float64            `json:"inputCharacters,omitempty"`
	InputImages      float64            `json:"inputImages,omitempty"`
	InputTokens      float64            `json:"inputTokens,omitempty"`
	OutputCharacters float64            `json:"outputCharacters,omitempty"`
	OutputImages     float64            `json:"outputImages,omitempty"`
	OutputTokens     float64            `json:"outputTokens,omitempty"`
	TotalTokens      float64            `json:"totalTokens,omitempty"`
}

GenerationUsage provides information about the generation process.

type Generator

type Generator interface {
	// If the streaming callback is non-nil:
	// - Each response candidate will be passed to that callback instead of
	//   populating the result's Candidates field.
	// - If the streaming callback returns a non-nil error, generation will stop
	//   and Generate immediately returns that error (and a nil response).
	Generate(context.Context, *GenerateRequest, func(context.Context, *Candidate) error) (*GenerateResponse, error)
}

Generator is the interface used to query an AI model.

func LookupGeneratorAction

func LookupGeneratorAction(provider, name string) (Generator, error)

LookupGeneratorAction looks up an action registered by RegisterGenerator and returns a generator that invokes the action.

type GeneratorCapabilities

type GeneratorCapabilities struct {
	Multiturn  bool
	Media      bool
	Tools      bool
	SystemRole bool
}

GeneratorCapabilities describes various capabilities of the generator.

type GeneratorMetadata

type GeneratorMetadata struct {
	Label    string
	Supports GeneratorCapabilities
}

GeneratorMetadata is the metadata of the generator, specifying things like nice user visible label, capabilities, etc.

type IndexerRequest

type IndexerRequest struct {
	Documents []*Document `json:"docs"`
	Options   any         `json:"options,omitempty"`
}

IndexerRequest is the data we pass to add documents to the database. The Options field is specific to the actual retriever implementation.

type Message

type Message struct {
	Content []*Part `json:"content,omitempty"`
	Role    Role    `json:"role,omitempty"`
}

Message is the contents of a model response.

type ModelInfo

type ModelInfo struct {
	Label    string             `json:"label,omitempty"`
	Supports *ModelInfoSupports `json:"supports,omitempty"`
	Versions []string           `json:"versions,omitempty"`
}

type ModelInfoSupports

type ModelInfoSupports struct {
	Context    bool         `json:"context,omitempty"`
	Media      bool         `json:"media,omitempty"`
	Multiturn  bool         `json:"multiturn,omitempty"`
	Output     OutputFormat `json:"output,omitempty"`
	SystemRole bool         `json:"systemRole,omitempty"`
	Tools      bool         `json:"tools,omitempty"`
}

type OutputFormat

type OutputFormat string

OutputFormat is the format that the model's output should produce.

const (
	OutputFormatJSON  OutputFormat = "json"
	OutputFormatText  OutputFormat = "text"
	OutputFormatMedia OutputFormat = "media"
)

type Part

type Part struct {
	Kind         PartKind      `json:"kind,omitempty"`
	ContentType  string        `json:"contentType,omitempty"` // valid for kind==blob
	Text         string        `json:"text,omitempty"`        // valid for kind∈{text,blob}
	ToolRequest  *ToolRequest  `json:"toolreq,omitempty"`     // valid for kind==partToolRequest
	ToolResponse *ToolResponse `json:"toolresp,omitempty"`    // valid for kind==partToolResponse
}

A Part is one part of a Document. This may be plain text or it may be a URL (possibly a "data:" URL with embedded data).

func NewDataPart

func NewDataPart(contents string) *Part

NewDataPart returns a Part containing raw string data.

func NewJSONPart

func NewJSONPart(text string) *Part

NewJSONPart returns a Part containing JSON.

func NewMediaPart

func NewMediaPart(mimeType, contents string) *Part

NewMediaPart returns a Part containing structured data described by the given mimeType.

func NewTextPart

func NewTextPart(text string) *Part

NewTextPart returns a Part containing text.

func NewToolRequestPart

func NewToolRequestPart(r *ToolRequest) *Part

NewToolRequestPart returns a Part containing a request from the model to the client to run a Tool. (Only genkit plugins should need to use this function.)

func NewToolResponsePart

func NewToolResponsePart(r *ToolResponse) *Part

NewToolResponsePart returns a Part containing the results of applying a Tool that the model requested.

func (*Part) IsData

func (p *Part) IsData() bool

IsData reports whether the Part contains unstructured data.

func (*Part) IsMedia

func (p *Part) IsMedia() bool

IsMedia reports whether the Part contains structured media data.

func (*Part) IsText

func (p *Part) IsText() bool

IsText reports whether the Part contains plain text.

func (*Part) IsToolRequest

func (p *Part) IsToolRequest() bool

IsToolRequest reports whether the Part contains a request to run a tool.

func (*Part) IsToolResponse

func (p *Part) IsToolResponse() bool

IsToolResponse reports whether the Part contains the result of running a tool.

func (*Part) MarshalJSON

func (p *Part) MarshalJSON() ([]byte, error)

MarshalJSON is called by the JSON marshaler to write out a Part.

func (*Part) UnmarshalJSON

func (p *Part) UnmarshalJSON(b []byte) error

UnmarshalJSON is called by the JSON unmarshaler to read a Part.

type PartKind

type PartKind int8
const (
	PartText PartKind = iota
	PartMedia
	PartData
	PartToolRequest
	PartToolResponse
)

type Prompt

type Prompt interface {
	Generate(context.Context, *PromptRequest, func(context.Context, *Candidate) error) (*GenerateResponse, error)
}

Prompt is the interface used to execute a prompt template and pass the result to a Generator.

type PromptRequest

type PromptRequest struct {
	// Input fields for the prompt. If not nil this should be a struct
	// or pointer to a struct that matches the prompt's input schema.
	Variables any `json:"variables,omitempty"`
	// Number of candidates to return; if 0, will be taken
	// from the prompt config; if still 0, will use 1.
	Candidates int `json:"candidates,omitempty"`
	// Generator Configuration. If nil will be taken from the prompt config.
	Config *GenerationCommonConfig `json:"config,omitempty"`
	// Context to pass to model, if any.
	Context []any `json:"context,omitempty"`
	// The model to use. This overrides any model specified by the prompt.
	Model string `json:"model,omitempty"`
}

PromptRequest is a request to execute a prompt template and pass the result to a Generator.

type RetrieverRequest

type RetrieverRequest struct {
	Document *Document `json:"content"`
	Options  any       `json:"options,omitempty"`
}

RetrieverRequest is the data we pass to retrieve documents from the database. The Options field is specific to the actual retriever implementation.

type RetrieverResponse

type RetrieverResponse struct {
	Documents []*Document `json:"documents"`
}

RetrieverResponse is the response to a document lookup.

type Role

type Role string

Role indicates which entity is responsible for the content of a message.

const (
	// RoleSystem indicates this message is user-independent context.
	RoleSystem Role = "system"
	// RoleUser indicates this message was generated by the client.
	RoleUser Role = "user"
	// RoleModel indicates this message was generated by the model during a previous interaction.
	RoleModel Role = "model"
	// RoleTool indicates this message was generated by a local tool, likely triggered by a request
	// from the model in one of its previous responses.
	RoleTool Role = "tool"
)

type Tool

type Tool struct {
	Definition *ToolDefinition
	Fn         func(context.Context, map[string]any) (map[string]any, error)
}

A Tool is an implementation of a single tool. The ToolDefinition has JSON schemas that describe the types. TODO: This should be generic over the function input and output types, and something in the general code should handle the JSON conversion.

type ToolDefinition

type ToolDefinition struct {
	Description string `json:"description,omitempty"`
	// Valid JSON Schema representing the input of the tool.
	InputSchema map[string]any `json:"inputSchema,omitempty"`
	Name        string         `json:"name,omitempty"`
	// Valid JSON Schema describing the output of the tool.
	OutputSchema map[string]any `json:"outputSchema,omitempty"`
}

A ToolDefinition describes a tool.

type ToolRequest

type ToolRequest struct {
	// Input is a JSON object describing the input values to the tool.
	// An example might be map[string]any{"country":"USA", "president":3}.
	Input map[string]any `json:"input,omitempty"`
	Name  string         `json:"name,omitempty"`
}

A ToolRequest is a message from the model to the client that it should run a specific tool and pass a ToolResponse to the model on the next chat request it makes. Any ToolRequest will correspond to some ToolDefinition previously sent by the client.

type ToolResponse

type ToolResponse struct {
	Name string `json:"name,omitempty"`
	// Output is a JSON object describing the results of running the tool.
	// An example might be map[string]any{"name":"Thomas Jefferson", "born":1743}.
	Output map[string]any `json:"output,omitempty"`
}

A ToolResponse is a message from the client to the model containing the results of running a specific tool on the arguments passed to the client by the model in a ToolRequest.

Jump to

Keyboard shortcuts

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