Skip to content
50 changes: 50 additions & 0 deletions ai/component/agent/react/answer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package react

import (
"strings"

"github.com/firebase/genkit/go/ai"
)

// answerText returns the answer of a model response.
//
// Only the parts that genkit itself treats as text are joined. The reasoning
// of a thinking model is a reasoning part, and a response that carries
// nothing but the reasoning has no answer to deliver.
//
// genkit's Message.Text() returns the text of a single part without looking
// at its kind, so the reasoning of such a response would be delivered to the
// user as the answer. It would also bypass the capture policy, because the
// policy acts on the parts of a trace and never sees the answer.
func answerText(resp *ai.ModelResponse) string {
if resp == nil || resp.Message == nil {
return ""
}
var sb strings.Builder
for _, part := range resp.Message.Content {
if part == nil {
continue
}
if part.IsText() || part.IsData() {
sb.WriteString(part.Text)
}
}
return sb.String()
}
63 changes: 63 additions & 0 deletions ai/component/agent/react/answer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package react

import (
"testing"

"github.com/firebase/genkit/go/ai"
)

// TestAnswerTextIgnoresTheReasoning makes sure the reasoning of a thinking
// model is not delivered as the answer.
//
// genkit's Message.Text() returns the text of a single part without looking
// at its kind, so a response that carries nothing but the reasoning would be
// delivered to the user as the answer, and it would bypass the capture
// policy that is meant to keep the reasoning out of the trace.
func TestAnswerTextIgnoresTheReasoning(t *testing.T) {
response := &ai.ModelResponse{
Message: ai.NewMessage(ai.RoleModel, nil, ai.NewReasoningPart("chain of thought", nil)),
}
if got := answerText(response); got != "" {
t.Fatalf("answer of a reasoning only response = %q, want it to be empty", got)
}
}

// TestAnswerTextReturnsTheTextParts makes sure the answer of a response that
// carries a reasoning part as well is the text of the response.
func TestAnswerTextReturnsTheTextParts(t *testing.T) {
message := ai.NewMessage(ai.RoleModel, nil)
message.Content = append(message.Content, ai.NewReasoningPart("chain of thought", nil))
message.Content = append(message.Content, ai.NewTextPart("the answer"))
response := &ai.ModelResponse{Message: message}
if got := answerText(response); got != "the answer" {
t.Fatalf("answer = %q, want %q", got, "the answer")
}
}

// TestAnswerTextOfAnEmptyResponse makes sure a response without a message
// does not panic.
func TestAnswerTextOfAnEmptyResponse(t *testing.T) {
if got := answerText(nil); got != "" {
t.Fatalf("answer of a missing response = %q, want it to be empty", got)
}
if got := answerText(&ai.ModelResponse{}); got != "" {
t.Fatalf("answer of a response without a message = %q, want it to be empty", got)
}
}
22 changes: 22 additions & 0 deletions ai/component/agent/react/hook_content.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,21 @@ func genAIOutputMessages(output any) any {
return convertGenAIMessages([]*ai.Message{response.Message}, string(response.FinishReason))
}

// genAIAssistantMessages renders the agent's final answer as a GenAI assistant
// message, so the agent span can carry the answer the user actually receives.
func genAIAssistantMessages(answer string) any {
if answer == "" {
return nil
}
return convertGenAIMessages([]*ai.Message{ai.NewMessage(ai.RoleModel, nil, ai.NewTextPart(answer))}, "")
}

