Go SDK AI replies
When a user chats one-to-one with an AI bot, the bot's reply is a message whose Type is ai and whose content is pushed while it is being generated. cli.AI() receives this live content: it joins it in order, resumes after disconnects and fills in after reconnecting, and once the reply ends the message body is authoritative. Bots and replies are created by your server, see AI conversations.
Version
AI replies are available from v1.0.2: go get github.com/DeepRespond-AI/deeprespond-im-go-sdk@v1.0.2.
AI messages
Parse the message body with the package-level function im.BodyOf:
body := im.BodyOf(msg) // 不是 ai 消息时为 nil
if body != nil {
fmt.Println(body.Status) // im.AIStreaming、im.AICompleted、im.AIStopped、im.AIFailed
fmt.Println(body.Parts) // 结束后的完整内容;生成中为空
}| Field | Description |
|---|---|
StreamID | Stream ID of the reply, used to read live content and to stop generation |
Status | streaming generating, completed, stopped, failed interrupted |
Parts | Parts (AIPart): text body (Markdown), reasoning, image and file attachments, tool tool-call progress (State is running, done or failed) |
Text | Plain text without Markdown, up to 2000 characters |
FinishReason, Error | Finish reason; when interrupted, Error.Message is the explanation to show the user |
Parts are described fully in AI messages.
Track content while generating
While a message is generating its Parts is empty; read the live content with State. OnAI is called when a reply starts, on every update and when it ends:
ai := cli.AI()
ai.OnAI(func(s im.AIStreamState) {
if s.Status == im.AIStreaming {
// s.Parts 是当前完整内容(不是增量)
redraw(s.StreamID, s.Parts)
return
}
// 回复结束:Parts 为空,消息随后(或已经)更新为最终内容,改读 im.BodyOf(msg)
})
parts := body.Parts
if body.Status == im.AIStreaming {
if s := ai.State(body.StreamID); s != nil {
parts = s.Parts
}
}- Callbacks run on an internal SDK goroutine; do not block in them. A panic in a callback is recovered and does not affect other callbacks.
- After reconnecting, the SDK fills in content still being generated.
Statereturns a copy; it returnsnilafter the reply ends, so read the message body from then on.
Stop generating
stream, err := cli.AI().Stop(ctx, body.StreamID)
// stream.Status 为 stopped;已结束的回复返回当前状态,不报错Only the user receiving the reply can stop it. Stopping ends the reply immediately, keeps what was generated, and notifies the bot's server. To read a reply's current content from the server, use Get(ctx, streamID); replies that ended more than 10 minutes ago return not_found, so read the message instead.
Regenerate
There is no separate "regenerate" API: send the answered question again and the bot's server starts a new reply.
Demo
The Go demo already displays AI replies: live content is pushed to the page through the bridge and rendered as Markdown, with "Stop generating" and "Copy", and notices for stopped and interrupted replies.
