Purpose
Theopenai package is a small client plus a few data structures for chat completions and streamed deltas.
Client construction
Create a client with:- base URL:
https://api.openai.com/v1 - request timeout on the default client: 5 minutes
Request methods
CreateChatCompletion
Sends a non-streaming POST request to:
model or messages are missing.
StreamChatCompletion
Also posts to /chat/completions, but forces stream=true, requests text/event-stream, and returns a channel of StreamEvent.
Each StreamEvent can contain:
Data: a parsed response chunkDone: true when[DONE]is receivedRaw: the raw payload bytesError: a parse or scan error
Extra-field preservation
The package is intentionally tolerant of provider-specific fields.ChatCompletionRequest.Extrais merged into outbound JSON.Message.Extra,ToolCall.Extra, andChatCompletionChoice.Extrapreserve unknown inbound fields.ChatCompletionResponse.Rawstores raw JSON fragments by top-level key.
Stream accumulation
ChatCompletionAccumulator merges partial deltas into full choices. In particular, it:
- concatenates text content
- merges partial tool calls by index
- stitches fragmented tool-call argument strings together
- preserves extra fields and logprobs
- preserves structured content when no text concatenation is possible
loop.RunLoop relies on before executing tools.
Helper constructors
Use:openai.SystemMessage(...)openai.UserMessage(...)openai.ToolMessage(...)
openai.MessageText(...) when you expect plain string content and want the helper’s type assertion behavior.
Error model
Non-2xx API responses return*openai.APIError, which includes:
StatusCodeMessageBody