docsgpt

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 18 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

DocsGPT Go SDK

A Go client for the DocsGPT chat API: the OpenAI-compatible /v1/chat/completions endpoint, with streaming, tool calls, sources and conversation ids. It is the client docsgpt-cli is built on.

go get github.com/arc53/DocsGPT-cli/sdk

The import path ends in /sdk; the package is docsgpt.

import docsgpt "github.com/arc53/DocsGPT-cli/sdk"

client := docsgpt.NewClient("https://gptcloud.arc53.com", apiKey)
resp, err := client.Send(ctx, docsgpt.ChatRequest{
	Messages: []docsgpt.Message{{Role: "user", Content: "What is DocsGPT?"}},
})

apiKey is an agent API key (DocsGPT → Agent settings → API key).

Streaming and tools

Run streams the answer, runs tool calls through your handler and sends the results back until the model is done:

res, err := client.Run(ctx, messages, docsgpt.RunOptions{
	Stream: true,
	Tools:  tools,
	OnDelta: func(d docsgpt.Delta, _ string) { fmt.Print(d.Content) },
	OnToolCall: func(tc docsgpt.ToolCall) string {
		return runTool(tc) // the result the model sees
	},
})
// res.Messages: the history with the new turns
// res.ConversationID: pass it in RunOptions to continue the conversation
// res.Sources, res.Model, res.Usage

A tool that returns images uses OnToolResult instead: its ToolResult carries the text and Parts (ImagePart), which the server shows to the model.

API What
Send, SendStream One request, whole or streamed (StreamHandler per delta)
Run The tool-call loop, streamed or not; RunWithTools is its older positional form (deprecated)
ToolResult, OnToolResult A tool result with images for the model
Message.Parts, AttachmentPart Images and files in a message (below)
Models The key's agent (GET /v1/models); a cheap way to check a key
APIError A non-2xx reply: status code, body, Message() (the server's message, one line), Code(), RetryAfter
RetryPolicy Client.Retry: how failed chat requests are sent again

Images and files

A user message carries images and files as content parts after its text; the server stores them as the conversation's attachments (PDFs, office documents, spreadsheets, text, PNG/JPEG/WebP images), so later turns of the conversation see them too.

data, _ := os.ReadFile("shot.png")
msg := docsgpt.Message{
	Role:    "user",
	Content: "Why does this fail?",
	Parts:   []docsgpt.ContentPart{docsgpt.AttachmentPart("shot.png", data)},
}

AttachmentPart sends an image (told by its bytes) as an image_url part and anything else as a file part named by its file name; ImagePart, FilePart and TextPart build one kind. With Parts, the message goes out with the OpenAI content array; one read back with a content array has every part in Parts, and Text() joins its text.

Retries

NewClient retries a chat request up to 3 times (after 2s, 4s, 8s) when it failed before any of the answer arrived: 408, 429, 502, 503, 504, or a connection refused, reset or timed out. A Retry-After is honoured, up to MaxDelay (a longer one returns the error at once), and so is x-should-retry: false; a spent usage limit (error_code ending in limit-reached) is not retried. A stream that fails once it has started is never retried, so an answer never comes twice.

client.Retry.OnRetry = func(ev docsgpt.RetryEvent) {
	log.Printf("retrying (%d/%d) in %s: %v", ev.Attempt, ev.MaxRetries, ev.Delay, ev.Err)
}
client.Retry = docsgpt.RetryPolicy{} // never retry

Cancelling the context ends a wait at once.

Versioning

The module has no dependencies beyond the standard library. It is versioned independently of the CLI, under sdk/vX.Y.Z tags, and is below v1, so the API may still change.

Documentation

Overview

Package docsgpt is a Go client for the DocsGPT chat API.

It talks to the OpenAI-compatible /v1/chat/completions endpoint of a DocsGPT server, with the streaming, tool-calling and conversation-id handling the DocsGPT extensions add on top.

client := docsgpt.NewClient("https://gptcloud.arc53.com", apiKey)
resp, err := client.Send(ctx, docsgpt.ChatRequest{
	Messages: []docsgpt.Message{{Role: "user", Content: "What is DocsGPT?"}},
})

The import path ends in /sdk while the package is named docsgpt, so imports are written as:

import "github.com/arc53/DocsGPT-cli/sdk"

and the package is referred to as docsgpt.

This module is versioned independently of the docsgpt-cli command that lives in the same repository: its tags are prefixed, as in sdk/v0.1.0. While it is below v1 the API may still change.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ImageType added in v0.2.0

func ImageType(data []byte) string

ImageType returns the media type of an image the models read (PNG, JPEG, GIF or WebP), told by its first bytes; "" for anything else.

func MimeType added in v0.2.0

func MimeType(filename string) string

MimeType returns the media type of a file named filename, without parameters: from its extension, application/octet-stream when unknown.

func Retryable added in v0.2.0

func Retryable(err error) bool

Retryable reports whether err, from a request that got no answer, is worth sending the request again for: a transient status (408, 429, 502, 503, 504) that the server did not mark final, or a connection that failed or was dropped. A spent usage limit (a 429 whose code ends in "limit-reached"), a name that does not resolve and a TLS failure are not.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status the server replied with.
	StatusCode int
	// Body is the raw response body, which usually carries the server's
	// own error message (see Message).
	Body string
	// RetryAfter is the wait the server asked for in a Retry-After header,
	// or 0.
	RetryAfter time.Duration
	// contains filtered or unexported fields
}

