Skip to content
/ zai Public

A small Go client for the z.ai chat completion API (Coding Plan default).

Notifications You must be signed in to change notification settings

deicod/zai

Repository files navigation

zai (Go)

A small Go client for the z.ai chat completion API (Coding Plan default).

Install

go get github.com/deicod/zai

Quick start (non-streaming)

c, err := zai.NewClient(os.Getenv("ZAI_API_KEY"))
if err != nil {

    log.Fatal(err)
}

resp, err := c.ChatCompletions(context.Background(), &zai.ChatCompletionRequest{

    Model: "glm-4.7",
    Messages: []zai.Message{{
        Role:    zai.RoleUser,
        Content: "Write a Go function that reverses a string.",
    }},
})
if err != nil {
    log.Fatal(err)
}

fmt.Println(resp.Choices[0].Message.Content)

Streaming (SSE)

stream, err := c.ChatCompletionsStream(context.Background(), &zai.ChatCompletionRequest{

    Model: "glm-4.7",
    Messages: []zai.Message{{
        Role:    zai.RoleUser,
        Content: "Explain quicksort in 3 bullet points.",
    }},
    // Exposed as-is (some models support tool argument streaming):
    ToolStream: true,
})
if err != nil {
    log.Fatal(err)
}

defer stream.Close()

acc := zai.NewAccumulator()
for {
    chunk, err := stream.Recv()
    if errors.Is(err, io.EOF) {
        break
    }
    if err != nil {
        log.Fatal(err)
    }
    events, err := acc.Push(chunk)
    if err != nil {
        log.Fatal(err)
    }
    for _, ev := range events {
        if ev.Type == zai.EventTextDelta {
            fmt.Print(ev.TextDelta)
        }
    }
}

final := acc.Finalize()
fmt.Println("\nfinish_reason:", final.FinishReason)

(For a one-shot helper, use zai.Collect(stream).)

Defaults

  • Base URL: https://api.z.ai/api/coding/paas/v4
  • Auth: Authorization: Bearer <API_KEY>
  • Retries: enabled by default (429 and 5xx, plus temporary network errors)

To override the base URL (e.g. general API), pass zai.WithBaseURL(zai.DefaultBaseURLGeneral).

About

A small Go client for the z.ai chat completion API (Coding Plan default).

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

 

Packages

No packages published

Languages