Skip to content

Commit 68fd12e

Browse files
authored
fix(go): fixed panic when stream value is nil (firebase#4102)
1 parent 192cd7c commit 68fd12e

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

go/ai/generate.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,6 +640,10 @@ func GenerateDataStream[Out any](ctx context.Context, r api.Registry, opts ...Ge
640640
yield(nil, err)
641641
return err
642642
}
643+
// Skip yielding if there's no parseable output yet (e.g., incomplete JSON during streaming).
644+
if base.IsNil(streamValue) {
645+
return nil
646+
}
643647
if !yield(&StreamValue[Out, Out]{Chunk: streamValue}, nil) {
644648
return errGenerateStop
645649
}

go/ai/prompt.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -950,6 +950,10 @@ func (dp *DataPrompt[In, Out]) ExecuteStream(ctx context.Context, input In, opts
950950
yield(nil, err)
951951
return err
952952
}
953+
// Skip yielding if there's no parseable output yet (e.g., incomplete JSON during streaming).
954+
if base.IsNil(streamValue) {
955+
return nil
956+
}
953957
if !yield(&StreamValue[Out, Out]{Chunk: streamValue}, nil) {
954958
return errGenerateStop
955959
}

go/internal/base/misc.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package base
1818

1919
import (
2020
"net/url"
21+
"reflect"
2122
)
2223

2324
// An Environment is the execution context in which the program is running.
@@ -38,3 +39,16 @@ func Zero[T any]() T {
3839
func Clean(id string) string {
3940
return url.PathEscape(id)
4041
}
42+
43+
// IsNil returns true if v is nil or a nil pointer/interface/map/slice/channel/func.
44+
func IsNil[T any](v T) bool {
45+
rv := reflect.ValueOf(v)
46+
switch rv.Kind() {
47+
case reflect.Invalid:
48+
return true
49+
case reflect.Ptr, reflect.Interface, reflect.Map, reflect.Slice, reflect.Chan, reflect.Func:
50+
return rv.IsNil()
51+
default:
52+
return false
53+
}
54+
}

0 commit comments

Comments
 (0)