dialogram

package module
v0.0.0-...-a1bbc68 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 8 Imported by: 1 module, 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.

README

dialogram

English · 简体中文

Conversations that draw. A provider-neutral agent runtime for Go with inline generative UI, human-in-the-loop pauses, and streams that survive the connection.

ci Go Reference Go Report Card Go version

Extracted from ProProp, an AI property advisor for Singapore running in production, where this runtime drives 53 tools, inline generative UI and human-in-the-loop across web, iOS and Telegram.

What it does

  • One conversation shape, two providers. Conversations are persisted as a provider-neutral block IR (text / tool_use / tool_result / image). A turn started on OpenAI can be resumed on Anthropic, and a paused tool call can be resumed later, because neither wire format is baked into the stored state. provider/anthropic and provider/openai are thin adapters over one shared loop, and both run end to end in CI against hand-written wire-format fixtures, cross-provider resume and image turns included, with no network or API key.
  • Tool results split into three channels. A tool returns an Envelope: what the model hears (model_observation), what the user sees (ui_payload, rendered inline as a chart or table), and what the server keeps (runtime_state, the raw rows, addressable through opaque artifact handles). The model asks for a table to be shown by handle; the rows never enter its context. An envelope can also be marked untrusted: its observation then reaches the model fenced as data, not as instructions.
  • Policy from annotations. Tools carry MCP-style hints (ReadOnly, Destructive, Idempotent, OpenWorld). agent.PolicyInterceptor turns them into pause or deny decisions in the same interceptor chain as the approval list. The hints never reach the model.
  • Tool calls with limits, turns that survive a crash. The default tool.LocalExecutor gives each call a timeout, recovers panics, caps the bytes the model reads back and bounds how many calls run at once. Timeouts and panics reach the model as soft failures. A Checkpointer saves the turns at every step boundary, and CloseDangling pairs unanswered calls after a crash so the conversation continues on either provider. There is no sandbox: isolation belongs to the tool.
  • MCP servers as tool sources. tool/mcp connects to a server over stdio or streamable HTTP and registers its tools under a per-server prefix. Server annotations map onto the policy hints, and results from servers you do not operate can be fenced as untrusted. A server that asks the user for input in the middle of a call (elicitation) pauses the run until the user answers, through either transport. examples/mcpagent is a terminal agent on one server's tools; docs/MCP.md runs it against sg-property-engine.
  • Human-in-the-loop as tools. request_user_input, request_user_choice and request_user_form end the turn and wait; an interceptor chain can pause any tool for approval; applications add their own pause tools. Mixed turns (a pause co-requested with real tools) run the real tools and defer the pause deterministically instead of dropping work, and agent.AnswerPause resumes a paused turn with every call in it answered, so the next request is one both providers accept.
  • Streams that survive the connection. The model call is a detached server-side producer writing to a streambuf.Store (memory or Redis). The HTTP connection is disposable: a client reconnects with the last id: it saw and gets exactly the events it missed. Tab switches, radio sleep and load-balancer hops stop losing replies.
  • Prompt-cache aware. With Anthropic, the stable system prompt, the tool list and the growing conversation each carry a cache breakpoint; the per-turn volatile context is sent as a separate un-cached block so state drift does not bust the cache.
  • An honesty guard you can measure. agent.Guard redacts regulated figures stated on a turn with no successful grounding tool call. The eval package ships the paired before/after harness that measures whether it fires on the turns a judge flags, and the guard is designed against the failure modes such a measurement exposes.
  • Traces and metrics per run. Every Chat / ChatStream is an OpenTelemetry span tree following the GenAI semantic conventions: an invoke_agent run span, a chat {model} span per upstream request with token and cache usage, and an execute_tool {name} span per tool call with its outcome (success, soft failure, timeout, panic, denied). The SSE producer joins the trace of the request that launched it. Nothing is recorded until you install an SDK. Opt-in Prometheus metrics track the per-turn budgets the eval harness asserts.
  • Skills on demand. Skills in the Agent Skills format (SKILL.md) are advertised as a name-and-description catalog in the cached prompt, and the model loads a skill's instructions and its bundled files through a load_skill tool. Loading is lenient the way the format's client guide recommends, and agent.ValidateSkills applies the strict rules in CI.