func convertGenAIMessages(messages []*ai.Message, finishReason string) []genAIMessage {
if len(messages) == 0 {
// An empty list would be exported as "[]", and a backend reads that
// as "there was no conversation". The attribute is left out instead.
return nil
}
converted := make([]genAIMessage, 0, len(messages))
for _, message := range messages {
if message == nil {
Expand All @@ -63,6 +77,14 @@ func convertGenAIMessages(messages []*ai.Message, finishReason string) []genAIMe
continue
case part.IsText():
parts = append(parts, genAIMessagePart{Type: "text", Content: part.Text})
case part.IsReasoning():
Comment thread
ambiguous-pointer marked this conversation as resolved.
Resolved
// The generative AI semantic conventions model the thinking
// content of a model as a reasoning part that only carries a
// type and a content field.
if part.Text == "" {
continue
}
parts = append(parts, genAIMessagePart{Type: "reasoning", Content: part.Text})
case part.IsToolRequest() && part.ToolRequest != nil:
parts = append(parts, genAIMessagePart{
Type: "tool_call",
Expand Down
70 changes: 70 additions & 0 deletions ai/component/agent/react/hook_content_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,73 @@ func TestGenAIOutputIncludesFinishReason(t *testing.T) {
t.Fatalf("output = %v, want finish_reason stop", decoded)
}
}

func TestGenAIInputIncludesReasoningPart(t *testing.T) {
messages := []*ai.Message{
ai.NewModelMessage(
ai.NewReasoningPart("thinking about the answer", []byte("signature")),
ai.NewTextPart("the answer"),
),
}
content, err := json.Marshal(genAIInputMessages(messages))
if err != nil {
t.Fatal(err)
}
var decoded []map[string]any
if err := json.Unmarshal(content, &decoded); err != nil {
t.Fatal(err)
}
parts := decoded[0]["parts"].([]any)
reasoning := parts[0].(map[string]any)
if reasoning["type"] != "reasoning" || reasoning["content"] != "thinking about the answer" {
t.Fatalf("reasoning part = %v", reasoning)
}
if len(reasoning) != 2 {
t.Fatalf("reasoning part = %v, want only a type and a content field", reasoning)
}
text := parts[1].(map[string]any)
if text["type"] != "text" || text["content"] != "the answer" {
t.Fatalf("text part = %v", text)
}
}

func TestGenAIOutputIncludesReasoningPart(t *testing.T) {
response := &ai.ModelResponse{
Message: ai.NewModelMessage(ai.NewReasoningPart("thinking", nil)),
FinishReason: ai.FinishReasonStop,
}
content, err := json.Marshal(genAIOutputMessages(response))
if err != nil {
t.Fatal(err)
}
var decoded []map[string]any
if err := json.Unmarshal(content, &decoded); err != nil {
t.Fatal(err)
}
parts := decoded[0]["parts"].([]any)
reasoning := parts[0].(map[string]any)
if reasoning["type"] != "reasoning" || reasoning["content"] != "thinking" {
t.Fatalf("reasoning part = %v", reasoning)
}
}

func TestGenAIInputSkipsEmptyReasoningPart(t *testing.T) {
messages := []*ai.Message{
ai.NewModelMessage(
ai.NewReasoningPart("", nil),
ai.NewTextPart("the answer"),
),
}
content, err := json.Marshal(genAIInputMessages(messages))
if err != nil {
t.Fatal(err)
}
var decoded []map[string]any
if err := json.Unmarshal(content, &decoded); err != nil {
t.Fatal(err)
}
parts := decoded[0]["parts"].([]any)
if len(parts) != 1 || parts[0].(map[string]any)["type"] != "text" {
t.Fatalf("parts = %v, want only the text part", parts)
}
}
10 changes: 9 additions & 1 deletion ai/component/agent/react/hook_lifecycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,15 @@ type interactionTrace struct {
FallbackUsed bool
FallbackReason string
Degraded bool
FinalAnswer string
// Conversation is the message window the last model call saw, and Answer
// is the final answer streamed to the user. Both are only attached to the
// agent span when a content-capturing hook asks for them.
Conversation []*ai.Message
Answer string
// FinalAnswer is the answer recorded for the interaction itself. It is
// set before the delivery, so it also covers an answer whose persistence
// failed and which therefore never reached the user.
FinalAnswer string
}

func emitStageEnd(s *interactionTrace, ctx context.Context, startedAt time.Time, err error) {
Expand Down
20 changes: 16 additions & 4 deletions ai/component/agent/react/react.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,10 +215,22 @@ func (ra *ReActAgent) Interact(parent context.Context, input *schema.UserInput,
StartedAt: interactionStartedAt,
EndedAt: endedAt,
}
if interactionState != nil && interactionState.Usage != nil {
endState.InputTokens = interactionState.Usage.InputTokens
endState.OutputTokens = interactionState.Usage.OutputTokens
endState.TotalTokens = interactionState.Usage.TotalTokens
if interactionState != nil {
// The agent span closes here, so this is the only point where
// the whole conversation and the final answer are both known.
// Backends read the trace input and output from the trace root,
// so they are attached to the span that closes it.
endState = withHookInput(ra.hookManager, hooks.EventInteractionEnd, "", endState, func() any {
return genAIInputMessages(interactionState.Conversation)
})
endState = withHookOutput(ra.hookManager, hooks.EventInteractionEnd, "", endState, func() any {
return genAIAssistantMessages(interactionState.Answer)
})
if interactionState.Usage != nil {
endState.InputTokens = interactionState.Usage.InputTokens
endState.OutputTokens = interactionState.Usage.OutputTokens
endState.TotalTokens = interactionState.Usage.TotalTokens
}
}
emitHook(ra.hookManager, interactionCtx, endState)
chans.Close()
Expand Down
15 changes: 13 additions & 2 deletions ai/component/agent/react/steps.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,11 @@ func (ra *ReActAgent) runIteration(ctx context.Context, chans *agent.Channels, h
} else {
messages = history.WindowMemory(s.Session)
}
// The agent span reports the conversation this call worked on, so the
// trace root shows the turn instead of an empty trace.
s.Conversation = messages
// The model call receives an ephemeral sanitized view of the messages.
// The canonical messages are never changed by it.
modelMessages, err := modelInputView(messages)
if err != nil {
return false, err
Expand All @@ -167,7 +172,7 @@ func (ra *ReActAgent) runIteration(ctx context.Context, chans *agent.Channels, h
lctx, cancel := withTimeout(ctx, ra.callTimeout)
defer cancel()
return executeModelCall(lctx, s, prompt, modelMessages, func(resp *ai.ModelResponse, err error) {
if err == nil && forceAnswer && resp.Text() == "" {
if err == nil && forceAnswer && answerText(resp) == "" {
s.FallbackUsed = true
s.FallbackReason = hooks.FallbackReasonEmptyResponse
}
Expand All @@ -192,7 +197,7 @@ func (ra *ReActAgent) runIteration(ctx context.Context, chans *agent.Channels, h
return false, nil
}
}
answer := resp.Text()
answer := answerText(resp)
if answer == "" {
if !forceAnswer {
runtime.GetLogger().Warn("react: empty model response, retrying", "iteration", s.Iteration)
Expand All @@ -205,6 +210,12 @@ func (ra *ReActAgent) runIteration(ctx context.Context, chans *agent.Channels, h
if err := ra.finish(ctx, chans, history, s.Session, turnID, answer); err != nil {
return false, err
}
// The answer is recorded only once it has been delivered. finish persists
// it and streams it to the user; when the persistence fails the
// interaction ends in an error and the user never receives the answer, so
// recording it as the interaction output would put a delivered answer in
// the trace that the user never saw.
s.Answer = answer
return true, nil
}

Expand Down
Loading