openai

package
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: Apache-2.0 Imports: 9 Imported by: 13

README

OpenAI Plugin

This plugin provides Genkit support for OpenAI chat models and embedders through the Chat Completions API.

Setup

Set an OpenAI API key:

export OPENAI_API_KEY=<your-api-key>
import (
    "context"

    "github.com/firebase/genkit/go/ai"
    "github.com/firebase/genkit/go/genkit"
    oai "github.com/firebase/genkit/go/plugins/compat_oai/openai"
)

ctx := context.Background()
plugin := &oai.OpenAI{}
g := genkit.Init(ctx,
    genkit.WithPlugins(plugin),
    genkit.WithDefaultModel("openai/gpt-5.4"),
)

response, err := genkit.Generate(ctx, g, ai.WithPrompt("Write a haiku about Go."))

Client options such as a different base URL or an organization ride the plugin's Opts (option.WithBaseURL, option.WithOrganization, and the rest of the SDK's request options).

Models

The plugin registers a curated catalog spanning the GPT-5 line (gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna, gpt-5.5, gpt-5.4, and earlier), the GPT-4 line, and the o-series reasoning models. The catalog is not a ceiling: any model ID the API serves resolves on demand, and the models the endpoint reports are listed dynamically. Use the Models field to describe or correct any model, most often one released after this plugin:

plugin := &oai.OpenAI{Models: map[string]ai.ModelOptions{
    "gpt-6": {Label: "GPT-6", Supports: &compat_oai.Multimodal},
}}

The current model list and capabilities are at https://developers.openai.com/api/docs/models.

Models served only by the Responses API (the -pro variants) are not part of this plugin, which speaks the Chat Completions API; naming one still resolves it and fails at request time.

Config

Models take the OpenAI SDK's own request type, openai.ChatCompletionNewParams, with the SDK's wire names. oai.ModelRef carries a config with the model ID:

import "github.com/openai/openai-go"

response, err := genkit.Generate(ctx, g,
    ai.WithModel(oai.ModelRef("gpt-5.4", &openai.ChatCompletionNewParams{
        Temperature:         openai.Float(0.2),
        MaxCompletionTokens: openai.Int(1024),
    })),
    ai.WithPrompt("Answer concisely."),
)

The GPT-5 generation rejects the legacy max_tokens, so cap output with MaxCompletionTokens; the older field remains for the models that still read it.

Set the config's Model to a dated snapshot to pin the exact version a request is served by. The fields Genkit builds from the request (messages, tools, and their variants) are not config: a config naming one is rejected.

The advertised schema is reflected from the openai-go version your build links, so a field OpenAI ships tomorrow becomes usable, and validated, by bumping github.com/openai/openai-go in your own go.mod.

Embedders

text-embedding-3-large, text-embedding-3-small, and text-embedding-ada-002 are registered, and the Embedders field overrides what the plugin knows the way Models does. Embedders take a typed oai.TextEmbeddingConfig:

res, err := genkit.Embed(ctx, g,
    ai.WithEmbedder(oai.NewEmbedderRef("text-embedding-3-small", &oai.TextEmbeddingConfig{
        Dimensions: 256,
    })),
    ai.WithTextDocs("Genkit is an AI framework."),
)

The embedding config also carries the settings Genkit owns: apiKey (settable only from Go code) serves one request with a different credential, and extra forwards request body fields the config does not declare, keyed by OpenAI's wire names.

Live tests

Live tests are skipped unless OPENAI_API_KEY is set:

go test -v ./plugins/compat_oai/openai

Documentation

Overview

Package openai provides a Genkit plugin for OpenAI's models and embedders.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ModelRef added in v1.12.0

func ModelRef(id string, config *openaiGo.ChatCompletionNewParams) ai.ModelRef

ModelRef names an OpenAI model and carries the config to generate with, so the config is typed at the call site instead of an any the model checks at runtime. The config is the OpenAI SDK's request params, the raw request the plugin sends; a nil config leaves the request's config unset.

ai.WithModel(openai.ModelRef("gpt-4o", &openaiGo.ChatCompletionNewParams{
	Temperature: openaiGo.Float(0.7),
}))

name is the model ID, with or without the provider prefix: "gpt-4o" and "openai/gpt-4o" name the same model, as they do everywhere else in this package.

func NewEmbedderRef added in v1.12.0

func NewEmbedderRef(id string, config *TextEmbeddingConfig) ai.EmbedderRef

NewEmbedderRef names an OpenAI embedder and carries the config to embed with, so the config is typed at the call site. A nil config leaves the request's options unset.

ai.WithEmbedder(openai.NewEmbedderRef("text-embedding-3-small", &openai.TextEmbeddingConfig{
	Dimensions: 256,
}))

id is the embedder ID, with or without the provider prefix.

Types

type EmbedderRef deprecated added in v0.7.0

type EmbedderRef struct {
	Name         string
	ConfigSchema TextEmbeddingConfig // Represents the schema, can be used for default config
	Label        string
	Supports     *ai.EmbedderSupports
	Dimensions   int
}

