go-z-ai

command module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: Apache-2.0 Imports: 1 Imported by: 0

README

go-z-ai

A Go CLI, library, and TUI for the Z.AI (Zhipu AI / BigModel) platform — every GLM model surface in one tool, plus a Go port of @z_ai/coding-helper that wires Claude Code, OpenCode, Crush, Factory Droid, and Cursor to your GLM Coding Plan.

English | 简体中文 | Русский | Deutsch | Татарча | Türkçe

CI Go Reference OpenSSF Scorecard Latest release License

Quick example

# 1. Configure (any of these works — env var, .env file, or --config <file>)
export ZAI_API_KEY=your_api_key_here
# or: cp .env.example .env  &&  edit .env

# 2. Use the CLI
go-z-ai chat create "Explain goroutines in one paragraph" --stream
// …or import the library — no CLI required.
import "github.com/SamyRai/go-z-ai/pkg/client"

c, _ := client.NewClientFromEnv()
resp, _ := c.Chat().Create(ctx, client.ChatRequest{
    Model:    "glm-5.2",
    Messages: []client.Message{{Role: "user", Content: "Explain goroutines in one paragraph"}},
})
fmt.Println(resp.Choices[0].Message.Content)

More runnable programs — streaming, async image polling, the Anthropic /v1/messages endpoint — live under examples/.

Features

  • Chat — streaming, structured output (JSON Schema), deep thinking, function/tool calling, vision (glm-4.6v/glm-4.5v), and an Anthropic-compatible /v1/messages endpoint (the same one Claude Code and Cursor hit when wired to a GLM Coding Plan).
  • Media — image generation, video generation (always async), audio transcription, TTS, and GLM-TTS voice cloning.
  • Document understanding — layout OCR, handwriting OCR, and a document parser for RAG preprocessing.
  • Retrieval — embeddings, rerank, built-in web search / web reader / tokenizer tools.
  • Moderations — content moderation via the China-platform endpoint.
  • Agents — Z.AI's specialized agents (translation, slide/poster generation, video effects).
  • Batch & files — JSONL batch jobs for chat completions, file upload/list/download.
  • GLM Coding Plan — quota/usage monitoring, multi-account management, and go-z-ai coding to wire Claude Code, OpenCode, Crush, Factory Droid, and Cursor to your subscription.
  • DX — full-screen terminal UI (go-z-ai tui), regional gateway switching (api.z.aiopen.bigmodel.cn), automatic retry with backoff + jitter, and a typed APIError with every Z.AI error code mapped.

Install

go install github.com/SamyRai/go-z-ai@latest

This produces a binary named go-z-ai on your $GOPATH/bin.

# Optional short alias: ln -s "$(go env GOPATH)/bin/go-z-ai" "$(go env GOPATH)/bin/zai"

Requires Go 1.26.4+ and a Z.AI API key. Building from source, first-run auth, and troubleshooting: Getting Started →

As a CLI

A single go-z-ai binary covering the full surface. Every command supports --help; the quick tour:

go-z-ai chat create "..." --stream          # chat (streaming, tools, vision, structured output)
go-z-ai anthropic messages "..." --stream   # Anthropic-compatible /v1/messages
go-z-ai image|video|audio|voice ...         # media generation, transcription, TTS, cloning
go-z-ai ocr|parser ...                      # OCR + document parsing
go-z-ai embeddings|rerank|moderations ...   # retrieval + content moderation
go-z-ai models list                         # model catalog + pricing
go-z-ai accounts add|use|quota|usage ...    # multi-account + GLM Coding Plan monitoring
go-z-ai coding auth|load|doctor|mcp ...     # wire Claude Code / Cursor / etc. to GLM Coding Plan
go-z-ai tui                                 # full-screen terminal UI (all of the above)
go-z-ai validate                            # confirm your key works with one real call

Every result-producing command takes --format text|json (JSON goes to stdout, progress chatter to stderr, so you can pipe into jq).

→ Full command list: CLI Reference

As a Go library

pkg/client is the only public importable package; everything under internal/ is implementation detail. Retry, timeout, regional gateway selection, and error mapping are centralized — services never build their own http.Client or issue raw requests.

go get github.com/SamyRai/go-z-ai
import "github.com/SamyRai/go-z-ai/pkg/client"

