Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 73 additions & 3 deletions go/MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -889,14 +889,84 @@ A background model sets the error with `status.Errorf`:
op.Error = status.Errorf(status.ErrUnavailable, "render failed: %s", msg)
```

## HTTP serving moves to `genkithttp` and `genkithttp/exp`

The HTTP action handlers, server helper, route builders, and custom context
providers are replaced by two framework-agnostic `net/http` packages:

- `github.com/genkit-ai/genkit-go/v2/genkithttp` (`package genkithttp`) for
serving actions, routing (`Mux`, `HandleAction`), CORS middleware (`CORS`),
graceful standalone serving (`ListenAndServe`), and low-level wire helpers
(`WriteError`, `WriteResult`, `DecodeRequest`, `WantsStream`, `SSEWriter`).
- `github.com/genkit-ai/genkit-go/v2/genkithttp/exp` (`package exp`, commonly
aliased `genkithttpx`) for mounting experimental agents and their snapshot
companion routes (`HandleAgent`).

| v1 / earlier v2 | v2 (`genkithttp`) |
| --- | --- |
| `genkit.Handler(a, opts...)` | `genkithttp.NewHandler(a, opts...)` |
| `genkit.HandlerFunc(a, opts...)` | Removed; use `genkithttp.NewHandler` with `WithOnError` / `WithErrorEncoder` |
| `genkit.WithStreamManager(sm)` | `genkithttp.WithStreamManager(sm)` |
| `server.Start(ctx, addr, mux)` (`plugins/server`) | `genkithttp.ListenAndServe(ctx, addr, handler, opts...)` |
| `genkitx.AgentRoutes`, `AllAgentRoutes`, `FlowRoutes`, `AllFlowRoutes`, `Route` | `genkithttp.NewMux`, `genkithttp.HandleAction`, `genkithttpx.HandleAgent`, `(*genkithttp.Mux).Routes` |
| `genkit.WithContextProviders`, `core.ContextProvider`, `core.RequestData` | Standard `net/http` middleware setting values on `r.Context()` + `genkithttp.WriteError` + `genkit.NewContextKey[T]` |
| `firebase.ContextProvider(ctx, g, policy)` | `firebase.AuthMiddleware(ctx, g, policy)` + `firebase.AuthKey` |

**Before:**

```go
mux := http.NewServeMux()
mux.HandleFunc("POST /story", genkit.Handler(storyFlow,
genkit.WithContextProviders(authProvider),
))
for _, r := range genkitx.AllAgentRoutes(g) {
mux.HandleFunc(r.Pattern(), r.Handler())
}
log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux))
```

**After:**

```go
var userKey = genkit.NewContextKey[User]("auth")

func requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := verifyToken(r.Context(), r.Header.Get("Authorization"))
if err != nil {
genkithttp.WriteError(w, status.PublicErrorf(status.ErrUnauthenticated, "sign in required"))
return
}
next.ServeHTTP(w, r.WithContext(userKey.WithValue(r.Context(), user)))
})
}

api := genkithttp.NewMux()
genkithttp.HandleAction(api, storyFlow)
genkithttpx.HandleAgent(api, chatAgent)

mux := http.NewServeMux()
mux.Handle("/api/", http.StripPrefix("/api", requireAuth(api)))

