in message.go [2091:2150]
func (acc *Message) Accumulate(event MessageStreamEventUnion) error {
if acc == nil {
return fmt.Errorf("accumulate: cannot accumlate into nil Message")
}
switch event := event.AsAny().(type) {
case MessageStartEvent:
*acc = event.Message
case MessageDeltaEvent:
acc.StopReason = MessageStopReason(event.Delta.StopReason)
acc.StopSequence = event.Delta.StopSequence
acc.Usage.OutputTokens = event.Usage.OutputTokens
// acc.JSON.StopReason = event.Delta.JSON.StopReason
// acc.JSON.StopSequence = event.Delta.JSON.StopSequence
// acc.Usage.JSON.OutputTokens = event.Usage.JSON.OutputTokens
case MessageStopEvent:
accJson, err := json.Marshal(acc)
if err != nil {
return fmt.Errorf("error converting content block to JSON: %w", err)
}
acc.JSON.raw = string(accJson)
case ContentBlockStartEvent:
acc.Content = append(acc.Content, ContentBlockUnion{})
err := acc.Content[len(acc.Content)-1].UnmarshalJSON([]byte(event.ContentBlock.RawJSON()))
if err != nil {
return err
}
case ContentBlockDeltaEvent:
if len(acc.Content) == 0 {
return fmt.Errorf("received event of type %s but there was no content block", event.Type)
}
cb := &acc.Content[len(acc.Content)-1]
switch delta := event.Delta.AsAny().(type) {
case TextDelta:
cb.Text += delta.Text
case InputJSONDelta:
if string(cb.Input) == "{}" {
cb.Input = json.RawMessage{}
}
cb.Input = append(cb.Input, []byte(delta.PartialJSON)...)
case ThinkingDelta:
cb.Thinking += delta.Thinking
case SignatureDelta:
cb.Signature += delta.Signature
}
case ContentBlockStopEvent:
if len(acc.Content) == 0 {
return fmt.Errorf("received event of type %s but there was no content block", event.Type)
}
contentBlock := &acc.Content[len(acc.Content)-1]
cbJson, err := json.Marshal(contentBlock)
if err != nil {
return fmt.Errorf("error converting content block to JSON: %w", err)
}
contentBlock.JSON.raw = string(cbJson)
}
return nil
}