browser ── POST /chat/stream?message_id=X&since=N ──▶ sse.Handler ──▶ streambuf.Store (mem | redis)
   ▲                                                      │  Start(X) wins? → go produce()      ▲
   └──── id:<seq> event:<type> data:{…} ◀──── Tail(since) ┘                                    │
                                                          ▼                                    │
                                              agent.Agent.ChatStream ── provider loop ── Append(X, event)
                                              (guard · metrics)        (tools · pauses · cache breakpoints)

Conversations in ProProp

ProProp's advisor chat runs on this runtime; each screenshot shows one turn of a conversation. Click a screenshot to view it at full size.

Two PSF trend calls in one step, then a sourced summary
Parallel tool calls. Two trend lookups in one step; the answer names its dataset.A line chart rendered in the chat
Inline generative UI. The follow-up draws both towns on one chart.Stamp duty computed band by band
Figures from tools. BSD and ABSD come from calculators on the IRAS tables.Five lookups for one project, then its profile
A project, looked up. Five calls in one step: location, unit mix, MRT, transactions, profile.The project card with facts and floor plans
The project card. A chip opens the server's record; images are blurred because they belong to developers.A web search with linked quotes and listed sources
Searching the web. Each forum quote links to its thread; sources listed below.Rental yields for four districts tied to the user's shortlist
Per-turn context. Four estimates in one step; the user's shortlist arrives as volatile context.A shortlist proposal waiting for Add or Skip
An application pause. The run waits on Add or Skip; the input is locked until then.

How it compares

dialogram is a single-agent runtime: one tool loop, its transport and its persisted state. It is not a LangChain-style integration library, and it is not a graph orchestrator.

Vercel AI SDK (TypeScript)

  • Shared: tool approval that ends the call, typed UI parts per tool result, a separate model-facing view of tool output, resumable streams.
  • dialogram adds: a stored IR both adapters resume from, per-tool timeouts and output caps, annotation-driven policy, an eval harness.
  • dialogram lacks: the AI SDK's provider list, its React, Vue and Svelte integrations, the JavaScript ecosystem.

OpenAI Agents SDK (Python, JS/TS)

  • Shared: approval interruptions with serialisable run state, MCP over stdio and streamable HTTP, per-call tool timeouts, tracing.
  • dialogram adds: a resumable stream transport, a UI channel for tool results, annotation-driven policy, an eval harness that needs no platform.
  • dialogram lacks: handoffs and agents-as-tools, general guardrails, session backends, hosted MCP tools, realtime voice.

Eino (Go)

  • Shared: Go, interrupt and resume through a pluggable checkpoint store, MCP tools, callback hooks.
  • dialogram adds: a resumable stream transport, the three-channel envelope, annotation policy and provenance fencing, the honesty guard with its A/B harness.
  • dialogram lacks: graphs and workflows, multi-agent, retrieval components, the eino-ext integration catalogue.

docs/COMPARISON.md covers nine projects and four protocols, with a capability matrix and sources. "Adds" means not found in the other project's own docs as read on 2026-10-23.

Quickstart

go get github.com/Cyprinus12138/dialogram
reg := tool.NewRegistry()
tool.RegisterHITL(reg)         // request_user_input / _choice / _form
tool.RegisterPresentData(reg)  // inline metric cards, bar/line charts, tables
tool.RegisterRenderFromRef(reg)
reg.Register(&tool.Tool{
    Name: "get_weather", Description: "Five-day forecast for a city.",
    Schema: tool.Obj(map[string]any{"city": tool.Str("City")}, "city"),
    Fn: func(ctx context.Context, in json.RawMessage) (any, error) {
        rows := lookup(in)
        return &tool.Envelope{
            ModelObservation: summary(rows),                                   // what the model hears
            UIPayload:        &tool.UIPayload{Component: "bar_chart", Data: bars(rows)}, // what the user sees
            RuntimeState:     table(rows),                                     // what the server keeps
            Artifacts:        []tool.ArtifactRef{{ID: tool.ToolUseIDFromContext(ctx), Type: tool.ShapeTableRecord}},
        }, nil
    },
})