handler := genkithttp.CORS(genkithttp.CORSOptions{
AllowedOrigins: []string{"https://myapp.dev"},
})(mux)
log.Fatal(genkithttp.ListenAndServe(ctx, "", handler))
```

`genkit.NewContextKey[T](name)` reads typed values set by HTTP middleware via
`WithValue` with zero JSON overhead, and falls back to decoding `name` from
`core.FromContext(ctx)` when flows run through the Dev UI or CLI `--context`.
Plain Go `context.WithValue` continues to work natively.

## Smaller changes

- **`api.Registry` is sealed.** Only Genkit implements it, so Genkit can add
a method to it in a minor release. A test that needs a registry calls
`genkit.Init`.
- **`WithPlugins` and `WithContextProviders` accumulate.** A second option
adds to the first instead of making `genkit.Init` return an error or
`genkit.Handler` panic, so a helper can extend a base option list.
- **`WithPlugins` accumulates.** A second `genkit.WithPlugins` option adds to
the first instead of making `genkit.Init` return an error, so a helper can
extend a base option list.
- **A nil model or embedder sets nothing.** `ai.WithModel` and
`ai.WithEmbedder` ignore the nil `*ai.Model`, `*ai.BackgroundModel`, or
`*ai.Embedder` of a lookup that found nothing. It no longer replaces a model
Expand Down
16 changes: 7 additions & 9 deletions go/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,18 +374,16 @@ chatAgent := genkitx.DefineAgent(g, "chat",

### Serve Agents over HTTP

`AllAgentRoutes` serves every agent, one turn per request:
`genkithttpx.HandleAgent` mounts an agent and its companion routes on a `genkithttp.Mux`:

```go
mux := http.NewServeMux()
for _, r := range genkitx.AllAgentRoutes(g) {
mux.HandleFunc(r.Pattern(), r.Handler())
}
api := genkithttp.NewMux(genkithttp.WithBasePath("/agents"))
genkithttpx.HandleAgent(api, chatAgent)
// POST /agents/chat one turn (?stream=true for SSE)
// POST /agents/chat/getSnapshot read a snapshot
// POST /agents/chat/waitForSnapshot wait for a snapshot to settle
// POST /agents/chat/abort abort background work
if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil {
if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", api); err != nil {
log.Fatal(err)
}
```
Expand Down Expand Up @@ -737,15 +735,15 @@ storyFlow := genkit.DefineStreamingFlow(g, "story",
)

mux := http.NewServeMux()
mux.HandleFunc("POST /story", genkit.Handler(storyFlow))
log.Fatal(http.ListenAndServe(":8080", mux))
mux.Handle("POST /story", genkithttp.NewHandler(storyFlow))
log.Fatal(genkithttp.ListenAndServe(ctx, ":8080", mux))
```

```bash
curl -N "http://localhost:8080/story?stream=true" -d '{"data": "a robot who paints"}'
```

