google/generative-ai-go

Null Pointer Exception in addToHistory

Closed this issue · 2 comments

A null pointer exception occurs in the addToHistory method of the ChatSession struct. This issue is triggered when the Content field of a Candidate struct's first element is nil, and the method attempts to access its Role property (c.Role).

//  github.com/google/generative-ai-go@v0.8.0/genai/client.go:183
func (iter *GenerateContentResponseIterator) Next() (*GenerateContentResponse, error) {
...
    resp, err := iter.sc.Recv()
    iter.err = err
    if err == io.EOF {
        if iter.cs != nil && iter.merged != nil {
            iter.cs.addToHistory(iter.merged.Candidates)
        }
        return nil, iterator.Done
    }
...
}

//  cloud.google.com/go/ai@v0.3.0/generativelanguage/apiv1/generative_client.go:746
func (c *streamGenerateContentRESTClient) Recv() (*generativelanguagepb.GenerateContentResponse, error) {
    if err := c.ctx.Err(); err != nil {
        defer c.stream.Close()
        return nil, err
    }
    msg, err := c.stream.Recv()    // msg.Candidates[0].Content is nil
    if err != nil {
        defer c.stream.Close()
        return nil, err
    }
    res := msg.(*generativelanguagepb.GenerateContentResponse)
    return res, nil
}

// Cause the following function to throw a NullPointerException
// github.com/google/generative-ai-go@v0.8.0/genai/chat.go:63
func (cs *ChatSession) addToHistory(cands []*Candidate) bool {
	if len(cands) > 0 {
		c := cands[0].Content // c is nil
		c.Role = roleModel 
		cs.History = append(cs.History, c)
		return true
	}
	return false
}

截屏2024-04-26 10 32 52

jba commented

This bug is fixed in the latest version of github.com/google/generative-ai-go (v0.11.0).
The fix for the vertex client is at googleapis/google-cloud-go#10057.

This bug is fixed in the latest version of github.com/google/generative-ai-go (v0.11.0). The fix for the vertex client is at googleapis/google-cloud-go#10057.

Thanks for the update. I've upgraded to the latest version and the issue has been resolved.