cfg := &agent.Config{
    Profiles:       map[string]agent.Profile{"assistant": {SystemPrompt: "You are a concise travel assistant…"}},
    DefaultProfile: "assistant",
}
ag, err := dialogram.New(dialogram.SettingsFromEnv(), dialogram.Deps{
    Registry:     reg,
    Config:       cfg,
    Interceptors: []agent.Interceptor{agent.NewApprovalListInterceptor([]string{"book_flight"})},
    Guard:        agent.NewGuard("get_weather"), // optional
})

out, err := ag.Chat(ctx, agent.ChatInput{Turns: history})
// or stream:
err = ag.ChatStream(ctx, agent.ChatInput{Turns: history}, func(ev agent.StreamEvent) { … })

Serve it resumably:

buf := streambuf.NewMemStore(0) // or streambuf.NewRedisStore(ctx, streambuf.RedisOptions{URL: redisURL})
h := sse.NewHandler(buf, func(ctx context.Context, msgID string, body []byte, emit agent.EmitFn) error {
    history := loadConversation(body)
    return ag.ChatStream(ctx, agent.ChatInput{Turns: history}, emit)
}, sse.Options{OnFinish: func(ctx context.Context, r sse.Result) { persist(r.Turns, r.Paused) }})
mux.Handle("/chat/stream", h)
mux.Handle("/chat/cancel", h.CancelHandler())

Run the reference server and open http://localhost:8080:

ANTHROPIC_API_KEY=… go run ./examples/chatserver
# or any OpenAI-compatible endpoint:
LLM_PROVIDER=openai OPENAI_API_KEY=… OPENAI_BASE_URL=https://api.groq.com/openai/v1 OPENAI_MODEL=llama-3.3-70b-versatile go run ./examples/chatserver

The example has a weather tool that renders a bar chart, a flight search whose rows are shown by artifact handle, an approval-gated booking tool, a choice pause, an in-memory conversation store, and a vanilla-JS client that resumes a stream after a reload. Its Singapore property tools are adapted from ProProp: HDB resale comparables whose rows stay behind an artifact handle, a price-trend line chart, the IRAS stamp-duty calculators, and propose_shortlist, an application pause that takes only a project name and shows the user the project's facts from the server's own table. The market tools run on a generated demo sample and the projects are fictional.

Packages

Package What it is
agent Block IR, Provider contract, Agent wrapper, profiles, interceptors, pause detection, skills, the honesty Guard, opt-in Prometheus metrics, OpenTelemetry run spans (Options.TracerProvider)
tool Tool, Registry, the three-channel Envelope, ArtifactStore, built-in tools (HITL ×3, present_data, render_from_ref, now)
tool/mcp MCP client as a tool source: Connect to a server over stdio or streamable HTTP, Register its tools under a per-server prefix, results mapped to the registry's shapes
provider/anthropic, provider/openai Wire adapters: translators, streaming parsers, cache breakpoints, retries
streambuf Store contract with MemStore and RedisStore
sse The resumable HTTP handler: detached producer, idle watchdog, cancel, gen_ui conversion, OnFinish persistence hook
agui AG-UI protocol transport for CopilotKit-compatible frontends: Encoder from stream events to AG-UI events, messages ⇄ turns conversion, one-run-per-request handler, pauses as AG-UI interrupts resumed with signed ids
eval Grounding checker, LLM-as-judge scenarios, manifest pins, budgets, honesty-guard A/B runner
dialogram (root) New / NewProvider / SettingsFromEnv

Docs

  • docs/STREAMING.md — the resumable stream protocol and the store contract
  • docs/AGUI.md — serving a run over the AG-UI protocol, and when to prefer it over sse
  • docs/BLOCK_IR.md — the block IR, the three-channel envelope and artifact handles
  • docs/SKILLS.md — Agent Skills: the format, progressive disclosure through load_skill, validation, and what is not supported
  • docs/MCP.md — MCP servers as tool sources: transports, registration, result mapping, the isolation stance
  • docs/EVAL.md — the three-layer evaluation harness
  • docs/COMPARISON.md — how dialogram relates to nine agent frameworks and four protocols, gaps included
  • docs/HONESTY_AB.md — how to measure an honesty guard, and the failure modes it has to handle
  • docs/OBSERVABILITY.md — Prometheus metrics and the OpenTelemetry span model

