Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ai/component/agent/agent.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
type: agent
spec:
agent_type: "react"
model: "dashscope/qwen3.5-plus"
model: "dashscope/qwen3.7-max"
prompt_base_path: "./prompts"
max_iterations: 3 # Reduced from 10 to 3 for faster response
stage_channel_buffer_size: 5
Expand Down
73 changes: 73 additions & 0 deletions ai/component/agent/react/page_context.go

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussion:这里的Context命名感觉有点太宽泛了?在agent项目中,context一般指的是给到agent的上下文,这里其实特指从前端传过来的页面的上下文。

Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* 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 (
"context"
"encoding/json"
"fmt"

"dubbo-admin-ai/schema"

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

type currentPageContextKey struct{}

type currentPageContextEnvelope struct {
Kind string `json:"kind"`
Trust string `json:"trust"`
Context *schema.AIContextSnapshot `json:"context"`
}

func withCurrentPageContext(ctx context.Context, snapshot *schema.AIContextSnapshot) context.Context {
if snapshot == nil {
return ctx
}
return context.WithValue(ctx, currentPageContextKey{}, snapshot)
}

func injectCurrentPageContext(ctx context.Context, messages []*ai.Message) ([]*ai.Message, error) {
snapshot, ok := ctx.Value(currentPageContextKey{}).(*schema.AIContextSnapshot)
if !ok || snapshot == nil {
return messages, nil
}

payload, err := json.Marshal(currentPageContextEnvelope{
Kind: "page_context",
Trust: "untrusted_observation",
Context: snapshot,
})
if err != nil {
return nil, fmt.Errorf("failed to marshal current AI context: %w", err)
}

insertAt := len(messages)
for index := len(messages) - 1; index >= 0; index-- {
if messages[index].Role == ai.RoleUser {
insertAt = index
break
}
}

result := make([]*ai.Message, 0, len(messages)+1)
result = append(result, messages[:insertAt]...)
result = append(result, ai.NewUserMessage(ai.NewJSONPart(string(payload))))
result = append(result, messages[insertAt:]...)
return result, nil
}
106 changes: 106 additions & 0 deletions ai/component/agent/react/page_context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* 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 (
"context"
"encoding/json"
"strings"
"testing"

"dubbo-admin-ai/component/memory"
"dubbo-admin-ai/schema"

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

func TestInjectCurrentPageContext(t *testing.T) {
history := []*ai.Message{
ai.NewUserMessage(ai.NewTextPart("previous question")),
ai.NewModelMessage(ai.NewTextPart("previous answer")),
ai.NewUserMessage(ai.NewTextPart("current question")),
ai.NewModelMessage(ai.NewTextPart("current thought")),
}
snapshot := &schema.AIContextSnapshot{
Version: schema.AIContextVersion,
CapturedAt: "2026-07-19T13:00:00Z",
Global: schema.AIContextGlobal{Locale: "cn"},
Page: schema.AIContextPage{Path: "/home"},
Scope: schema.AIContextScope{Mesh: "nacos2.5"},
}

messages, err := injectCurrentPageContext(withCurrentPageContext(context.Background(), snapshot), history)
if err != nil {
t.Fatalf("injectCurrentPageContext() error = %v", err)
}
if len(messages) != 5 || len(history) != 4 {
t.Fatalf("message lengths = (%d, %d), want (5, 4)", len(messages), len(history))
}
contextMessage := messages[2]
if contextMessage.Role != ai.RoleUser || len(contextMessage.Content) != 1 {
t.Fatalf("unexpected context message: %#v", contextMessage)
}
if messages[3].Content[0].Text != "current question" || messages[4].Content[0].Text != "current thought" {
t.Fatalf("context changed the current turn order: %#v", messages)
}
var envelope currentPageContextEnvelope
if err := json.Unmarshal([]byte(contextMessage.Content[0].Text), &envelope); err != nil {
t.Fatalf("unmarshal context message: %v", err)
}
if envelope.Trust != "untrusted_observation" || envelope.Context.Scope.Mesh != "nacos2.5" {
t.Fatalf("unexpected context envelope: %#v", envelope)
}
}

func TestNewInteractionCarriesPageContext(t *testing.T) {
snapshot := &schema.AIContextSnapshot{
Version: schema.AIContextVersion,
Page: schema.AIContextPage{Path: "/home"},
Scope: schema.AIContextScope{Mesh: "nacos2.5"},
}
ra := &ReActAgent{memoryCtx: memory.NewMemoryContext(memory.ChatHistoryKey)}

ctx, _, history, err := ra.newInteraction(&schema.UserInput{
Content: "current question",
Context: snapshot,
}, "session")
if err != nil {
t.Fatalf("newInteraction() error = %v", err)
}
messages, err := injectCurrentPageContext(ctx, history.WindowMemory("session"))
if err != nil {
t.Fatalf("injectCurrentPageContext() error = %v", err)
}
if len(messages) != 2 || messages[1].Content[0].Text != "current question" {
t.Fatalf("unexpected interaction messages: %#v", messages)
}
}

func TestUserInputContextIsNotSerialized(t *testing.T) {
input := schema.UserInput{
Content: "hello",
Context: &schema.AIContextSnapshot{Version: schema.AIContextVersion},
}
data, err := json.Marshal(input)
if err != nil {
t.Fatalf("marshal UserInput: %v", err)
}
if strings.Contains(string(data), "context") {
t.Fatalf("serialized history contains page context: %s", data)
}
}
1 change: 1 addition & 0 deletions ai/component/agent/react/react.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ func (ra *ReActAgent) newInteraction(input *schema.UserInput, sessionID string)
history.AddHistory(sessionID, ai.NewUserMessage(ai.NewTextPart(input.Content)))

ctx := context.WithValue(ra.memoryCtx, memory.SessionIDKey, sessionID)
ctx = withCurrentPageContext(ctx, input.Context)
s := &state{Input: input, Session: sessionID, Usage: &ai.GenerationUsage{}}
return ctx, s, history, nil
}
Expand Down
12 changes: 10 additions & 2 deletions ai/component/agent/react/steps.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,16 @@ func (ra *ReActAgent) reasonActStep(prompt ai.Prompt, chans *agent.Channels, tim
if history.IsEmpty(sessionID) {
return false, fmt.Errorf("history is empty")
}
messages, err := injectCurrentPageContext(ctx, history.WindowMemory(sessionID))
if err != nil {
return false, err
}

// Only the model call is bound by the stage timeout; tool execution below
// runs on the original ctx so a slow reasoning step can't starve the tools
// it just asked for (which would otherwise fail hard on the shared deadline).
lctx, cancel := withTimeout(ctx, timeout)
resp, err := prompt.Execute(lctx, ai.WithMessages(history.WindowMemory(sessionID)...))
resp, err := prompt.Execute(lctx, ai.WithMessages(messages...))
cancel()
if err != nil {
return false, fmt.Errorf("failed to execute reasonAct prompt: %w", err)
Expand Down Expand Up @@ -150,12 +154,16 @@ func (ra *ReActAgent) observeStep(prompt ai.Prompt, chans *agent.Channels, timeo
if history.IsEmpty(sessionID) {
return false, fmt.Errorf("history is empty")
}
messages, err := injectCurrentPageContext(ctx, history.WindowMemory(sessionID))
if err != nil {
return false, err
}

obsCtx, cancel := withTimeout(ctx, timeout)
defer cancel()

var observation *schema.Observation
resp, err := prompt.Execute(obsCtx, ai.WithMessages(history.WindowMemory(sessionID)...))
resp, err := prompt.Execute(obsCtx, ai.WithMessages(messages...))
switch {
case err != nil && (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)):
runtime.GetLogger().Warn("Observe stage timeout, returning fallback response", "timeout", timeout)
Expand Down
8 changes: 7 additions & 1 deletion ai/component/models/models.yaml
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
type: models
spec:
default_model: "dashscope/qwen-max"
default_model: "dashscope/qwen3.7-max"
default_embedding: "dashscope/text-embedding-v4"
providers:
dashscope:
api_key: "${DASHSCOPE_API_KEY}"
base_url: "https://dashscope.aliyuncs.com/compatible-mode/v1"
models:
- name: "qwen3.7-max"
key: "qwen3.7-max"
type: "chat"
- name: "qwen3.7-plus"
key: "qwen3.7-plus"
type: "chat"
- name: "qwen-max"
key: "qwen-max"
type: "chat"
Expand Down
Loading