c, err := client.NewClient(client.Config{
    APIKey: os.Getenv("ZAI_API_KEY"),
    // Optional: BaseURL, Timeout, MaxRetries, RetryDelay, ChinaAPIKey, Region
})

Services, all following c.<Service>().<Method>(ctx, …):

Accessor Covers
c.Chat() Completions, streaming, async, RunWithTools
c.Anthropic() Anthropic-protocol /v1/messages (Create, CreateStream)
c.Models() List, Get, text/vision/free filters
c.Images() / c.Videos() Image (sync/async), video (always async)
c.Audio() / c.Voice() Transcription, TTS, voice cloning
c.Layout() / c.FileParser() OCR + document-to-text for RAG
c.Files() / c.Batch() Upload, batch jobs
c.Agents() Z.AI specialized agents
c.Embeddings() / c.Rerank() / c.Moderations() Retrieval + moderation
c.Tools() WebSearch, WebReader, Tokenize
c.Usage() / c.Quota() / c.Account() / c.Detection() GLM Coding Plan monitoring
c.GetAsyncResult() / c.WaitForResult() Shared polling for async tasks

→ Full API with examples: Library Guide → Generated reference: pkg.go.dev

Configuration

Three ways to provide credentials, resolved in this priority order (highest wins):

Method When to use
--api-key <key> flag One-off calls, scripts, CI
--account <name> flag Switch between stored accounts
ZAI_API_KEY env var (or .env file) Everyday local shell use
Accounts store's active account After go-z-ai accounts use <name>

The .env file is the common case — copy the annotated template and edit it:

cp .env.example .env
# or point at any file: go-z-ai --config /path/to/config ...
ZAI_API_KEY=your_api_key_here
# ZAI_API_BASE_URL=https://api.z.ai/api/paas/v4     # override the chat endpoint
# ZAI_REGION=china                                   # if your key was issued on open.bigmodel.cn
# ZAI_CHINA_API_KEY=...                              # separate bigmodel.cn credential
# ZAI_ENV=production

→ Full reference (multi-account, regional gateways, quota windows): Accounts & Quota

Documentation

Full documentation index →

Getting Started CLI Reference
Accounts & Quota Coding Tools
Library Guide Error Handling
Architecture Roadmap & Known Limitations
Contributing Security Policy
Code of Conduct Changelog

How it relates to the official SDKs

Z.AI / Zhipu publish official SDKs for Python (zai-org/z-ai-sdk-python, PyPI zai-sdk), Node (MetaGLM/zhipuai-sdk-nodejs-v4), and Java (MetaGLM/zhipuai-sdk-java-v4). There is no official Go SDKgo-z-ai fills that gap, and layers a CLI, a TUI, regional gateway switching (api.z.aiopen.bigmodel.cn), and GLM Coding Plan multi-account management on top of the same API surface.

ℹ️ zai-claude-config.json at the repo root is a template with placeholder values ("your-zai-api-key-here") used by go-z-ai coding load claude-code. It is not a real config and ships no credentials.

⚠️ Usage policy. Z.AI's coding endpoint is restricted to "officially supported tools" and prohibits SDK-based access; see Coding Tools — Compliance. go-z-ai sends an identifying User-Agent header on every request and its coding subcommand wires officially-supported tools. Using pkg/client directly against the coding endpoint from a custom integration is at your own risk until explicit listing.

Contributing

See CONTRIBUTING.md — in particular, this project's live-verification convention (recorded API cassettes instead of hand-wished fixtures) if you're adding or changing a service.

License

Apache License 2.0 — see LICENSE.

