agui

package
v2.22.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agui serves PromptKit conversations over the AG-UI protocol (1.0), using the AG-UI community Go SDK's types. It provides bidirectional converters between PromptKit and AG-UI messages and tools, and an EventAdapter that turns one conversation turn into one AG-UI run.

Text streams as the model writes it for a conversation that streams (*sdk.Conversation); a workflow conversation's text arrives in one TEXT_MESSAGE_CONTENT per message. A run also carries the model's reasoning (REASONING_* events), the state's changes (STATE_DELTA), its token usage and the frontend tool calls it left unanswered (pendingToolCallIds) on RUN_FINISHED, and, with WithMessagesSnapshot, a MESSAGES_SNAPSHOT. Not produced: RUN_STARTED's protocolVersion, which the Go SDK cannot encode, REASONING_ENCRYPTED_VALUE, and activity and subagent events. A message's id is its stable id (types.MetaMessageID), so it is the same in every run; a message stored before ids were assigned gets a new id per conversion.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrContinueUnsupported = errors.New("agui: conversation does not support Continue")

ErrContinueUnsupported is returned by EventAdapter.RunContinue when the conversation cannot continue after an approval hold.

Functions

func MessageFromAGUI

func MessageFromAGUI(msg *aguitypes.Message) types.Message

MessageFromAGUI converts an AG-UI Message to a PromptKit Message. It maps roles, content (text or multimodal), tool calls, and tool call IDs. The developer role becomes system, and an unrecognized role becomes user.

A reasoning message becomes an assistant message whose Reasoning holds the text, never user input. MessagesFromAGUI folds it into the assistant message that follows it instead.

The message's AG-UI id becomes its stable id (types.MetaMessageID), which the conversation stores it under, so MessageToAGUI and MESSAGES_SNAPSHOT give it back under the id the client gave it.

Example

ExampleMessageFromAGUI converts an AG-UI Message back to a PromptKit Message, the inverse of agui.MessageToAGUI.

package main

import (
	"fmt"

	aguitypes "github.com/ag-ui-protocol/ag-ui/sdks/community/go/pkg/core/types"

	"github.com/AltairaLabs/PromptKit/sdk/v2/agui"
)

func main() {
	aguiMsg := &aguitypes.Message{
		Role:    aguitypes.RoleAssistant,
		Content: "Hi there!",
	}
	msg := agui.MessageFromAGUI(aguiMsg)
	fmt.Println(msg.Role, "->", msg.GetContent())
}
Output:
assistant -> Hi there!

func MessageToAGUI

func MessageToAGUI(msg *types.Message) aguitypes.Message

MessageToAGUI converts a PromptKit Message to an AG-UI Message. It maps roles, content, tool calls, and tool results.

User and tool messages carry content parts (text, image, audio, video, document) when they hold media; assistant and system content is text, as AG-UI 1.0 defines it. A media part whose bytes are neither inline nor at a URL (a local file path or a storage reference) has no AG-UI form and is dropped with a warning.

The id is the message's stable id (types.MetaMessageID), which the conversation gives each message it stores, so converting a stored message gives the same id every time. A message with none (one stored before ids were assigned, or one not stored yet) gets a new id on each conversion. A user message RunSend sent with WithInputContext is given back without the context block it opened with.

Example

ExampleMessageToAGUI converts a PromptKit Message to the AG-UI wire format used by AG-UI-compatible frontends.

package main

import (
	"fmt"

	"github.com/AltairaLabs/PromptKit/runtime/v2/types"
	"github.com/AltairaLabs/PromptKit/sdk/v2/agui"
)

func main() {
	msg := types.NewTextMessage("user", "Hello!")
	aguiMsg := agui.MessageToAGUI(&msg)
	fmt.Println(aguiMsg.Role, "->", aguiMsg.Content)
}
Output:
user -> Hello!

func MessagesFromAGUI

func MessagesFromAGUI(msgs []aguitypes.Message) []types.Message

