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 ¶
- func ImageType(data []byte) string
- func MimeType(filename string) string
- func Retryable(err error) bool
- type APIError
- type ChatRequest
- type ChatResponse
- type Choice
- type Client
- func (c *Client) Models(ctx context.Context) ([]Model, error)
- func (c *Client) Run(ctx context.Context, messages []Message, opts RunOptions) (*RunResult, error)
- func (c *Client) RunWithTools(ctx context.Context, messages []Message, tools []Tool, stream bool, ...) ([]Message, error)deprecated
- func (c *Client) Send(ctx context.Context, req ChatRequest) (*ChatResponse, error)
- func (c *Client) SendStream(ctx context.Context, req ChatRequest, onDelta StreamHandler) (*ChatResponse, error)
- type ContentPart
- type Delta
- type DocsGPTMeta
- type DocsGPTRequest
- type FileData
- type FunctionCall
- type ImageURL
- type Message
- type Model
- type RetryEvent
- type RetryPolicy
- type RunOptions
- type RunResult
- type Source
- type StreamHandler
- type StreamOptions
- type Tool
- type ToolCall
- type ToolCallHandler
- type ToolFunction
- type ToolResult
- type ToolResultHandler
- type Usage
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ImageType ¶ added in v0.2.0
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
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
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.
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 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 (*Client) Models ¶ added in v0.2.0
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
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 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 ImageURL ¶ added in v0.2.0
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
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
Text returns the message's text: Content, then the text parts, a line apart.
func (*Message) UnmarshalJSON ¶ added in v0.2.0
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 ¶
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 ¶
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.