Documentation
¶
Overview ¶
Package session provides types to manage user sessions and their states.
Index ¶
Constants ¶
const ( // KeyPrefixApp is the prefix for app-level state keys. // They are shared across all users and sessions for that application. KeyPrefixApp string = "app:" // KeyPrefixTemp is the prefix for temporary state keys. // Such entries are specific to the current invocation (the entire process // from an agent receiving user input to generating the final output for // that input. Discarded after the invocation completes. KeyPrefixTemp string = "temp:" // KeyPrefixUser is the prefix for user-level state keys. // They are tied to the user_id, shared across all sessions for that user // (within the same app_name). KeyPrefixUser string = "user:" )
Prefixes for defining session's state scopes
Variables ¶
var ErrStateKeyNotExist = errors.New("state key does not exist")
ErrStateKeyNotExist is the error thrown when key does not exist.
Functions ¶
This section is empty.
Types ¶
type CreateRequest ¶
type CreateRequest struct {
AppName string
UserID string
// SessionID is the client-provided ID of the session to create.
// Optional: if not set, it will be autogenerated.
SessionID string
// State is the initial state of the session.
State map[string]any
}
CreateRequest represents a request to create a session.
type CreateResponse ¶
type CreateResponse struct {
Session Session
}
CreateResponse represents a response for newly created session.
type DeleteRequest ¶
DeleteRequest represents a request to delete a session.
type Event ¶
type Event struct {
model.LLMResponse
// Set by storage
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
// Set by agent.Context implementation.
InvocationID string `json:"invocationId"`
// The branch of the event.
//
// The format is like agent_1.agent_2.agent_3, where agent_1 is
// the parent of agent_2, and agent_2 is the parent of agent_3.
//
// Branch is used when multiple sub-agent shouldn't see their peer agents'
// conversation history.
Branch string `json:"branch,omitempty"`
// IsolationScope, when set, restricts which agent contexts include this
// event in LLM prompt history: an event is visible only when
// event.IsolationScope equals the agent's isolation scope (exact match;
// empty sees only empty). Empty for non-scoped events.
IsolationScope string `json:"isolationScope,omitempty"`
// Author is the name of the event's author
Author string `json:"author"`
// The actions taken by the agent.
Actions EventActions `json:"actions"`
// Set of IDs of the long running function calls.
// Agent client will know from this field about which function call is long running.
// Only valid for function call event.
LongRunningToolIDs []string `json:"longRunningToolIds,omitempty"`
// Routing information for workflow execution
Routes []string `json:"routes,omitempty"`
// RequestedInput, when non-nil, signals that the workflow node
// emitting this event is asking for human input and is about to
// pause. The workflow scheduler observes this field at event
// dispatch time and transitions the corresponding node to
// NodeWaiting on the activation's completion. UI surfaces read
// the same field to render the prompt.
//
// At most one event per node activation may carry this field.
RequestedInput *RequestInput `json:"requestedInput,omitempty"`
// Output is the generic data output from a workflow node.
Output any `json:"output,omitempty"`
// NodeInfo carries workflow-node metadata for events emitted
// inside a workflow. Nil for non-workflow events.
NodeInfo *NodeInfo `json:"nodeInfo,omitempty"`
}
Event represents an interaction in a conversation between agents and users. It is used to store the content of the conversation, as well as the actions taken by the agents like function calls, etc.
func NewEvent ¶
NewEvent creates a new event defining now as the timestamp.
The event ID and timestamp are obtained through the platform package, so a time or UUID provider installed on ctx (see platform.WithTimeProvider and platform.WithUUIDProvider) controls them. This lets callers such as workflow engines produce deterministic, replay-safe events.
func (*Event) IsFinalResponse ¶
IsFinalResponse returns whether the event is the final response of an agent.
Note: when multiple agents participate in one invocation, there could be multiple events with IsFinalResponse() as True, for each participating agent.
func (*Event) UnmarshalJSON ¶ added in v2.2.0
UnmarshalJSON decodes an Event, accepting the timestamp either as an RFC 3339 string (this package's own encoding) or as a JSON number of epoch seconds. The numeric form is what adk-python emits, since its Event timestamp is a float; without this an Event serialized by another ADK runtime fails to decode part-way through, leaving the fields after the timestamp unset.
Numeric timestamps are resolved to microseconds, matching the resolution of Python's datetime. float64 cannot represent epoch seconds to nanosecond precision, so a finer value would only encode rounding noise.
type EventActions ¶
type EventActions struct {
// Set by agent.Context implementation.
StateDelta map[string]any `json:"stateDelta"`
// Indicates that the event is updating an artifact. key is the filename,
// value is the version.
ArtifactDelta map[string]int64 `json:"artifactDelta"`
RequestedToolConfirmations map[string]toolconfirmation.ToolConfirmation `json:"requestedToolConfirmations,omitempty"`
// If true, it won't call model to summarize function response.
// Only valid for function response event.
SkipSummarization bool `json:"skipSummarization,omitempty"`
// If set, the event transfers to the specified agent.
TransferToAgent string `json:"transferToAgent,omitempty"`
// The agent is escalating to a higher level agent.
Escalate bool `json:"escalate,omitempty"`
}
EventActions represent the actions attached to an event.
func (EventActions) MarshalJSON ¶ added in v2.2.0
func (a EventActions) MarshalJSON() ([]byte, error)
MarshalJSON omits StateDelta and ArtifactDelta when they are nil and writes an empty object when they are allocated but empty.
The two cases have to stay distinguishable, and neither `omitempty` nor a plain tag manages it. A map tagged `omitempty` is dropped whenever its length is zero, which loses the difference: NewEvent allocates both maps and callers write into them without a nil check, so an allocated-but-empty map that decodes back as nil panics on the first write. Leaving the tag bare keeps the difference but encodes a nil map as `null`, which adk-python rejects -- both fields are non-Optional dicts there, so the whole EventActions fails to validate ("Input should be an object", type=dict_type) and takes the event with it.
Omitting the key is the third option and the only one that satisfies both: adk-python fills an absent key from the field's default factory, and Go decodes it back to nil, so nil stays nil and empty stays empty in either runtime. The shadowing pointer fields below express that -- `omitempty` on a pointer keys off the pointer being nil, not the length of what it points to.
type Events ¶
type Events interface {
// All returns an iterator (iter.Seq) that yields all events
// in the sequence, preserving their order.
All() iter.Seq[*Event]
// Len returns the total number of events in the sequence.
Len() int
// At returns the event at the specified index i.
At(i int) *Event
}
Events define a standard interface for an Event list. It provides methods for iterating over the sequence and accessing individual events by their index.
type GetRequest ¶
type GetRequest struct {
AppName string
UserID string
SessionID string
// NumRecentEvents returns at most NumRecentEvents most recent events.
// Optional: if zero, the filter is not applied.
NumRecentEvents int
// After returns events with timestamp >= the given time.
// Optional: if zero, the filter is not applied.
After time.Time
}
GetRequest represents a request to get a session.
type GetResponse ¶
type GetResponse struct {
Session Session
}
GetResponse represents a response from Service.Get.
type ListRequest ¶
ListRequest represents a request to list sessions.
type ListResponse ¶
type ListResponse struct {
Sessions []Session
}
ListResponse represents a response from Service.List.
type NodeInfo ¶
type NodeInfo struct {
// Path is the composite path of the emitting node within its
// workflow activation. Empty for top-level static nodes;
// "<parent_path>/<child_name>@<run_id>" for dynamic children.
// The scheduler uses it to scope per-activation Output/Routes
// invariants to the emitter, allowing dynamic nodes to forward
// children's terminal events alongside their own.
Path string `json:"path,omitempty"`
// MessageAsOutput marks that this event's content IS the node's
// output: when set and Event.Output is nil, readers derive the
// node output from the event's model text. Mirrors adk-python's
// node_info.message_as_output.
MessageAsOutput bool `json:"messageAsOutput,omitempty"`
// OutputFor lists the node paths this event's Output counts for: the
// emitter plus any WithUseAsOutput delegating ancestors, so one event
// stands in for a whole delegation chain rather than each level
// re-emitting a duplicate. Mirrors adk-python's node_info.output_for.
OutputFor []string `json:"outputFor,omitempty"`
}
NodeInfo carries the per-event metadata identifying which node in a workflow activation emitted it.
type ReadonlyState ¶
type ReadonlyState interface {
// Get retrieves the value associated with a given key.
// It returns a ErrStateKeyNotExist error if the key does not exist.
Get(string) (any, error)
// All returns an iterator (iter.Seq2) that yields all key-value pairs
// currently in the state. The order of iteration is not guaranteed.
All() iter.Seq2[string, any]
}
ReadonlyState defines a standard interface for a key-value store. It provides basic methods for accessing, and iterating over key-value pairs.
type RequestInput ¶
type RequestInput struct {
// InterruptID correlates this request with the response that
// resumes it; the reply is routed back by matching this ID.
// Prefer a value that is unique per request: leave it empty and
// the engine fills in a fresh UUID (the recommended default), or
// build your own from a readable prefix plus a UUID
// (e.g. "manager_approval-"+uuid).
//
// Avoid reusing one fixed literal across separate runs in the same
// session. ADK clients — notably the Dev UI — track answered
// requests by this ID and will not re-prompt for an ID already
// resolved earlier in the session, so a later run that reuses it
// shows no input box. Mirrors adk-python RequestInput.interrupt_id,
// which defaults to a fresh UUID.
InterruptID string `json:"interruptId"`
// Message is the human-readable description of what is being
// asked. Surfaced in UI as the prompt text. Optional.
Message string `json:"message,omitempty"`
// ResponseSchema, when non-nil, is the JSON schema the user's
// response payload must conform to.
ResponseSchema *jsonschema.Schema `json:"responseSchema,omitempty"`
// Payload is optional context the UI may render alongside the
// prompt (e.g. the document to approve, the proposed parameters).
// Carried through opaquely; the engine does not interpret it.
Payload any `json:"payload,omitempty"`
}
RequestInput describes a single human-in-the-loop prompt emitted by a workflow node. It travels on Event.RequestedInput from the node, through the scheduler, out to the UI surface; the matching response is routed back by InterruptID.
JSON-marshallable: persisted in session.State across pause/resume turns. Payload is typed any and must be JSON-encodable; for binary data, stash the bytes via agent.Artifacts and put a URI string in Payload.
type Service ¶
type Service interface {
Create(context.Context, *CreateRequest) (*CreateResponse, error)
Get(context.Context, *GetRequest) (*GetResponse, error)
List(context.Context, *ListRequest) (*ListResponse, error)
Delete(context.Context, *DeleteRequest) error
// AppendEvent is used to append an event to a session, and remove temporary state keys from the event.
AppendEvent(context.Context, Session, *Event) error
}
Service is a session storage service.
It provides a set of methods for managing sessions and events.
func InMemoryService ¶
func InMemoryService() Service
InMemoryService returns an in-memory implementation of the session service.
type Session ¶
type Session interface {
// ID returns the unique identifier of the session.
ID() string
// AppName returns name of the app.
AppName() string
// UserID returns the id of the user.
UserID() string
// State returns the state of the session.
State() State
// Events return the events of the session, e.g. user input, model response, function call/response, etc.
Events() Events
// LastUpdateTime returns the time of the last update.
LastUpdateTime() time.Time
}
Session represents a series of interactions between a user and agents.
When a user starts interacting with your agent, session holds everything related to that one specific chat thread.
type State ¶
type State interface {
// Get retrieves the value associated with a given key.
// It returns a ErrStateKeyNotExist error if the key does not exist.
Get(string) (any, error)
// Set assigns the given value to the given key, overwriting any
// existing value. It returns an error if the underlying storage
// operation fails.
Set(string, any) error
// All returns an iterator (iter.Seq2) that yields all key-value pairs
// currently in the state. The order of iteration is not guaranteed.
All() iter.Seq2[string, any]
}
State defines a standard interface for a key-value store. It provides basic methods for accessing, modifying, and iterating over key-value pairs.