Status

Pre-1.0. The public surface may still move; see CHANGELOG.md.

License

MIT. Copyright 2026 Mr.Cyprinus (https://github.com/Cyprinus12138).

Documentation

Overview

Package dialogram is the batteries-included entry point: pick a provider from settings, wrap it in an Agent, and you have a tool-using chat loop with streaming, human-in-the-loop pauses, inline generative UI and an optional honesty guard.

reg := tool.NewRegistry()
tool.RegisterHITL(reg)
tool.RegisterPresentData(reg)
reg.Register(myWeatherTool)

ag, err := dialogram.New(dialogram.SettingsFromEnv(), dialogram.Deps{
	Registry: reg,
	Config:   &agent.Config{Profiles: map[string]agent.Profile{"assistant": {SystemPrompt: "..."}}, DefaultProfile: "assistant"},
})

The sub-packages are usable on their own: agent (block IR, profiles, guard), tool (registry + envelope), provider/anthropic and provider/openai (wire adapters), streambuf (resumable stream buffers), sse (the resumable HTTP handler) and eval (the evaluation harness).

Index

Constants

View Source
const (
	ProviderAnthropic = "anthropic"
	ProviderOpenAI    = "openai"
)

Provider names accepted by Settings.Provider.

Variables

This section is empty.

Functions

func New

func New(s Settings, d Deps) (*agent.Agent, error)

New builds the configured provider and wraps it in an Agent with the guard, metrics and tracer provider from d.

func NewProvider

func NewProvider(s Settings, d Deps) (agent.Provider, error)

NewProvider builds the raw provider selected by s, WITHOUT the Agent wrapper — no guard, no metrics. Use New for production paths; this seam exists so an eval harness can observe the model's raw reply.

Types

type Deps

type Deps struct {
	Registry     *tool.Registry
	Config       *agent.Config
	Interceptors []agent.Interceptor
	Skills       *agent.SkillLibrary
	// Executor runs tool calls; nil selects tool.NewLocalExecutor with the
	// default limits.
	Executor tool.Executor
	// Checkpointer, when non-nil, receives the run's block IR at every
	// step boundary so a crashed turn can be recovered (see
	// agent.Checkpoint and docs/STREAMING.md).
	Checkpointer agent.Checkpointer
	// Guard, Metrics and TracerProvider are layered on by New (not
	// NewProvider). A nil TracerProvider uses the global one, which records
	// nothing until an OpenTelemetry SDK is installed.
	Guard          *agent.Guard
	Metrics        *agent.Metrics
	TracerProvider trace.TracerProvider
}

Deps are the application-side pieces every provider receives.

type Settings

type Settings struct {
	// Provider is "anthropic" or "openai". Empty means anthropic when an
	// Anthropic key is set, else openai.
	Provider string

	AnthropicAPIKey  string
	AnthropicModel   string
	AnthropicBaseURL string

	OpenAIAPIKey  string
	OpenAIBaseURL string
	OpenAIModel   string
}

Settings select and configure the model backend.

func SettingsFromEnv

func SettingsFromEnv() Settings

SettingsFromEnv reads LLM_PROVIDER, ANTHROPIC_API_KEY, ANTHROPIC_MODEL, ANTHROPIC_BASE_URL, OPENAI_API_KEY, OPENAI_BASE_URL and OPENAI_MODEL.

Directories

Path Synopsis
Package agent is the provider-neutral core of dialogram: the block IR a conversation is persisted in, the Provider contract every model backend implements, the Agent wrapper that layers the honesty guard and metrics on top of a provider, and the supporting pieces the tool loop relies on (profiles, interceptors, skills, pause detection).
Package agent is the provider-neutral core of dialogram: the block IR a conversation is persisted in, the Provider contract every model backend implements, the Agent wrapper that layers the honesty guard and metrics on top of a provider, and the supporting pieces the tool loop relies on (profiles, interceptors, skills, pause detection).
Package agui serves a dialogram run over the AG-UI protocol (https://docs.ag-ui.com), the event vocabulary that CopilotKit and the other AG-UI clients consume.
Package agui serves a dialogram run over the AG-UI protocol (https://docs.ag-ui.com), the event vocabulary that CopilotKit and the other AG-UI clients consume.
Package eval is the evaluation harness for a dialogram agent, organised in three cheapest-first layers so the free tiers can gate every pull request and only the paid tier runs on a schedule:
Package eval is the evaluation harness for a dialogram agent, organised in three cheapest-first layers so the free tiers can gate every pull request and only the paid tier runs on a schedule:
examples
agui command
Command agui serves a weather assistant over the AG-UI protocol, for CopilotKit-style frontends: POST a RunAgentInput to /agui and read the event stream back.
Command agui serves a weather assistant over the AG-UI protocol, for CopilotKit-style frontends: POST a RunAgentInput to /agui and read the event stream back.
chatserver command
Command chatserver is a runnable reference deployment of dialogram: a chat assistant for trips and Singapore property with resumable streaming, inline charts and tables, human-in-the-loop choices, an approval-gated tool, an application-defined pause, an Agent Skills package and an in-memory conversation store.
Command chatserver is a runnable reference deployment of dialogram: a chat assistant for trips and Singapore property with resumable streaming, inline charts and tables, human-in-the-loop choices, an approval-gated tool, an application-defined pause, an Agent Skills package and an in-memory conversation store.
mcpagent command
Command mcpagent is a terminal agent whose tools all come from one MCP server.
Command mcpagent is a terminal agent whose tools all come from one MCP server.
mcptools command
Command mcptools connects to an MCP server, registers its tools into a dialogram tool.Registry and prints what the model would see: the registered names and the Anthropic tool spec with each server's input schema passed through.
Command mcptools connects to an MCP server, registers its tools into a dialogram tool.Registry and prints what the model would see: the registered names and the Anthropic tool spec with each server's input schema passed through.
internal
loop
Package loop holds the provider-neutral machinery both wire translators share: tool dispatch through the interceptor chain, pause handling for mixed turns, system-prompt composition, retry/backoff and token estimation.
Package loop holds the provider-neutral machinery both wire translators share: tool dispatch through the interceptor chain, pause handling for mixed turns, system-prompt composition, retry/backoff and token estimation.
telemetry
Package telemetry is the OpenTelemetry vocabulary dialogram's spans share: the instrumentation scope, operation and event names, attribute keys, and the helpers the loop and the provider adapters use to start child spans.
Package telemetry is the OpenTelemetry vocabulary dialogram's spans share: the instrumentation scope, operation and event names, attribute keys, and the helpers the loop and the provider adapters use to start child spans.
provider
anthropic
Package anthropic is the Anthropic Messages API adapter for dialogram.
Package anthropic is the Anthropic Messages API adapter for dialogram.
internal/replay
Package replay serves recorded upstream responses to the provider adapters under test and records what each adapter sent.
Package replay serves recorded upstream responses to the provider adapters under test and records what each adapter sent.
openai
Package openai is the OpenAI Chat Completions adapter for dialogram.
Package openai is the OpenAI Chat Completions adapter for dialogram.
Package sse serves a resumable chat stream over Server-Sent Events.
Package sse serves a resumable chat stream over Server-Sent Events.
Package streambuf persists in-flight streaming events keyed by a client-supplied message id so that a client can disconnect (tab switch, network drop, mobile backgrounding) and reconnect to resume from where it left off — the pattern the major chat products use.
Package streambuf persists in-flight streaming events keyed by a client-supplied message id so that a client can disconnect (tab switch, network drop, mobile backgrounding) and reconnect to resume from where it left off — the pattern the major chat products use.
Package tool is the tool layer of dialogram: the Tool contract, the Registry the agent loop dispatches through, the three-channel result Envelope, the ArtifactStore that backs opaque data handles, and a handful of built-in tools (human-in-the-loop pauses, inline UI rendering, a clock).
Package tool is the tool layer of dialogram: the Tool contract, the Registry the agent loop dispatches through, the three-channel result Envelope, the ArtifactStore that backs opaque data handles, and a handful of built-in tools (human-in-the-loop pauses, inline UI rendering, a clock).
mcp
Package mcp connects a dialogram tool.Registry to Model Context Protocol servers.
Package mcp connects a dialogram tool.Registry to Model Context Protocol servers.

Jump to

Keyboard shortcuts

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