Files
zeekayandClaude Opus 5 3cb580cc07 Go 1.27.1, and the code it can say more simply
Modules declare go 1.27.1 and the build images follow. go fix applied the
modernizers; the intPtr test helper had no callers left once new(expr) could
say it. omitzero is not applied, since it changes what the JSON says.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-16 19:25:34 -07:00

87 lines
2.2 KiB
Go

package ai
import (
"encoding/json"
"fmt"
)
// Response represents the API response from OpenAI/OpenRouter.
type Response struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []Choice `json:"choices"`
Usage *Usage `json:"usage,omitempty"`
}
// Choice represents a completion choice.
type Choice struct {
Index int `json:"index"`
Message Message `json:"message"`
FinishReason string `json:"finish_reason"`
}
// Usage represents token usage information.
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}
// StreamChunk represents a streaming response chunk.
type StreamChunk struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []StreamDelta `json:"choices"`
}
// StreamDelta represents a delta in a streaming response.
type StreamDelta struct {
Index int `json:"index"`
Delta MessageDelta `json:"delta"`
FinishReason *string `json:"finish_reason"`
}
// MessageDelta represents the incremental message content.
type MessageDelta struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
}
// ErrorResponse represents an error from the API.
type ErrorResponse struct {
Error ErrorDetail `json:"error"`
}
// ErrorDetail contains error information.
type ErrorDetail struct {
Message string `json:"message"`
Type string `json:"type"`
Code string `json:"code,omitempty"`
}
// Text returns the text content from the first choice.
func (r *Response) Text() string {
if len(r.Choices) == 0 {
return ""
}
return r.Choices[0].Message.Content
}
// JSON parses the response content as JSON into the provided destination.
func (r *Response) JSON(dest any) error {
content := r.Text()
if content == "" {
return fmt.Errorf("empty response content")
}
return json.Unmarshal([]byte(content), dest)
}
// Into is an alias for JSON for ergonomic usage.
func (r *Response) Into(dest any) error {
return r.JSON(dest)
}