| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "reasonix/internal/provider" |
| 6 | "strings" |
| 7 | ) |
| 8 | |
| 9 | type reasoningStreamMeta struct { |
| 10 | signature, id, status string |
| 11 | complete bool |
| 12 | state provider.ReasoningState |
| 13 | blocks []provider.ThinkingBlock |
| 14 | } |
| 15 | |
| 16 | func (m *reasoningStreamMeta) ingest(chunk provider.Chunk, text *strings.Builder, limit int) { |
| 17 | if m.state == "" { |
| 18 | m.state = provider.ReasoningEmpty |
| 19 | } |
| 20 | if chunk.ReasoningState != "" && m.complete && (chunk.ReasoningState != provider.ReasoningEmpty || text.Len() == 0) { |
| 21 | m.state = chunk.ReasoningState |
| 22 | } |
| 23 | text.WriteString(chunk.Text) |
| 24 | if chunk.Signature != "" { |
| 25 | m.signature = chunk.Signature |
| 26 | } |
| 27 | if chunk.ReasoningID != "" { |
| 28 | m.id = chunk.ReasoningID |
| 29 | } |
| 30 | if chunk.ReasoningStatus != "" { |
| 31 | m.status = chunk.ReasoningStatus |
| 32 | } |
| 33 | m.complete = boundReasoningReplay(text, chunk.Text, limit, m.complete) |
| 34 | if chunk.ThinkingBlock != nil && m.complete { |
| 35 | m.blocks = append(m.blocks, *chunk.ThinkingBlock) |
| 36 | } |
| 37 | bytes := 0 |
| 38 | for _, b := range m.blocks { |
| 39 | bytes += len(b.Thinking) + len(b.Signature) + len(b.Data) |
| 40 | } |
| 41 | if limit > 0 && bytes > limit { |
| 42 | m.complete = false |
| 43 | } |
| 44 | if !m.complete { |
| 45 | m.state = provider.ReasoningTruncated |
| 46 | m.blocks = nil |
| 47 | } else if text.Len() > 0 && m.state == provider.ReasoningEmpty { |
| 48 | m.state = provider.ReasoningComplete |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func (m *reasoningStreamMeta) ingestResponsesItem(items []json.RawMessage, raw json.RawMessage, limit int) []json.RawMessage { |
| 53 | if len(raw) == 0 || !m.complete && provider.IsReplayableResponsesReasoning(raw) { |
| 54 | return items |
| 55 | } |
| 56 | items = provider.UpsertResponsesItem(items, raw) |
| 57 | if !withinReasoningItemsLimit(items, limit) { |
| 58 | m.complete = false |
| 59 | m.state = provider.ReasoningTruncated |
| 60 | return nil |
| 61 | } |
| 62 | return items |
| 63 | } |
| 64 |