APIError is returned when the server answers with a non-200 status. Callers that need to tell "the agent is missing" from "the key is wrong" from "the server is down" can inspect StatusCode rather than matching on a string.

func (*APIError) Code added in v0.2.0

func (e *APIError) Code() string

Code is the machine-readable error code of a JSON body (error.code, error.type or error_code), or "".

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Message added in v0.2.0

func (e *APIError) Message() string

Message is the server's own error message, on one line: from a JSON body ({"error":{"message"}}, {"error":"…"}, {"message"} or {"detail"}), else the body's first line. An HTML page (a proxy's error page) gives "".

type ChatRequest

type ChatRequest struct {
	Model    string    `json:"model,omitempty"`
	Messages []Message `json:"messages"`
	Stream   bool      `json:"stream"`
	// StreamOptions is set by SendStream, which always asks for usage.
	StreamOptions *StreamOptions `json:"stream_options,omitempty"`
	Tools         []Tool         `json:"tools,omitempty"`
	// ConversationID continues a conversation the server stored: it then
	// takes the history from that conversation instead of from Messages.
	ConversationID string          `json:"conversation_id,omitempty"`
	DocsGPT        *DocsGPTRequest `json:"docsgpt,omitempty"`
}

type ChatResponse

type ChatResponse struct {
	Model   string      `json:"model,omitempty"`
	Choices []Choice    `json:"choices"`
	DocsGPT DocsGPTMeta `json:"docsgpt,omitempty"`
	Usage   *Usage      `json:"usage,omitempty"`
}

type Choice

type Choice struct {
	Delta        Delta  `json:"delta,omitempty"`
	Message      Delta  `json:"message,omitempty"`
	FinishReason string `json:"finish_reason,omitempty"`
}

type Client

type Client struct {
	BaseURL    string
	APIKey     string
	HTTPClient *http.Client
	// Retry says how chat requests that failed before their answer
	// started are sent again; the zero value never retries.
	Retry RetryPolicy
}

func NewClient

func NewClient(baseURL, apiKey string) *Client

NewClient returns a client for the server at baseURL, with DefaultRetryPolicy.

func (*Client) Models added in v0.2.0

func (c *Client) Models(ctx context.Context) ([]Model, error)

Models lists the models the API key can use (GET /v1/models). DocsGPT answers with the key's agent, or 401 for an unknown key, without running the agent, which makes this a cheap way to check a key.

func (*Client) Run added in v0.2.0

func (c *Client) Run(ctx context.Context, messages []Message, opts RunOptions) (*RunResult, error)

Run sends a chat request and handles tool call loops. When the model returns tool_calls, OnToolResult (or OnToolCall) is invoked for each one, and results are sent back in a continuation request. This repeats until the model returns finish_reason "stop" (or non-tool_calls).

func (*Client) RunWithTools deprecated

func (c *Client) RunWithTools(
	ctx context.Context,
	messages []Message,
	tools []Tool,
	stream bool,
	onDelta StreamHandler,
	onToolCall ToolCallHandler,
) ([]Message, error)

RunWithTools is Run with positional arguments, returning only the messages.

Deprecated: use Run, which also returns the conversation id, sources, model and usage.

func (*Client) Send

func (c *Client) Send(ctx context.Context, req ChatRequest) (*ChatResponse, error)

Send performs a non-streaming chat completion request.

func (*Client) SendStream

func (c *Client) SendStream(ctx context.Context, req ChatRequest, onDelta StreamHandler) (*ChatResponse, error)

SendStream performs a streaming chat completion request, calling onDelta for each chunk. It returns the accumulated final response, including the conversation id, sources, model and usage the stream carried.

type ContentPart added in v0.2.0

type ContentPart struct {
	Type     string    `json:"type"` // "text", "image_url" or "file"
	Text     string    `json:"text,omitempty"`
	ImageURL *ImageURL `json:"image_url,omitempty"`
	File     *FileData `json:"file,omitempty"`
}

ContentPart is one part of a multimodal message, as the OpenAI content array has it: text, an image (image_url) or a file (file). DocsGPT stores the images and files sent inline as the conversation's attachments.

func AttachmentPart added in v0.2.0

func AttachmentPart(filename string, data []byte) ContentPart

AttachmentPart returns the part for a file named filename: an image_url part for a PNG, JPEG, GIF or WebP image (told by its bytes), else a file part, its type taken from the name.

func FilePart added in v0.2.0

func FilePart(filename, mimeType string, data []byte) ContentPart

FilePart returns a file part carrying the file as a data URL. The server reads it by its name's extension (a PDF, a spreadsheet, text).

func ImagePart added in v0.2.0

func ImagePart(mimeType string, data []byte) ContentPart

ImagePart returns an image_url part carrying the image as a data URL.

func TextPart added in v0.2.0

func TextPart(text string) ContentPart

TextPart returns a text part.

type Delta

type Delta struct {
	Role             string     `json:"role,omitempty"`
	Content          string     `json:"content,omitempty"`
	ReasoningContent string     `json:"reasoning_content,omitempty"`
	ToolCalls        []ToolCall `json:"tool_calls,omitempty"`
}

type DocsGPTMeta

type DocsGPTMeta struct {
	// Type names the kind of a streamed extension chunk ("id", "source",
	// "model", ...); it is empty on a non-streaming response.
	Type           string `json:"type,omitempty"`
	ConversationID string `json:"conversation_id,omitempty"`
	// Model is the LLM that answered (the top-level model is the agent).
	Model     string          `json:"model,omitempty"`
	Sources   json.RawMessage `json:"sources,omitempty"`
	ToolCalls json.RawMessage `json:"tool_calls,omitempty"`
}

DocsGPTMeta is the response-side "docsgpt" extension object. Sources and ToolCalls stay raw so a surprising shape can never fail the whole response decode (which would drop an otherwise valid answer); see ParseSources.

type DocsGPTRequest

type DocsGPTRequest struct {
	Attachments []string `json:"attachments,omitempty"`
}

DocsGPTRequest is the request-side "docsgpt" extension object. It currently carries server-side attachment ids for the /v1 endpoint.

type FileData added in v0.2.0

type FileData struct {
	Filename string `json:"filename,omitempty"`
	FileData string `json:"file_data,omitempty"`
	FileID   string `json:"file_id,omitempty"`
}

FileData is a file part's file: its bytes as a data URL (FileData), or the id of a file the server already holds.

type FunctionCall

type FunctionCall struct {
	Name      string `json:"name,omitempty"`
	Arguments string `json:"arguments,omitempty"`
}

type ImageURL added in v0.2.0

type ImageURL struct {
	URL    string `json:"url"`
	Detail string `json:"detail,omitempty"`
}

ImageURL is an image_url part's image: a URL, or the image itself as a data URL.

type Message

type Message struct {
	Role       string
	Content    string
	Parts      []ContentPart
	ToolCalls  []ToolCall
	ToolCallID string
}

Message is one chat message. Content is its text; Parts add images and files to a user message, or images to a tool result (see ContentPart, ToolResult), and the message then goes out with the OpenAI content array: Content as its first text part, then Parts. A message read with a content array has all its parts in Parts and Content empty; Text joins its text either way.

func (Message) MarshalJSON added in v0.2.0

func (m Message) MarshalJSON() ([]byte, error)

MarshalJSON writes content as a string, or, with Parts, as the parts array: Content first as a text part, then Parts.

func (Message) Text added in v0.2.0

func (m Message) Text() string

Text returns the message's text: Content, then the text parts, a line apart.

func (*Message) UnmarshalJSON added in v0.2.0

func (m *Message) UnmarshalJSON(b []byte) error

UnmarshalJSON reads content as a string into Content, or as an array into Parts, all of them (text parts too: see Text).

type Model added in v0.2.0

type Model struct {
	ID          string `json:"id"`
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
	OwnedBy     string `json:"owned_by,omitempty"`
}

Model is an entry of GET /v1/models. On DocsGPT it describes the agent the API key belongs to: ID is the agent id and Name its display name.

type RetryEvent added in v0.2.0

type RetryEvent struct {
	Attempt    int           // 1 for the first retry
	MaxRetries int           // the policy's MaxRetries
	Delay      time.Duration // the wait before it
	Err        error         // why the last attempt failed
}

RetryEvent describes a retry about to happen.

type RetryPolicy added in v0.2.0

type RetryPolicy struct {
	// MaxRetries is how many times a request is sent again; 0 never.
	MaxRetries int
	// BaseDelay is the wait before the first retry, doubled for each next
	// one; a Retry-After from the server takes its place.
	BaseDelay time.Duration
	// MaxDelay caps a wait. When the server asks for a longer one, the
	// error is returned at once.
	MaxDelay time.Duration
	// OnRetry, when set, is called before each wait. The wait still ends
	// Delay after the call, however long OnRetry takes, so it may block to
	// count the wait down.
	OnRetry func(RetryEvent)
}

RetryPolicy says how a chat request that failed before any of its answer arrived is sent again: on 408, 429, 502, 503 and 504, and when the server could not be reached or dropped the connection before replying. A failure once the answer has started streaming is never retried, so an answer is never given twice.

func DefaultRetryPolicy added in v0.2.0

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy is what NewClient sets: 3 retries after 2s, 4s and 8s, waiting at most a minute.

type RunOptions added in v0.2.0

type RunOptions struct {
	Tools []Tool
	// Stream selects SSE streaming; OnDelta then sees every chunk, and
	// otherwise each whole response once.
	Stream bool
	// ConversationID continues a stored conversation (from an earlier
	// RunResult); empty starts a new one.
	ConversationID string
	OnDelta        StreamHandler
	OnToolCall     ToolCallHandler
	// OnToolResult is used instead of OnToolCall when set.
	OnToolResult ToolResultHandler
}

RunOptions configures Run.

type RunResult added in v0.2.0

type RunResult struct {
	// Messages is the input history with the assistant and tool turns
	// appended.
	Messages []Message
	// ConversationID identifies the server-side conversation; pass it back
	// in RunOptions to continue it.
	ConversationID string
	// Sources are the documents the answer drew on.
	Sources []Source
	// Model is the LLM that answered, when the server says.
	Model string
	// Usage is summed over every request of the run (one per tool round);
	// nil when the server reported none.
	Usage *Usage
}

RunResult is the outcome of Run.

type Source added in v0.2.0

type Source struct {
	Title    string `json:"title,omitempty"`
	Source   string `json:"source,omitempty"` // URL or path, when known
	Filename string `json:"filename,omitempty"`
	Text     string `json:"text,omitempty"`
}

Source is one retrieved document an answer drew on.

func ParseSources added in v0.2.0

func ParseSources(raw json.RawMessage) []Source

ParseSources decodes a raw "sources" value, skipping entries of an unexpected shape instead of failing.

type StreamHandler

type StreamHandler func(delta Delta, finishReason string)

StreamHandler is called once per SSE chunk as it arrives, with the chunk's delta and its finish_reason — the latter empty on every chunk but the last.

type StreamOptions added in v0.2.0

type StreamOptions struct {
	IncludeUsage bool `json:"include_usage"`
}

StreamOptions mirrors the OpenAI stream_options object.

type Tool

type Tool struct {
	Type     string       `json:"type"`
	Function ToolFunction `json:"function"`
}

type ToolCall

type ToolCall struct {
	Index    int          `json:"index,omitempty"`
	ID       string       `json:"id,omitempty"`
	Type     string       `json:"type,omitempty"`
	Function FunctionCall `json:"function"`
}

type ToolCallHandler

type ToolCallHandler func(tc ToolCall) string

ToolCallHandler is called when the model requests a tool call. It receives the tool call and should return the result string.

type ToolFunction

type ToolFunction struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Parameters  json.RawMessage `json:"parameters"`
}

type ToolResult added in v0.3.0

type ToolResult struct {
	Content string
	Parts   []ContentPart
}

ToolResult is what a tool call gives back to the model: its text, and Parts for images (ImagePart) the model should see. A DocsGPT server shows those images to the model rather than sending them as text.

type ToolResultHandler added in v0.3.0

type ToolResultHandler func(tc ToolCall) ToolResult

ToolResultHandler is a ToolCallHandler whose result may carry images.

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

Usage mirrors the OpenAI usage object returned by /v1/chat/completions.

Jump to

Keyboard shortcuts

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