`genkit.Handler` returns a standard `http.HandlerFunc`, so it works with Gin, Echo, Chi, or any router. [`genkit.WithStreamManager`](https://genkit.dev/docs/go/durable-streaming/) lets clients reconnect to a stream *(preview)*.
`genkithttp.NewHandler` and `genkithttp.Mux` implement `http.Handler`, so they work with `net/http`, Chi, Gin, Echo, or any router. [`genkithttp.WithStreamManager`](https://genkit.dev/docs/go/durable-streaming/) lets clients reconnect to a stream *(preview)*.

[Docs](https://genkit.dev/docs/go/flows/) · [Example](samples/basic/main.go) · [Durable streaming example](samples/basic-durable-streaming-exp/main.go)

Expand Down
25 changes: 14 additions & 11 deletions go/ai/exp/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -795,7 +795,8 @@ type AgentFunc[State any] = func(ctx context.Context, resp Responder, sess *Sess
// Agent is a bidirectional streaming agent with automatic snapshot management.
//
// Agent implements [api.BidiAction], so generic transports accept it directly
// (e.g. pass it to genkit.Handler to serve it over HTTP, one turn per request).
// (e.g. mount it with genkithttpx.HandleAgent or genkithttp.NewHandler to serve
// it over HTTP, one turn per request).
// [Agent.Run], [Agent.RunText], and [Agent.Connect] are typed conveniences
// over the same underlying action.
//
Expand Down Expand Up @@ -836,9 +837,10 @@ func (a *Agent[State]) Name() string {
// client-managed (no [SessionStore] configured): there is no server-side
// snapshot to fetch.
//
// Use it to expose snapshot polling over a transport (e.g. mount it with
// genkit.Handler next to the agent itself); local Go code should use
// [Agent.GetSnapshot], which applies the configured state transform.
// Use it to expose snapshot polling over a transport (e.g. via
// genkithttpx.HandleAgent or genkithttp.NewHandler next to the agent itself);
// local Go code should use [Agent.GetSnapshot], which applies the configured
// state transform.
func (a *Agent[State]) GetSnapshotAction() api.Action {
return a.getSnapshot
}
Expand All @@ -851,10 +853,11 @@ func (a *Agent[State]) GetSnapshotAction() api.Action {
// until it settles. It returns nil when the agent is client-managed (no
// [SessionStore] configured).
//
// Use it to expose following a detached invocation over a transport (e.g.
// mount it with genkit.Handler next to the agent itself), so a remote caller
// waits in one request instead of a read per tick; local Go code should use
// [Agent.WaitForSnapshot], which applies the configured state transform.
// Use it to expose following a detached invocation over a transport (e.g. via
// genkithttpx.HandleAgent or genkithttp.NewHandler next to the agent itself),
// so a remote caller waits in one request instead of a read per tick; local Go
// code should use [Agent.WaitForSnapshot], which applies the configured state
// transform.
func (a *Agent[State]) WaitForSnapshotAction() api.Action {
return a.wait
}
Expand All @@ -865,8 +868,8 @@ func (a *Agent[State]) WaitForSnapshotAction() api.Action {
// [AgentAbortResponse]). It returns nil when the agent has no
// [SessionStore] or the store does not implement [SnapshotSubscriber].
//
// Use it to expose aborting over a transport (e.g. mount it with
// genkit.Handler next to the agent itself); local Go code aborts with
// Use it to expose aborting over a transport (e.g. via genkithttpx.HandleAgent
// or genkithttp.NewHandler next to the agent itself); local Go code aborts with
// [Agent.Abort]; a store-only caller uses this companion action.
func (a *Agent[State]) AbortAction() api.Action {
return a.abort
Expand Down Expand Up @@ -1256,7 +1259,7 @@ func newCustomAgent[State any](
ctx = cfg.contextFunc(ctx)
}
// A transport serving this agent to a client marks ctx (see
// genkit.Handler); the output it returns then keeps internal
// genkithttp.NewHandler); the output it returns then keeps internal
// error text off the wire.
served := wire.ServesAction(ctx, key)
rt, err := newAgentRuntime(ctx, name, cfg, in, inCh, outCh)
Expand Down
4 changes: 2 additions & 2 deletions go/ai/exp/handle.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ type AgentHandle struct {
// refusal an agent that lacks a capability earns. Build a handle over one
// with [NewAgentHandle].
//
// The methods mirror the agent's served routes (see the genkitx package's
// AgentRoutes) and take the wire types, so a field added to a request reaches
// The methods mirror the agent's served routes (see genkithttp/exp's
// HandleAgent) and take the wire types, so a field added to a request reaches
// every transport without a new method. Snapshot operations live in the
// optional [SnapshotTransport].
//
Expand Down
10 changes: 5 additions & 5 deletions go/ai/exp/remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func WithAgentMetadata(meta *AgentMetadata) RemoteAgentOption {
// --- NewRemoteAgent ---

// NewRemoteAgent returns a handle to an agent that a Genkit app serves over
// HTTP, in Go (the genkitx package's AgentRoutes layout), JS, or Dart. url
// HTTP, in Go (via genkithttp/exp.HandleAgent), JS, or Dart. url
// is the agent's turn route (e.g. "https://billing.internal/agents/billing");
// the snapshot companions are at url+"/getSnapshot", url+"/waitForSnapshot",
// and url+"/abort", unless [WithRouteURLs] puts them elsewhere. It performs no
Expand Down Expand Up @@ -228,7 +228,7 @@ const (
)

// httpTransport reaches an agent that a Genkit app serves over HTTP, through
// the routes of the genkitx package's AgentRoutes layout, speaking the
// the routes mounted by genkithttp/exp.HandleAgent, speaking the
// wire format in internal/wire.
type httpTransport struct {
name string
Expand Down Expand Up @@ -558,9 +558,9 @@ func olderGenkitError(mediaType string, body []byte) bool {
// to the agent through the handle's transport. Such an agent action runs the
// inputs of an invocation one after another, each as its own turn on the
// transport, and carries the session from one turn to the next; a detach
// applies to the input that carries it. Serving layouts that list every agent
// (the genkitx package's AllAgentRoutes) skip it, so a server does not
// expose another service's agent with its own credentials.
// applies to the input that carries it. The descriptor carries
// [wire.RemoteAgentMetadataKey] so tooling can distinguish remote proxies from
// locally defined agents.
//
// Like every registration, it panics if r already holds an agent by the same
// name.
Expand Down
30 changes: 30 additions & 0 deletions go/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

package genkit

import "github.com/genkit-ai/genkit-go/v2/core"

// ContextKey is a typed key for storing and retrieving request-scoped values in
// a [context.Context], with fallback to Dev UI / CLI (--context) and Dotprompt
// [core.ActionContext] entries.
type ContextKey[T any] = core.ContextKey[T]

// NewContextKey returns a new typed [ContextKey] associated with name for Dev
// UI (--context) and Dotprompt interoperability.
func NewContextKey[T any](name string) ContextKey[T] {
return core.NewContextKey[T](name)
}
90 changes: 80 additions & 10 deletions go/core/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,87 @@ func FromContext(ctx context.Context) ActionContext {
return val.(ActionContext)
}

// ActionContext is the runtime context for an Action.
// ActionContext is the runtime context for an Action, populated by the
// reflection server (Dev UI / CLI --context) and Dotprompt rendering.
type ActionContext = map[string]any

// RequestData is the data associated with a request.
// It is used to provide additional context to the Action.
type RequestData struct {
Method string // Method is the HTTP method of the request (e.g. "GET", "POST", etc.)
Headers map[string]string // Headers is the headers of the request. The keys are the header names in lowercase.
Input json.RawMessage // Input is the body of the request.
// contextKeyToken is a unique unexported non-zero-sized allocation identifying
// a [ContextKey]. It must have non-zero size so Go allocates distinct addresses
// for every [NewContextKey] call rather than reusing runtime.zerobase.
type contextKeyToken struct {
_ byte
}

// ContextProvider is a function that returns an ActionContext for a given request.
// It is used to provide additional context to the Action.
type ContextProvider = func(ctx context.Context, req RequestData) (ActionContext, error)
// contextKeyValue wraps a typed value stored in a [context.Context] so that a
// stored nil interface value is distinguishable from an absent key.
type contextKeyValue[T any] struct {
val T
}

// ContextKey is a typed key for storing and retrieving request-scoped values in
// a [context.Context], with an automatic fallback to [FromContext] (the Dev UI /
// CLI --context map) for seamless local development and Dotprompt
// interoperability.
//
// Construct keys once at package level with [NewContextKey].
type ContextKey[T any] struct {
name string
key *contextKeyToken
}

// NewContextKey returns a unique typed [ContextKey] associated with name.
// When [ContextKey.FromContext] does not find a value stored via
// [ContextKey.WithValue] and name is non-empty, it falls back to looking up
// name in [FromContext] and JSON-unmarshaling the entry into T.
func NewContextKey[T any](name string) ContextKey[T] {
return ContextKey[T]{
name: name,
key: new(contextKeyToken),
}
}

// Name returns the fallback key name used for [ActionContext] lookups.
func (k ContextKey[T]) Name() string {
return k.name
}

// WithValue attaches val to ctx under this typed key with zero JSON overhead.
// Panics if k was not constructed with [NewContextKey].
func (k ContextKey[T]) WithValue(ctx context.Context, val T) context.Context {
if k.key == nil {
panic("core.ContextKey.WithValue: zero ContextKey; construct with NewContextKey")
}
return context.WithValue(ctx, k.key, contextKeyValue[T]{val: val})
}
Comment on lines +88 to +93

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] ContextKey.WithValue only writes under k.key, whereas Dotprompt rendering (renderDotpromptToMessages in go/ai/prompt.go) reads only core.FromContext(ctx). Because firebase.AuthMiddleware now stores the verified token via AuthKey.WithValue instead of populating core.ActionContext, Dotprompt templates accessing the auth context key (or any other named ContextKey) over HTTP will no longer see those values, contradicting the Dotprompt interoperability documented on ContextKey and genkit.NewContextKey.

If named ContextKey values are meant to be visible to Dotprompt templates, consider attaching a lightweight immutable (name, val) chain in WithValue when k.name != "" and merging it in renderDotpromptToMessages (keeping ContextKey.FromContext isolated between distinct keys with the same name). Otherwise, clarify the one-way Dev UI fallback in the docs and keep AuthMiddleware populating ActionContext if Dotprompt template access is required.


// FromContext retrieves the typed value associated with k from ctx.
//
// Lookup order:
// 1. Fast path: a typed value stored via [ContextKey.WithValue].
// 2. Dev/reflection fallback: if [FromContext] contains k.name, returns it
// directly when already of type T, or JSON-roundtrips it into T.
func (k ContextKey[T]) FromContext(ctx context.Context) (T, bool) {
if k.key != nil {
if v, ok := ctx.Value(k.key).(contextKeyValue[T]); ok {
return v.val, true
}
}
if k.name != "" {
if actionCtx := FromContext(ctx); actionCtx != nil {
if raw, exists := actionCtx[k.name]; exists {
if v, ok := raw.(T); ok {
return v, true
}
b, err := json.Marshal(raw)
if err == nil {
var v T
if err := json.Unmarshal(b, &v); err == nil {
return v, true
}
}
}
}
}
var zero T
return zero, false
}
Loading
Loading