MessagesFromAGUI converts a slice of AG-UI Messages to PromptKit Messages. A tool message's result takes the name of the assistant tool call with the same ID; MessageFromAGUI alone cannot know it and leaves the name empty.

A reasoning message is attached to the assistant message that follows it, as that message's Reasoning; with no assistant message after it, it is dropped. Activity messages are UI material that AG-UI says never travels back to the agent, and are dropped too.

func MessagesToAGUI

func MessagesToAGUI(msgs []types.Message) []aguitypes.Message

MessagesToAGUI converts a slice of PromptKit Messages to AG-UI Messages.

func ToolsFromAGUI

func ToolsFromAGUI(aguiTools []aguitypes.Tool) []*tools.ToolDescriptor

ToolsFromAGUI converts a slice of AG-UI Tool definitions to PromptKit ToolDescriptors. Each tool's Parameters (JSON Schema as any) is marshaled to json.RawMessage for InputSchema.

The tools in RunAgentInput.tools are the application's own, executed by the application, so each descriptor has Mode "client": a call to one suspends the turn until the application answers it.

func ToolsToAGUI

func ToolsToAGUI(descs []tools.ToolDescriptor) []aguitypes.Tool

ToolsToAGUI converts a slice of PromptKit ToolDescriptors to AG-UI Tool definitions.

Types

type AdapterOption

type AdapterOption func(*adapterConfig)

AdapterOption configures an EventAdapter.

func WithClientHistory added in v2.22.0

func WithClientHistory(history []aguitypes.Message) AdapterOption

WithClientHistory sets the history the run's new message follows, as the client holds it: RunSend replaces the conversation's history with it before sending its message. Pass RunAgentInput.messages without the last message, the new one RunSend sends. By default (and with a nil history) the conversation keeps its own history and the client's is not read.

AG-UI has the client send the whole history with each run. Honoring it is a trust decision for the host: the client then decides what the model is told the user, the assistant and each tool said, including replies the model never gave. Set it only for a client entitled to edit its conversation. Even then, its system and developer messages are dropped, never sent: the pack's system prompt stays the only system instruction. Its reasoning messages are dropped too, so reasoning the conversation did not produce is never replayed to the provider.

The conversation's own copy of a message wins over the client's (see sdk.Conversation.ReplaceHistory). A client message is taken as stored, with its metadata, its provider's tool-call metadata and its media, when it carries a stored message's id (each run streams its messages under the ids it stores them under, so a client that keeps them holds those ids), when it repeats the stored history verbatim from its start, or when it is the same message, word for word, as one the conversation keeps out of model context. An edit under a stored id is ignored: the stored copy is what the model gets. A turn an input guardrail blocked and an interrupted reply echoed under their ids, or verbatim, stay out of model context in any order, and take out nothing the client put next to them. A message the conversation does not hold, an edited text included, is new and the client's to write: input guardrails judge only the run's new message, never one the client adds to its history.

New messages keep their AG-UI ids (types.MetaMessageID), so a MESSAGES_SNAPSHOT names them as the client does. A history the conversation refuses (a tool result answering no call, a call left without a result, a history over the size limits) fails the run with RUN_ERROR, before the model is called. The history is replaced inside the run's turn (sdk.WithHistory), so no other turn on the conversation runs between the replacement and the turn. It needs an *sdk.Conversation; for any other conversation, RunSend fails. RunResume and RunContinue continue the turn the conversation suspended and do not read it.

func WithFrontendTools added in v2.22.0

func WithFrontendTools(frontend []aguitypes.Tool) AdapterOption

WithFrontendTools sets the RunAgentInput.tools RunSend offers the model, for the turn it starts, as client tools: a call to one ends the run with the call pending (pendingToolCallIds on RUN_FINISHED) for the application to execute and answer in the next run (RunResume). By default, and with no tools, only the tools the pack's prompt declares are offered.

The model sees each tool's name, description and parameters as the client sent them. A tool named like a tool the conversation already has (one the pack declares, a host or MCP tool, or a capability tool such as skill__ or workflow__) is refused: the run fails with RUN_ERROR before the model is called, so a client cannot shadow a server tool. To let the application execute a client tool the pack declares, bind it with sdk.Conversation.DeferClientTool and leave it out of these tools.