EmbedderRef describes an embedding model.

Deprecated: use NewEmbedderRef, which builds an ai.EmbedderRef naming an embedder and carrying its typed config, the form generation and embedding calls accept.

type OpenAI

type OpenAI struct {
	// APIKey is the API key for the OpenAI API. If empty, the values of the environment variable "OPENAI_API_KEY" will be consulted.
	// Request a key at https://platform.openai.com/api-keys
	APIKey string
	// Optional: Opts are additional options for the OpenAI client.
	// Can include other options like WithOrganization, WithBaseURL, etc.
	Opts []option.RequestOption

	// Models overrides what the plugin knows about an OpenAI model, keyed by
	// model ID, bare or provider-prefixed. Every OpenAI model already works
	// without an entry: known IDs carry curated capabilities and the rest take
	// the generic multimodal defaults. Supply an entry only to correct or
	// extend what the plugin resolves, most often for a model released after
	// this version of the plugin or served by a proxy that supports less than
	// OpenAI does.
	//
	//	&openai.OpenAI{Models: map[string]ai.ModelOptions{
	//		"gpt-4o": {Supports: &ai.ModelSupports{Multiturn: true, Tools: true}},
	//	}}
	//
	// Fields left at their zero value keep what the plugin resolves, so an
	// entry can pin one capability without restating the label or the
	// versions. Entries apply to the models Init registers as well as the ones
	// [OpenAI.ListActions] advertises and [OpenAI.ResolveAction] builds, which
	// is the way to describe a curated model differently: Init has already
	// registered those and nothing can re-register them.
	Models map[string]ai.ModelOptions

	// Embedders is [OpenAI.Models] for embedders, keyed by embedder ID.
	Embedders map[string]ai.EmbedderOptions
	// contains filtered or unexported fields
}

func (*OpenAI) DefineEmbedder deprecated

func (o *OpenAI) DefineEmbedder(id string, opts *ai.EmbedderOptions) ai.Embedder

DefineEmbedder builds an OpenAI embedder and returns it, without registering it.

Deprecated: describe the embedder through OpenAI.Embedders instead. Like OpenAI.DefineModel, the embedder this returns is not registered, so embedding by that name serves the request with the options the plugin resolves rather than the ones passed here.

func (*OpenAI) DefineModel deprecated

func (o *OpenAI) DefineModel(id string, opts ai.ModelOptions) ai.Model

DefineModel builds an OpenAI model and returns it, without registering it.

Deprecated: describe the model through OpenAI.Models instead. This method builds the model and registers nothing, so the result carries only the model's name: generation resolves a model from that name and serves the request with the capabilities the plugin resolves, not the ones passed here. An entry in Models reaches both paths.

func (*OpenAI) Embedder deprecated

func (o *OpenAI) Embedder(g *genkit.Genkit, id string) ai.Embedder

Embedder returns a previously registered embedder.

Deprecated: Embedding resolves an embedder from its name, so looking one up first is rarely necessary: pass ai.WithEmbedderName("openai/text-embedding-3-small") or, to carry config with it, EmbedderRef. Use genkit.LookupEmbedder when the action itself is what you need.

func (*OpenAI) Init

func (o *OpenAI) Init(ctx context.Context) []api.Action

Init implements genkit.Plugin.

func (*OpenAI) ListActions added in v0.6.1

func (o *OpenAI) ListActions(ctx context.Context) []api.ActionDesc

ListActions lists the models the configured OpenAI endpoint exposes, described by the SDK config schema and the capabilities the plugin resolves for each ID, a caller's OpenAI.Models entry included.

func (*OpenAI) Model deprecated

func (o *OpenAI) Model(g *genkit.Genkit, id string) ai.Model

Model returns a previously registered model.

Deprecated: Generation resolves a model from its name, so looking one up first is rarely necessary: pass ai.WithModelName("openai/gpt-4o") or, to carry config with it, ModelRef. Use genkit.LookupModel when the action itself is what you need.

func (*OpenAI) Name

func (o *OpenAI) Name() string

Name implements genkit.Plugin.

func (*OpenAI) ResolveAction added in v0.6.1

func (o *OpenAI) ResolveAction(atype api.ActionType, id string) api.Action

ResolveAction dynamically builds a model the OpenAI endpoint exposes, described the same way OpenAI.ListActions describes it.

type TextEmbeddingConfig added in v0.7.0

type TextEmbeddingConfig = compat_oai.EmbeddingConfig

TextEmbeddingConfig is the per-request config for OpenAI embedders.

It is an alias for compat_oai.EmbeddingConfig, the config every plugin in this family embeds with, which carries two fields beyond the Dimensions and EncodingFormat this type had through v1.11.0: a per-request APIKey override and a User identifier. Dimensions and EncodingFormat keep their names, types, order, and JSON tags, so keyed literals and the wire format are unchanged. An unkeyed literal (TextEmbeddingConfig{256, "float"}) no longer compiles, since Go requires one value per field; go vet's composites check flags those already.

Jump to

Keyboard shortcuts

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