Support

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
examples
anthropic-messages command
Command anthropic-messages hits the Anthropic-compatible /v1/messages endpoint exposed by Z.AI, using the same API key (Bearer auth, not x-api-key).
Command anthropic-messages hits the Anthropic-compatible /v1/messages endpoint exposed by Z.AI, using the same API key (Bearer auth, not x-api-key).
async-poll command
Command async-poll demonstrates the async image flow: submit a request, receive a task id, then block on WaitForResult until the task is terminal.
Command async-poll demonstrates the async image flow: submit a request, receive a task id, then block on WaitForResult until the task is terminal.
audio-tts command
Command audio-tts synthesizes speech from text via GLM TTS and writes the resulting audio bytes to a file.
Command audio-tts synthesizes speech from text via GLM TTS and writes the resulting audio bytes to a file.
chat-streaming command
Command chat-streaming is a minimal example of streaming a chat completion token-by-token with the Z.AI Go client, using the Go 1.23+ iterator API.
Command chat-streaming is a minimal example of streaming a chat completion token-by-token with the Z.AI Go client, using the Go 1.23+ iterator API.
chat-tools command
Command chat-tools demonstrates function/tool calling via RunWithTools: define one or more tools (functions the model can invoke), let the model decide which to call, dispatch the calls, and loop until the model gives a final answer.
Command chat-tools demonstrates function/tool calling via RunWithTools: define one or more tools (functions the model can invoke), let the model decide which to call, dispatch the calls, and loop until the model gives a final answer.
embeddings-batch command
Command embeddings-batch generates embeddings for a list of texts and prints cosine-similarity scores against a query.
Command embeddings-batch generates embeddings for a list of texts and prints cosine-similarity scores against a query.
observability command
Command observability demonstrates wiring an OpenTelemetry hook onto the go-z-ai client, so every API call emits a span carrying the GenAI semantic-convention attributes (gen_ai.request.model, gen_ai.system=z.ai, gen_ai.usage.input_tokens, etc.) plus metrics (duration, request count, token usage) when a MeterProvider is registered.
Command observability demonstrates wiring an OpenTelemetry hook onto the go-z-ai client, so every API call emits a span carrying the GenAI semantic-convention attributes (gen_ai.request.model, gen_ai.system=z.ai, gen_ai.usage.input_tokens, etc.) plus metrics (duration, request count, token usage) when a MeterProvider is registered.
quickstart-chat command
Command quickstart-chat is the minimum hello-world for the go-z-ai client: one shot, non-streaming, prints the assistant's reply.
Command quickstart-chat is the minimum hello-world for the go-z-ai client: one shot, non-streaming, prints the assistant's reply.
quickstart-structured command
Command quickstart-structured shows structured (JSON Schema) output: ask the model for typed data, parse the response into a Go struct.
Command quickstart-structured shows structured (JSON Schema) output: ask the model for typed data, parse the response into a Go struct.
quickstart-vision command
Command quickstart-vision sends an image to a vision-capable GLM model (glm-4.6v) and prints the model's description.
Command quickstart-vision sends an image to a vision-capable GLM model (glm-4.6v) and prints the model's description.
quota-usage command
Command quota-usage inspects the GLM Coding Plan quota and recent usage for the configured API key.
Command quota-usage inspects the GLM Coding Plan quota and recent usage for the configured API key.
rerank-documents command
Command rerank-documents ranks candidate documents against a query using GLM's rerank API — typically the second stage of a RAG pipeline after embedding-based retrieval (see embeddings-batch).
Command rerank-documents ranks candidate documents against a query using GLM's rerank API — typically the second stage of a RAG pipeline after embedding-based retrieval (see embeddings-batch).
internal
accounts
Package accounts persists multiple named Z.AI credentials and tracks which one is active, so the CLI can switch between accounts without hand-editing .env.
Package accounts persists multiple named Z.AI credentials and tracks which one is active, so the CLI can switch between accounts without hand-editing .env.
cli
coding
Package coding is a Go port of Z.AI's official @z_ai/coding-helper ("chelper") CLI.
Package coding is a Go port of Z.AI's official @z_ai/coding-helper ("chelper") CLI.
fileinput
Package fileinput resolves a user-supplied "file or URL" argument into the value the layout/OCR API expects: an http(s) URL is passed through verbatim, while a local path is read and base64-encoded.
Package fileinput resolves a user-supplied "file or URL" argument into the value the layout/OCR API expects: an http(s) URL is passed through verbatim, while a local path is read and base64-encoded.
tui
Package tui implements the go-z-ai interactive terminal UI: a Bubble Tea v2 program with one tab per existing CLI command group, all wired to the same pkg/client, pkg/accounts, and pkg/coding services the non-interactive commands already use.
Package tui implements the go-z-ai interactive terminal UI: a Bubble Tea v2 program with one tab per existing CLI command group, all wired to the same pkg/client, pkg/accounts, and pkg/coding services the non-interactive commands already use.
tui/accounts
Package accounts implements the TUI's Accounts tab: list, add, switch, and remove stored Z.AI account credentials via pkg/accounts.Store, the same store the "go-z-ai accounts" commands use.
Package accounts implements the TUI's Accounts tab: list, add, switch, and remove stored Z.AI account credentials via pkg/accounts.Store, the same store the "go-z-ai accounts" commands use.
tui/chat
Package chat implements the TUI's Chat tab: a streaming conversation over pkg/client's ChatService, the same service "go-z-ai chat" uses.
Package chat implements the TUI's Chat tab: a streaming conversation over pkg/client's ChatService, the same service "go-z-ai chat" uses.
tui/coding
Package coding implements the TUI's Coding tab: install/config status, auth, load, and unload for supported coding-agent tools (Claude Code, OpenCode, Crush, Factory Droid), backed by pkg/coding — the same package the "go-z-ai coding" commands use.
Package coding implements the TUI's Coding tab: install/config status, auth, load, and unload for supported coding-agent tools (Claude Code, OpenCode, Crush, Factory Droid), backed by pkg/coding — the same package the "go-z-ai coding" commands use.
tui/media
Package media implements the TUI's Media tab: image generation, video generation, audio transcription, and OCR/layout parsing over pkg/client's ImagesService/VideosService/AudioService/LayoutService — the same services the "go-z-ai image/video/audio/ocr" commands use.
Package media implements the TUI's Media tab: image generation, video generation, audio transcription, and OCR/layout parsing over pkg/client's ImagesService/VideosService/AudioService/LayoutService — the same services the "go-z-ai image/video/audio/ocr" commands use.
tui/modelpicker
Package modelpicker implements the Chat tab's model picker overlay: a filterable list of available Z.AI models, fetched on open, that lets the user switch the model the Chat tab sends to.
Package modelpicker implements the Chat tab's model picker overlay: a filterable list of available Z.AI models, fetched on open, that lets the user switch the model the Chat tab sends to.
tui/models
Package models implements the TUI's Models tab: a browsable, enriched view of available Z.AI models, backed by the same ModelsService the "go-z-ai models" commands already use.
Package models implements the TUI's Models tab: a browsable, enriched view of available Z.AI models, backed by the same ModelsService the "go-z-ai models" commands already use.
tui/palette
Package palette implements the TUI's Ctrl+P command palette: a fuzzy-filter overlay of app-wide actions (go to tab, refresh, toggle help, switch chat model, quit).
Package palette implements the TUI's Ctrl+P command palette: a fuzzy-filter overlay of app-wide actions (go to tab, refresh, toggle help, switch chat model, quit).
tui/tools
Package tools implements the TUI's Tools tab: three independent request/response forms (web search, web reader, tokenizer) over pkg/client's ToolsService, the same service the "go-z-ai tools" commands use.
Package tools implements the TUI's Tools tab: three independent request/response forms (web search, web reader, tokenizer) over pkg/client's ToolsService, the same service the "go-z-ai tools" commands use.
tui/uimsg
Package uimsg holds tea.Msg types shared between the TUI root model and every screen subpackage.
Package uimsg holds tea.Msg types shared between the TUI root model and every screen subpackage.
tui/uistyle
Package uistyle holds the shared lipgloss style vocabulary used by the root chrome and every screen subpackage, so pill/border/toast colors stay consistent without pkg/tui's screens importing pkg/tui itself (which would create an import cycle, since pkg/tui imports every screen).
Package uistyle holds the shared lipgloss style vocabulary used by the root chrome and every screen subpackage, so pill/border/toast colors stay consistent without pkg/tui's screens importing pkg/tui itself (which would create an import cycle, since pkg/tui imports every screen).
tui/usage
Package usage implements the TUI's Usage tab: a live quota + token/tool usage dashboard, backed by the same QuotaService/UsageService the "go-z-ai usage"/"accounts quota"/"accounts usage" commands use.
Package usage implements the TUI's Usage tab: a live quota + token/tool usage dashboard, backed by the same QuotaService/UsageService the "go-z-ai usage"/"accounts quota"/"accounts usage" commands use.
usageview
Package usageview holds pure, presentation-only helpers for rendering usage/quota data (time windows, relative timestamps, compact counters, and a density-heatmap ramp).
Package usageview holds pure, presentation-only helpers for rendering usage/quota data (time windows, relative timestamps, compact counters, and a density-heatmap ramp).
pkg
observe
Package observe provides observability hooks for the go-z-ai client.
Package observe provides observability hooks for the go-z-ai client.

Jump to

Keyboard shortcuts

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