forked from zendev-sh/goai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject.go
More file actions
265 lines (227 loc) · 6.27 KB
/
Copy pathobject.go
File metadata and controls
265 lines (227 loc) · 6.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package goai
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/zendev-sh/goai/provider"
)
// ObjectResult is the final result of a structured output generation.
type ObjectResult[T any] struct {
// Object is the parsed structured output.
Object T
// Usage tracks token consumption.
Usage provider.Usage
// FinishReason indicates why generation stopped.
FinishReason provider.FinishReason
// Response contains provider metadata (ID, Model).
Response provider.ResponseMetadata
}
// ObjectStream is a streaming structured output response.
type ObjectStream[T any] struct {
ctx context.Context
source <-chan provider.StreamChunk
consumeOnce sync.Once
doneCh chan struct{}
timeoutCancel context.CancelFunc
// Channel returned by the first PartialObjectStream() call.
partialCh <-chan *T
// Accumulated state.
text strings.Builder
finishReason provider.FinishReason
usage provider.Usage
response provider.ResponseMetadata
finalObject *T
parseErr error
}
func newObjectStream[T any](ctx context.Context, source <-chan provider.StreamChunk) *ObjectStream[T] {
return &ObjectStream[T]{
ctx: ctx,
source: source,
doneCh: make(chan struct{}),
}
}
// PartialObjectStream returns a channel that emits partial objects as JSON accumulates.
// Each emitted value has progressively more fields populated.
// Mutually exclusive with Result() -- only call one consumption method first.
func (os *ObjectStream[T]) PartialObjectStream() <-chan *T {
ch := make(chan *T, 64)
os.consumeOnce.Do(func() {
os.partialCh = ch
go os.consume(ch)
})
if os.partialCh != nil {
return os.partialCh
}
// Called after Result() consumed the source -- return closed channel.
close(ch)
return ch
}
// Result blocks until the stream completes and returns the final validated object.
// Returns an error if JSON parsing of the accumulated text fails.
func (os *ObjectStream[T]) Result() (*ObjectResult[T], error) {
os.consumeOnce.Do(func() {
go os.consume(nil)
})
<-os.doneCh
if os.parseErr != nil {
return nil, fmt.Errorf("parsing structured output: %w (raw: %s)", os.parseErr, truncate(os.text.String(), 200))
}
if os.finalObject == nil {
return &ObjectResult[T]{
Usage: os.usage,
FinishReason: os.finishReason,
Response: os.response,
}, nil
}
return &ObjectResult[T]{
Object: *os.finalObject,
Usage: os.usage,
FinishReason: os.finishReason,
Response: os.response,
}, nil
}
func (os *ObjectStream[T]) consume(partialOut chan<- *T) {
defer close(os.doneCh)
if os.timeoutCancel != nil {
defer os.timeoutCancel()
}
if partialOut != nil {
defer close(partialOut)
}
for chunk := range os.source {
switch chunk.Type {
case provider.ChunkText:
os.text.WriteString(chunk.Text)
// Try to parse partial JSON.
if partialOut != nil {
if partial, err := parsePartialJSON[T](os.text.String()); err == nil {
select {
case partialOut <- partial:
case <-os.ctx.Done():
return
}
}
}
case provider.ChunkFinish:
os.finishReason = chunk.FinishReason
os.usage = chunk.Usage
os.response = chunk.Response
}
}
// Parse final result.
text := os.text.String()
if text != "" {
var obj T
if err := json.Unmarshal([]byte(text), &obj); err != nil {
os.parseErr = err
} else {
os.finalObject = &obj
}
}
}
// GenerateObject performs a non-streaming structured output generation.
// The schema is auto-generated from T, or can be overridden with WithExplicitSchema.
func GenerateObject[T any](ctx context.Context, model provider.LanguageModel, opts ...Option) (*ObjectResult[T], error) {
o := applyOptions(opts...)
if o.Timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, o.Timeout)
defer cancel()
}
// Resolve schema.
schema := o.ExplicitSchema
if schema == nil {
schema = SchemaFrom[T]()
}
schemaName := cmp.Or(o.SchemaName, "response")
params := buildParams(o)
params.ResponseFormat = &provider.ResponseFormat{
Name: schemaName,
Schema: schema,
}
if o.OnRequest != nil {
o.OnRequest(RequestInfo{
Model: model.ModelID(),
MessageCount: len(params.Messages),
ToolCount: len(params.Tools),
Timestamp: time.Now(),
})
}
start := time.Now()
result, err := withRetry(ctx, o.MaxRetries, func() (*provider.GenerateResult, error) {
return model.DoGenerate(ctx, params)
})
if o.OnResponse != nil {
info := ResponseInfo{Latency: time.Since(start), Error: err}
if err == nil {
info.Usage = result.Usage
info.FinishReason = result.FinishReason
}
var apiErr *APIError
if errors.As(err, &apiErr) {
info.StatusCode = apiErr.StatusCode
}
o.OnResponse(info)
}
if err != nil {
return nil, err
}
// Parse the JSON response into T.
var obj T
text := result.Text
if text == "" {
return nil, fmt.Errorf("goai: empty response from model")
}
if err := json.Unmarshal([]byte(text), &obj); err != nil {
return nil, fmt.Errorf("parsing structured output: %w (raw: %s)", err, truncate(text, 200))
}
return &ObjectResult[T]{
Object: obj,
Usage: result.Usage,
FinishReason: result.FinishReason,
Response: result.Response,
}, nil
}
// StreamObject performs a streaming structured output generation.
// Returns an ObjectStream that emits progressively populated partial objects.
func StreamObject[T any](ctx context.Context, model provider.LanguageModel, opts ...Option) (*ObjectStream[T], error) {
o := applyOptions(opts...)
var timeoutCancel context.CancelFunc
if o.Timeout > 0 {
ctx, timeoutCancel = context.WithTimeout(ctx, o.Timeout)
}
// Resolve schema.
schema := o.ExplicitSchema
if schema == nil {
schema = SchemaFrom[T]()
}
schemaName := cmp.Or(o.SchemaName, "response")
params := buildParams(o)
params.ResponseFormat = &provider.ResponseFormat{
Name: schemaName,
Schema: schema,
}
result, err := withRetry(ctx, o.MaxRetries, func() (*provider.StreamResult, error) {
return model.DoStream(ctx, params)
})
if err != nil {
if timeoutCancel != nil {
timeoutCancel()
}
return nil, err
}
os := newObjectStream[T](ctx, result.Stream)
os.timeoutCancel = timeoutCancel
return os, nil
}
func truncate(s string, max int) string {
if len(s) <= max {
return s
}
return s[:max] + "..."
}