fix(agent): honor suggested-questions limit parameter

Treat limit as the authoritative upper bound instead of clamping it down
to the agent's Starters.Count, so ?limit=N no longer always returns 6.

Fixes #2238
This commit is contained in:
Jack Wang
2026-07-23 21:23:31 +08:00
committed by lyingbug
parent e0b6a71503
commit 43839f7830
10 changed files with 152 additions and 19 deletions
+4 -2
View File
@@ -225,9 +225,11 @@ export async function getEmbedChunkById(channelId: string, token: string, chunkI
)
}
export async function getEmbedSuggestedQuestions(channelId: string, token: string, limit = 6) {
export async function getEmbedSuggestedQuestions(channelId: string, token: string, limit?: number) {
// Omit limit to let the channel agent's configured starter count apply.
const qs = typeof limit === 'number' && limit > 0 ? `?limit=${limit}` : ''
return get<{ success: boolean; data: { questions: SuggestedQuestion[] } }>(
`/api/v1/embed/${channelId}/suggested-questions?limit=${limit}`,
`/api/v1/embed/${channelId}/suggested-questions${qs}`,
{ headers: { Authorization: `Embed ${token}` } },
)
}
+6 -2
View File
@@ -418,8 +418,12 @@ export const useSettingsStore = defineStore("settings", {
return this.settings.selectedFiles || [];
},
/** Scope for suggested-questions API (KB / file / tag @mentions). */
getSuggestedQuestionsParams(limit = 6) {
/**
* Scope for suggested-questions API (KB / file / tag @mentions).
* Leave `limit` undefined to let the backend apply the agent's configured
* starter count; pass a number only to request a specific count.
*/
getSuggestedQuestionsParams(limit?: number) {
const selectedKBs = this.getSelectedKnowledgeBases();
const selectedFiles = this.getSelectedFiles();
const tags = this.settings.selectedTags || [];
+1 -1
View File
@@ -314,7 +314,7 @@ const fetchSuggestedQuestions = async () => {
try {
const agentId = useSettingsStoreInstance.selectedAgentId;
if (!agentId) return;
const res = await getSuggestedQuestions(agentId, useSettingsStoreInstance.getSuggestedQuestionsParams(6));
const res = await getSuggestedQuestions(agentId, useSettingsStoreInstance.getSuggestedQuestionsParams());
if (fetchId === suggestedQuestionsFetchId) {
suggestedQuestions.value = res?.data?.questions || [];
}
+1 -1
View File
@@ -139,7 +139,7 @@ const fetchSuggestedQuestions = async () => {
try {
const agentId = settingsStore.selectedAgentId;
if (!agentId) return;
const res = await getSuggestedQuestions(agentId, settingsStore.getSuggestedQuestionsParams(6));
const res = await getSuggestedQuestions(agentId, settingsStore.getSuggestedQuestionsParams());
if (fetchId === suggestedQuestionsFetchId) {
sqCardsRevealed.value = false;
sqRenderKey.value++;
+1 -1
View File
@@ -315,7 +315,7 @@ const fetchSuggestedQuestions = async () => {
}
suggestedLoading.value = true
try {
const res = await getEmbedSuggestedQuestions(props.channelId, props.token, 6)
const res = await getEmbedSuggestedQuestions(props.channelId, props.token)
suggestedQuestions.value = res?.data?.questions || []
} catch {
suggestedQuestions.value = []
+23 -3
View File
@@ -23,6 +23,16 @@ var (
ErrAgentNameRequired = errors.New("agent name is required")
)
const (
// suggestionDefaultLimit is the fallback count when neither the caller nor
// the agent configuration specifies how many suggestions to return.
suggestionDefaultLimit = 6
// suggestionMaxLimit caps how many suggestions a single request may ask for.
// It bounds the downstream candidate pool (limit*5) so an oversized limit
// cannot turn into an unbounded chunk query.
suggestionMaxLimit = 30
)
// customAgentService implements the CustomAgentService interface
type customAgentService struct {
repo interfaces.CustomAgentRepository
@@ -497,8 +507,15 @@ func (s *customAgentService) getSuggestedQuestions(
limit int,
includeCurated bool,
) ([]types.SuggestedQuestion, error) {
if limit <= 0 {
limit = 6
// A non-positive limit means "unspecified": fall back to the agent's
// configured Starters.Count (below) or the default. An explicit limit is
// authoritative and only bounded by the safety cap.
limitProvided := limit > 0
if !limitProvided {
limit = suggestionDefaultLimit
}
if limit > suggestionMaxLimit {
limit = suggestionMaxLimit
}
if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, kbIDs, knowledgeIDs); err != nil {
@@ -529,7 +546,10 @@ func (s *customAgentService) getSuggestedQuestions(
if suggestionConfig == nil || !suggestionConfig.Starters.Enabled {
return []types.SuggestedQuestion{}, nil
}
if limit > suggestionConfig.Starters.Count {
// Starters.Count is the agent-author default, applied only when the
// caller did not request a specific limit. An explicit limit stays
// authoritative so ?limit=N actually changes how many are returned.
if !limitProvided && suggestionConfig.Starters.Count > 0 {
limit = suggestionConfig.Starters.Count
}
starterMode = suggestionConfig.Starters.Mode
@@ -0,0 +1,103 @@
package service
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// suggestionLimitAgentRepo returns a single curated-starter agent so the
// suggestion path resolves without touching chunk/KB repositories.
type suggestionLimitAgentRepo struct {
interfaces.CustomAgentRepository
agent *types.CustomAgent
}
func (r *suggestionLimitAgentRepo) GetAgentByID(
_ context.Context, _ string, _ uint64,
) (*types.CustomAgent, error) {
return r.agent, nil
}
func newCuratedStarterAgent(count int, items []string) *types.CustomAgent {
return &types.CustomAgent{
ID: "agent-1",
TenantID: 1,
Config: types.CustomAgentConfig{
QuestionSuggestions: &types.QuestionSuggestionConfig{
Starters: types.StarterSuggestionConfig{
Enabled: true,
Mode: types.SuggestionModeCurated,
Count: count,
Items: items,
},
},
},
}
}
// TestGetSuggestedQuestions_ExplicitLimitOverridesStarterCount is the
// regression test for issue #2238: an explicit limit must be honored instead
// of being clamped down to the agent's configured Starters.Count.
func TestGetSuggestedQuestions_ExplicitLimitOverridesStarterCount(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
items := []string{"q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10"}
svc := &customAgentService{
repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(6, items)},
}
got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 10)
require.NoError(t, err)
// Before the fix limit was clamped to Starters.Count (6); now the explicit
// request of 10 is honored.
assert.Len(t, got, 10)
}
// TestGetSuggestedQuestions_SmallerLimitStillHonored guards the other
// direction: a limit below Starters.Count must also take effect.
func TestGetSuggestedQuestions_SmallerLimitStillHonored(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
items := []string{"q1", "q2", "q3", "q4", "q5", "q6"}
svc := &customAgentService{
repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(6, items)},
}
got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 2)
require.NoError(t, err)
assert.Len(t, got, 2)
}
// TestGetSuggestedQuestions_UnspecifiedLimitFallsBackToStarterCount confirms
// that omitting the limit (<= 0) still uses the agent's configured count.
func TestGetSuggestedQuestions_UnspecifiedLimitFallsBackToStarterCount(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
items := []string{"q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8"}
svc := &customAgentService{
repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(4, items)},
}
got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 0)
require.NoError(t, err)
assert.Len(t, got, 4)
}
// TestGetSuggestedQuestions_LimitBoundedByMax ensures an oversized limit is
// capped so it cannot inflate the downstream candidate pool without bound.
func TestGetSuggestedQuestions_LimitBoundedByMax(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
items := make([]string, 0, 100)
for i := 0; i < 100; i++ {
items = append(items, "q"+string(rune('A'+i%26))+string(rune('0'+i/26)))
}
svc := &customAgentService{
repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(6, items)},
}
got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 999)
require.NoError(t, err)
assert.Len(t, got, suggestionMaxLimit)
}
@@ -322,9 +322,8 @@ func (s *embedChannelService) SuggestedQuestions(
if ch == nil || !ch.ShowSuggestedQuestions {
return nil, nil
}
if limit <= 0 {
limit = 6
}
// A non-positive limit is forwarded as "unspecified" so GetSuggestedQuestions
// falls back to the agent's configured starter count rather than a fixed 6.
kbIDs := s.resolveKnowledgeBaseIDs(ctx, ch)
return s.agentService.GetSuggestedQuestions(ctx, ch.AgentID, kbIDs, nil, nil, limit)
}
+5 -2
View File
@@ -563,7 +563,7 @@ func (h *CustomAgentHandler) GetAgentTypePresets(c *gin.Context) {
// @Param knowledge_base_ids query string false "知识库ID列表(逗号分隔),覆盖智能体默认配置"
// @Param knowledge_ids query string false "知识ID列表(逗号分隔),限定到具体文档"
// @Param tag_scopes query string false "带知识库归属的标签范围(JSON)"
// @Param limit query int false "返回数量上限(默认6)"
// @Param limit query int false "返回数量上限(未传时使用智能体配置的开场问题数量,最大30)"
// @Success 200 {object} map[string]interface{} "推荐问题列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "智能体不存在"
@@ -608,7 +608,10 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
}
}
limit := 6
// limit == 0 signals "unspecified" so the service falls back to the agent's
// configured starter count. A provided value is passed through unchanged and
// bounded by the service's safety cap.
limit := 0
if limitStr := c.Query("limit"); limitStr != "" {
if parsed, err := strconv.Atoi(limitStr); err == nil && parsed > 0 {
limit = parsed
+6 -4
View File
@@ -382,13 +382,15 @@ func (h *EmbedChannelHandler) GetEmbedSuggestedQuestions(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"questions": []types.SuggestedQuestion{}}})
return
}
limit := 6
// limit == 0 signals "unspecified" so the channel agent's starter count
// applies. A provided value is honored up to the embed cap.
limit := 0
if raw := c.Query("limit"); raw != "" {
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
limit = n
}
if limit > 12 {
limit = 12
if limit > 12 {
limit = 12
}
}
}
questions, err := h.embedSvc.SuggestedQuestions(c.Request.Context(), ch, limit)