The tools are the turn's own (sdk.WithClientTools): a RunResume or RunContinue of the turn offers them still, whatever its own options, and the next RunSend offers its own input's tools, so pass the option on every RunSend of the thread. Two runs on one conversation never offer each other's tools. Each tool is registered on the conversation's own tool registry, never on a shared host registry, and a call's arguments are checked against the client's schema. A ToolResultProvider is never asked to answer a call to one of them. It needs an *sdk.Conversation; for any other conversation, RunSend fails.

func WithInputContext added in v2.22.0

func WithInputContext(entries []aguitypes.Context) AdapterOption

WithInputContext sets the RunAgentInput.context entries RunSend gives the model with its message. By default the context is not read.

The entries open the user's message, as one text block: a line saying the block is the application's context and not an instruction, then the entries as a JSON array of {"description", "value"} objects between <context> and </context>. JSON encoding escapes "<" and ">", so a value cannot close the block early. The context is part of the user's turn, never of the system prompt: the client supplies it, and it carries no more authority than the user's own words. Everything that reads the user's message reads the block as part of it: input guardrails, evals, skill and tool selectors, memory extraction, retrieval, and the message size limit. The block is stored with the message, so later turns see the context the message was sent with; MessageToAGUI and MESSAGES_SNAPSHOT give the message back without it. No entries, or a run other than RunSend, adds nothing.

func WithMessagesSnapshot added in v2.22.0

func WithMessagesSnapshot(enabled bool) AdapterOption

WithMessagesSnapshot sets whether each run ends with a MESSAGES_SNAPSHOT, immediately before RUN_FINISHED, restating the conversation's history as the agent holds it: for a client reconnecting to the thread, or one whose copy has drifted from the agent's. Off by default.

The client replaces its messages with the snapshot's. Each message is keyed by its stable id (types.MetaMessageID), which a later run's snapshot gives it again: the id the client gave it, for a message that came from the client, or the one the conversation gave it when storing it. A message stored before ids were assigned is keyed by the thread id and its position in the history ("<thread>-0", "<thread>-1", ...), stable across runs only when the thread id is: set it with WithThreadID from the input's threadId. The messages the run streamed under ids of their own are replaced too. The history keeps no reasoning: with WithReasoning on, the snapshot restates the reasoning of the run's own turns, as reasoning messages before the assistant messages they led to, which AG-UI reads as the complete set of reasoning messages. A run whose history reads back empty, or shorter than the run's own turn (a store that failed or does not keep it), sends no snapshot rather than one that would clear the client. It needs a conversation that exposes its history (*sdk.Conversation does); for any other the option does nothing.

func WithReasoning added in v2.22.0

func WithReasoning(enabled bool) AdapterOption

WithReasoning sets whether the run sends the model's reasoning as AG-UI REASONING_* events, for a provider configured to return its reasoning (a Claude thinking budget, Gemini's include_thoughts, OpenAI's reasoning_summary). Off by default: reasoning routinely holds what the model chose not to say, so the client gets it only when asked for. With it off, reasoning is also left out of the RAW events WithRuntimeEvents forwards; with it on, those carry the reasoning's text but never its opaque tokens.

Only the reasoning's text is sent. A reply an output guardrail blocks keeps no reasoning, so a settled reply never sends the reasoning behind it. But reasoning that streams (sdk.WithStreamReasoning) goes out as the model produces it, before the output guardrails judge the reply it leads to: enable streamed reasoning only for a client that may see what a guardrail would block.

func WithRunID

func WithRunID(id string) AdapterOption

WithRunID sets the AG-UI run ID for emitted events. By default the adapter generates one.

func WithRuntimeEvents added in v2.17.0

func WithRuntimeEvents(eventTypes ...events.EventType) AdapterOption

