feat(models): add max concurrency setting for background tasks

Introduce a new `max_concurrency` parameter to the model configuration, allowing control over the maximum number of concurrent background tasks (ingestion/enrichment) per model. This feature is applicable to chat, embedding, and VLM models, with a value of 0 or undefined falling back to the global default. Update UI components and localization files to support this new setting, ensuring a seamless user experience.
This commit is contained in:
wizardchen
2026-07-09 19:56:43 +08:00
committed by lyingbug
parent 200c344065
commit 20256287ec
17 changed files with 173 additions and 55 deletions
+22 -18
View File
@@ -99,13 +99,16 @@ type Chat interface {
}
type ChatConfig struct {
Source types.ModelSource
BaseURL string
ModelName string
APIKey string
ModelID string
Provider string
ExtraConfig map[string]string
Source types.ModelSource
BaseURL string
ModelName string
APIKey string
ModelID string
Provider string
// MaxConcurrency caps concurrent background calls to this model; 0 falls
// back to the process-wide default (see limiter.GateN).
MaxConcurrency int
ExtraConfig map[string]string
// CustomHeaders 允许在调用远程 OpenAI 兼容 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string
AppID string
@@ -121,16 +124,17 @@ func ConfigFromModel(m *types.Model, appID, appSecret string) *ChatConfig {
return nil
}
return &ChatConfig{
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
Provider: m.Parameters.Provider,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
Provider: m.Parameters.Provider,
MaxConcurrency: m.Parameters.MaxConcurrency,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
}
}
@@ -150,7 +154,7 @@ func NewChat(config *ChatConfig, ollamaService *ollama.OllamaService) (Chat, err
c, err = wrapChatLangfuse(c, err)
// Outermost: hold the per-model concurrency slot only around the real
// provider round-trip, so the wait is excluded from debug/langfuse timing.
return wrapChatConcurrency(c, err)
return wrapChatConcurrency(c, config.MaxConcurrency, err)
}
// NewRemoteChat 根据 provider 创建远程聊天实例。
+7 -4
View File
@@ -26,19 +26,22 @@ import (
// inner debug/langfuse timing.
type concurrencyChat struct {
inner Chat
// limit is this model's configured per-model background cap; 0 falls back
// to the process-wide default (see limiter.GateN).
limit int
}
func (w *concurrencyChat) GetModelName() string { return w.inner.GetModelName() }
func (w *concurrencyChat) GetModelID() string { return w.inner.GetModelID() }
func (w *concurrencyChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
release := limiter.Gate(ctx, w.inner.GetModelID())
release := limiter.GateN(ctx, w.inner.GetModelID(), w.limit)
defer release()
return w.inner.Chat(ctx, messages, opts)
}
func (w *concurrencyChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) {
release := limiter.Gate(ctx, w.inner.GetModelID())
release := limiter.GateN(ctx, w.inner.GetModelID(), w.limit)
ch, err := w.inner.ChatStream(ctx, messages, opts)
if err != nil || ch == nil {
release()
@@ -71,9 +74,9 @@ func (w *concurrencyChat) ChatStream(ctx context.Context, messages []Message, op
// wrapChatConcurrency installs the background concurrency governor as the
// outermost Chat decorator. It is always applied; when no limiter is installed
// or the call is interactive, the wrapper is a cheap passthrough.
func wrapChatConcurrency(c Chat, err error) (Chat, error) {
func wrapChatConcurrency(c Chat, limit int, err error) (Chat, error) {
if err != nil || c == nil {
return c, err
}
return &concurrencyChat{inner: c}, nil
return &concurrencyChat{inner: c, limit: limit}, nil
}
@@ -24,16 +24,19 @@ import (
// is acceptable for background ingestion.
type concurrencyEmbedder struct {
inner Embedder
// limit is this model's configured per-model background cap; 0 falls back
// to the process-wide default (see limiter.GateN).
limit int
}
func (w *concurrencyEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
release := limiter.Gate(ctx, w.inner.GetModelID())
release := limiter.GateN(ctx, w.inner.GetModelID(), w.limit)
defer release()
return w.inner.Embed(ctx, text)
}
func (w *concurrencyEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
release := limiter.Gate(ctx, w.inner.GetModelID())
release := limiter.GateN(ctx, w.inner.GetModelID(), w.limit)
defer release()
return w.inner.BatchEmbed(ctx, texts)
}
@@ -55,9 +58,9 @@ func (w *concurrencyEmbedder) GetModelID() string { return w.inner.GetModelID(
// wrapEmbeddingConcurrency installs the background concurrency governor directly
// around the real embedder. Always applied; a cheap passthrough when no limiter
// is installed or the call is interactive.
func wrapEmbeddingConcurrency(e Embedder) Embedder {
func wrapEmbeddingConcurrency(e Embedder, limit int) Embedder {
if e == nil {
return e
}
return &concurrencyEmbedder{inner: e}
return &concurrencyEmbedder{inner: e, limit: limit}
}
@@ -75,7 +75,7 @@ func TestConcurrencyEmbedderBackgroundGated(t *testing.T) {
limiter.SetGovernor(limiter.NewLocalLimiter(), 2)
f := newFakeEmbedder("emb-bg")
w := wrapEmbeddingConcurrency(f)
w := wrapEmbeddingConcurrency(f, 0)
ctx := types.WithBackgroundTask(context.Background())
const n = 5
@@ -110,6 +110,46 @@ func TestConcurrencyEmbedderBackgroundGated(t *testing.T) {
}
}
// TestConcurrencyEmbedderPerModelLimitOverridesDefault verifies a model's own
// configured limit takes precedence over the process-wide default.
func TestConcurrencyEmbedderPerModelLimitOverridesDefault(t *testing.T) {
t.Cleanup(func() { limiter.SetGovernor(nil, 0) })
// Global default is generous (10), but this model is pinned to 1.
limiter.SetGovernor(limiter.NewLocalLimiter(), 10)
f := newFakeEmbedder("emb-permodel")
w := wrapEmbeddingConcurrency(f, 1)
ctx := types.WithBackgroundTask(context.Background())
const n = 3
var wg sync.WaitGroup
for range n {
wg.Add(1)
go func() {
defer wg.Done()
_, _ = w.BatchEmbed(ctx, []string{"x"})
}()
}
// Only one may be in flight because the per-model limit is 1.
select {
case <-f.enter:
case <-time.After(2 * time.Second):
t.Fatalf("expected one call to enter, inFlight=%d", atomic.LoadInt32(&f.inFlight))
}
select {
case <-f.enter:
t.Fatal("a second call entered while per-model limit=1 slot was held")
case <-time.After(150 * time.Millisecond):
}
close(f.release)
wg.Wait()
if got := atomic.LoadInt32(&f.maxSeen); got > 1 {
t.Fatalf("max in-flight %d exceeded per-model limit 1", got)
}
}
// TestConcurrencyEmbedderInteractiveNotGated verifies interactive calls bypass
// the governor entirely, even at limit 1.
func TestConcurrencyEmbedderInteractiveNotGated(t *testing.T) {
@@ -117,7 +157,7 @@ func TestConcurrencyEmbedderInteractiveNotGated(t *testing.T) {
limiter.SetGovernor(limiter.NewLocalLimiter(), 1)
f := newFakeEmbedder("emb-interactive")
w := wrapEmbeddingConcurrency(f)
w := wrapEmbeddingConcurrency(f, 0)
ctx := context.Background() // no background marker
const n = 3
@@ -158,7 +198,7 @@ func TestConcurrencyEmbedderPoolFanOutGated(t *testing.T) {
f := newFakeEmbedder("emb-pool")
f.pooler = NewBatchEmbedder(pool)
w := wrapEmbeddingConcurrency(f)
w := wrapEmbeddingConcurrency(f, 0)
ctx := types.WithBackgroundTask(context.Background())
done := make(chan struct{})
+6 -2
View File
@@ -50,7 +50,10 @@ type Config struct {
SupportsDimensionOverride bool `json:"supports_dimension_override"`
ModelID string `json:"model_id"`
Provider string `json:"provider"`
ExtraConfig map[string]string `json:"extra_config"`
// MaxConcurrency caps concurrent background calls to this model; 0 falls
// back to the process-wide default (see limiter.GateN).
MaxConcurrency int `json:"max_concurrency"`
ExtraConfig map[string]string `json:"extra_config"`
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string `json:"custom_headers"`
AppID string
@@ -74,6 +77,7 @@ func ConfigFromModel(m *types.Model, appID, appSecret string) Config {
SupportsDimensionOverride: m.Parameters.EmbeddingParameters.SupportsDimensionOverride,
TruncatePromptTokens: m.Parameters.EmbeddingParameters.TruncatePromptTokens,
Provider: m.Parameters.Provider,
MaxConcurrency: m.Parameters.MaxConcurrency,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
@@ -93,7 +97,7 @@ func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.Oll
// Innermost: gate the real provider round-trips (including the per-sub-batch
// pool callbacks) before debug/langfuse wrap for logging/tracing. See
// concurrencyEmbedder for why this sits below the observability decorators.
e = wrapEmbeddingConcurrency(e)
e = wrapEmbeddingConcurrency(e, config.MaxConcurrency)
if logger.LLMDebugEnabled() {
e = &debugEmbedder{inner: e}
}
+18 -6
View File
@@ -28,16 +28,28 @@ func SetGovernor(l ModelConcurrencyLimiter, limit int) {
governorN = limit
}
// Gate acquires a per-model concurrency slot when the call is a background task
// (see types.IsBackgroundTask) and a governor is installed. It returns a
// release func that is ALWAYS safe to call: on the passthrough / fail-open
// paths it is a cheap no-op. The gate never blocks a call permanently — a
// limiter/Redis outage or a cancelled context fails open.
// Gate acquires a per-model concurrency slot using the process-wide default
// limit. Equivalent to GateN(ctx, modelID, 0).
func Gate(ctx context.Context, modelID string) func() {
return GateN(ctx, modelID, 0)
}
// GateN acquires a per-model concurrency slot when the call is a background task
// (see types.IsBackgroundTask) and a governor is installed. modelLimit is the
// model's own configured cap; a value <= 0 means "fall back to the process-wide
// default" (governorN). It returns a release func that is ALWAYS safe to call:
// on the passthrough / fail-open paths it is a cheap no-op. The gate never
// blocks a call permanently — a limiter/Redis outage or a cancelled context
// fails open.
func GateN(ctx context.Context, modelID string, modelLimit int) func() {
governorMu.RLock()
l, limit := governor, governorN
l, defaultLimit := governor, governorN
governorMu.RUnlock()
limit := modelLimit
if limit <= 0 {
limit = defaultLimit
}
if l == nil || limit <= 0 || !types.IsBackgroundTask(ctx) {
return noop
}
+6 -3
View File
@@ -13,13 +13,16 @@ import (
// worker) calls are throttled — see limiter.Gate / types.IsBackgroundTask.
type concurrencyVLM struct {
inner VLM
// limit is this model's configured per-model background cap; 0 falls back
// to the process-wide default (see limiter.GateN).
limit int
}
func (w *concurrencyVLM) GetModelName() string { return w.inner.GetModelName() }
func (w *concurrencyVLM) GetModelID() string { return w.inner.GetModelID() }
func (w *concurrencyVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error) {
release := limiter.Gate(ctx, w.inner.GetModelID())
release := limiter.GateN(ctx, w.inner.GetModelID(), w.limit)
defer release()
return w.inner.Predict(ctx, imgBytes, prompt)
}
@@ -27,9 +30,9 @@ func (w *concurrencyVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt
// wrapVLMConcurrency installs the background concurrency governor as the
// outermost VLM decorator. Always applied; a cheap passthrough when no limiter
// is installed or the call is interactive.
func wrapVLMConcurrency(v VLM, err error) (VLM, error) {
func wrapVLMConcurrency(v VLM, limit int, err error) (VLM, error) {
if err != nil || v == nil {
return v, err
}
return &concurrencyVLM{inner: v}, nil
return &concurrencyVLM{inner: v, limit: limit}, nil
}
+17 -13
View File
@@ -29,7 +29,10 @@ type Config struct {
ModelID string
InterfaceType string // "ollama" or "openai" (default)
Provider string
Extra map[string]any
// MaxConcurrency caps concurrent background calls to this model; 0 falls
// back to the process-wide default (see limiter.GateN).
MaxConcurrency int
Extra map[string]any
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string
AppID string
@@ -53,17 +56,18 @@ func ConfigFromModel(m *types.Model, appID, appSecret string) *Config {
}
}
return &Config{
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
InterfaceType: ifType,
Provider: m.Parameters.Provider,
Extra: stringMapToAnyMap(m.Parameters.ExtraConfig),
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
InterfaceType: ifType,
Provider: m.Parameters.Provider,
MaxConcurrency: m.Parameters.MaxConcurrency,
Extra: stringMapToAnyMap(m.Parameters.ExtraConfig),
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
}
}
@@ -90,7 +94,7 @@ func NewVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) {
v, err = wrapVLMLangfuse(v, nil)
// Outermost: hold the per-model concurrency slot only around the real
// provider round-trip, so the wait is excluded from debug/langfuse timing.
return wrapVLMConcurrency(v, err)
return wrapVLMConcurrency(v, config.MaxConcurrency, err)
}
func newVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) {