WithRuntimeEvents forwards the conversation's runtime events, read from its event bus (EventBusProvider), as AG-UI RAW events with source "promptkit" and the [events.Event] as the payload. Name event types to forward only those (for example events.EventToolCallStarted); with none, every event is forwarded. By default no runtime event is forwarded.

The bus delivers asynchronously, so a RAW event is not ordered against the run's other events, and only events delivered while the run is open are forwarded: one the bus delivers after the run's RUN_FINISHED or RUN_ERROR is not sent. For a workflow conversation the bus is the active conversation's when the run starts. A bus shared by several conversations (sdk.WithEventBus) carries all of their events; filter on the payload's SessionID or ConversationID to keep one conversation's.

func WithStateAfterEachTool added in v2.22.0

func WithStateAfterEachTool(enabled bool) AdapterOption

WithStateAfterEachTool sets whether the run also reads the StateProvider after each TOOL_CALL_RESULT, sending the change a tool made as it lands rather than when the turn ends. Off by default.

The turn is still running then: its next tool calls can be executing, so Snapshot is called concurrently with the tools that change the state, and must be safe for that (guard the state with a lock the tools take too).

func WithStateProvider

func WithStateProvider(sp StateProvider) AdapterOption

WithStateProvider sets a provider of the state the run keeps in sync with the client. The run sends the state as a STATE_SNAPSHOT at its start, and reads it again once the turn has run, before RUN_FINISHED, sending the change as a STATE_DELTA: an RFC 6902 JSON Patch against the state the client holds. A change a patch cannot carry (one replacing the whole state, or setting a value to null, which the AG-UI Go SDK cannot encode) is sent as a new STATE_SNAPSHOT. Snapshot is never called while the turn runs; see WithStateAfterEachTool to send changes as each tool's result arrives.

func WithThreadID

func WithThreadID(id string) AdapterOption

WithThreadID sets the AG-UI thread ID for emitted events. By default the adapter generates one.

func WithToolResultProvider

func WithToolResultProvider(provider ToolResultProvider) AdapterOption

WithToolResultProvider sets a callback that answers pending client tools on the server, inside the run. When the callback answers every pending call, the adapter resolves them, emits a TOOL_CALL_RESULT for each, and resumes the turn. Calls it leaves unanswered stay pending: the run finishes with them unanswered, as AG-UI requires for a frontend tool, and the application answers them in the next run (see EventAdapter.RunResume). The answers it gave are reported before the run finishes; when the conversation has a ToolResultRewriter, each is reported as the model will be given it, rewritten.

Use it only for tools the server itself can answer. A frontend tool, one the application advertised in RunAgentInput.tools, must not be answered by the producer: a call to a tool listed in WithFrontendTools is never handed to the callback, and the run ends with it pending.

func WithWorkflowSteps

func WithWorkflowSteps(enabled bool) AdapterOption

WithWorkflowSteps enables STEP_STARTED / STEP_FINISHED events naming the workflow state a run executes in. It has an effect only when the conversation runs a workflow, as one passed to NewWorkflowEventAdapter does; NewWorkflowEventAdapter enables it by default.

type EventAdapter

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

EventAdapter bridges a PromptKit conversation to an AG-UI event channel. It runs one conversation turn and translates the turn's messages into AG-UI protocol events. An adapter carries one run: its channel closes when the run ends.

func NewEventAdapter

func NewEventAdapter(conv interface {
	Sender
	EventBusProvider
}, opts ...AdapterOption,
) *EventAdapter

NewEventAdapter creates a new EventAdapter for the given conversation. The conversation must implement both Sender and EventBusProvider. *sdk.Conversation satisfies both interfaces.

func NewWorkflowEventAdapter added in v2.11.0

func NewWorkflowEventAdapter(wc *sdk.WorkflowConversation, opts ...AdapterOption) *EventAdapter

NewWorkflowEventAdapter creates an EventAdapter for a workflow conversation. Each run opens a step named after the workflow state it executes in, and a transition the turn commits finishes that step and starts the next. Pass WithWorkflowSteps(false) to leave the steps out.

Client-tool results and approval resolutions go to the workflow's active conversation, the one serving the current state.

func (*EventAdapter) Events

func (a *EventAdapter) Events() <-chan aguievents.Event

Events returns the read-only channel of AG-UI events. The channel is closed when the run ends, successfully or with an error.

Drain it concurrently with RunSend, RunResume or RunContinue, for example from another goroutine. The adapter never drops an event. When the channel's buffer is full it waits for the reader, so a reader that stops reading holds the run until the run's context is canceled; cancel it (an HTTP handler's request context is canceled when the client disconnects) to release the run.

func (*EventAdapter) RunContinue added in v2.11.0

func (a *EventAdapter) RunContinue(ctx context.Context) error

RunContinue continues a turn whose approval-held tool calls were resolved (sdk.Conversation.ResolveTool / RejectTool) and emits it as a new run.

Read Events() concurrently with the run, or cancel ctx: the run waits for the reader once the channel's buffer of 64 events is full, so a caller that lets the run finish before reading blocks there.

The held calls' results are emitted as TOOL_CALL_RESULT events, since only the agent knows them.

It returns ErrContinueUnsupported (after a RUN_ERROR) when the conversation has no Continue method.

func (*EventAdapter) RunID

func (a *EventAdapter) RunID() string

RunID returns the run ID used by this adapter.

func (*EventAdapter) RunResume added in v2.11.0

func (a *EventAdapter) RunResume(ctx context.Context, results []ToolResult) error

RunResume answers the client tool calls a previous run left pending and emits the continued turn as a new run.

Read Events() concurrently with the run, or cancel ctx: the run waits for the reader once the channel's buffer of 64 events is full, so a caller that lets the run finish before reading blocks there.

In AG-UI the application answers a frontend tool call in the next run's input, as a tool message per call; ToolResultsFromAGUI extracts them. The answers are the application's own, so the run does not echo them back as TOOL_CALL_RESULT events. Nor does it repeat answers a ToolResultProvider gave in the earlier run, which reported them then: the resumed turn feeds every answer to the model, but none of them is new to the client.

A conversation that streams a resumed turn (sdk.Conversation.ResumeStream) sends it as RunSend sends a streamed turn.

func (*EventAdapter) RunSend

func (a *EventAdapter) RunSend(ctx context.Context, msg *types.Message) error

RunSend sends a message through the conversation and emits the run's AG-UI events.

Event sequence on success:

  1. RUN_STARTED
  2. STATE_SNAPSHOT (if a StateProvider is configured)
  3. STEP_STARTED for the current workflow state (workflow conversations)
  4. For each round of the turn (an assistant message and the tool results after it), in order: with WithReasoning(true), the round's reasoning (REASONING_START, REASONING_MESSAGE_START, a REASONING_MESSAGE_CONTENT for each chunk, REASONING_MESSAGE_END, REASONING_END) as the model streams it; TEXT_MESSAGE_START, a TEXT_MESSAGE_CONTENT for each chunk of text as the model streams it, TEXT_MESSAGE_END; then TOOL_CALL_START / TOOL_CALL_ARGS / TOOL_CALL_END for each call it made; then a TOOL_CALL_RESULT for each result the round fed back to the model, each followed by a STATE_DELTA when the state changed and WithStateAfterEachTool is set
  5. With WithReasoning(true), the reasoning of the streamed rounds that did not stream it, whole
  6. STEP_FINISHED / STEP_STARTED when the turn moved the workflow on
  7. If a ToolResultProvider answers the pending client tools: a TOOL_CALL_RESULT for each, then the resumed turn from step 4
  8. STATE_DELTA when the state changed
  9. STEP_FINISHED for the open step
  10. MESSAGES_SNAPSHOT (with WithMessagesSnapshot)
  11. RUN_FINISHED, with the run's token usage

Reasoning is sent only with WithReasoning(true). It streams for a conversation opened with sdk.WithStreamReasoning; otherwise each round's reasoning is sent whole (step 5). A turn that does not stream sends each round's reasoning before its text.

A client tool call left pending ends the run with the call unanswered, and RUN_FINISHED's success outcome names it in pendingToolCallIds; the application answers it in the next run with EventAdapter.RunResume. An approval-held call (sdk.Conversation.OnToolAsync) ends the run with RUN_FINISHED carrying an interrupt outcome that names the held calls; the next run continues with EventAdapter.RunContinue.

A conversation that streams (*sdk.Conversation, through sdk.Conversation.Stream) sends each round's text as it arrives, so the client shows the reply while the model writes it, and each round's calls as soon as the round's reply has streamed, before they run. The deltas of a message make up its text. One that does not (a workflow conversation, or any other Sender) runs the turn with Send, and each message arrives as one TEXT_MESSAGE_CONTENT once the turn has run.

A reply that ends differently from what streamed, as when a guardrail replaces it, is sent as a new text message holding the reply: the client has already shown the streamed text, which AG-UI cannot take back.

Before the model is called, the run offers the input's frontend tools (WithFrontendTools), replaces the conversation's history with the client's (WithClientHistory) and opens msg with the input's context (WithInputContext), each only when its option is set.

On error, a RUN_ERROR ends the run, with the token usage of the model calls made before the error. The events channel is always closed when RunSend returns.

Read Events() concurrently with the run, or cancel ctx: the run waits for the reader once the channel's buffer of 64 events is full, so a caller that lets the run finish before reading blocks there.

func (*EventAdapter) ThreadID

func (a *EventAdapter) ThreadID() string

ThreadID returns the thread ID used by this adapter.

type EventBusProvider

type EventBusProvider interface {
	EventBus() events.Bus
}

EventBusProvider abstracts access to the conversation's event bus. The adapter reads the bus only for WithRuntimeEvents: the run's messages, tool calls and steps come from the turn itself, which keeps them ordered.

type Sender

type Sender interface {
	Send(ctx context.Context, message any, opts ...sdk.SendOption) (*sdk.Response, error)
	SendToolResult(ctx context.Context, callID string, result any) error
	RejectClientTool(ctx context.Context, callID, reason string)
	Resume(ctx context.Context) (*sdk.Response, error)
}

Sender abstracts the conversation methods needed by the adapter. In production code, *sdk.Conversation satisfies this interface.

type StateProvider

type StateProvider interface {
	Snapshot(sender Sender) (any, error)
}

StateProvider produces the state the run keeps in sync with the client (see WithStateProvider). If Snapshot returns an error or a nil state, the run sends nothing for that read and carries on.

type ToolResult

type ToolResult struct {
	CallID   string // must match PendingClientTool.CallID
	Result   any    // JSON-serializable, or []types.ContentPart; ignored when Rejected is true
	Rejected bool
	Reason   string // rejection reason (used when Rejected is true)
	// Error reports that the tool failed. Result, when also set, is the
	// partial output it produced before failing.
	Error string
}

ToolResult carries the caller-provided outcome for a single client tool call.

func ToolResultsFromAGUI added in v2.11.0

func ToolResultsFromAGUI(msgs []aguitypes.Message) []ToolResult

ToolResultsFromAGUI returns the answers a RunAgentInput carries for the client tool calls a previous run left pending: the tool messages at the end of msgs, after the last message of any other role. Pass them to EventAdapter.RunResume. It returns nil when msgs does not end with a tool message.

The trailing tool messages can include results the agent itself produced in that round (a server tool's TOOL_CALL_RESULT the application kept in its history). An sdk.Conversation resumes with an answer only for a call it has no result for yet, so passing them along is harmless.

A tool message's content becomes the Result: text that is a JSON document is passed through as JSON, other text as a string, and content parts as []types.ContentPart. Its error becomes Error.

type ToolResultProvider

type ToolResultProvider func(ctx context.Context, tools []sdk.PendingClientTool) ([]ToolResult, error)

ToolResultProvider is a callback the caller implements to supply results for pending client tools. The adapter calls it when the LLM response contains deferred client tools that need fulfillment before the pipeline can continue. It may answer some of the pending calls and leave the rest.

Jump to

Keyboard shortcuts

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