feat(provider): add pipeline reasoning controls

This commit is contained in:
fdc310
2026-08-01 01:25:20 +08:00
parent e3832ca536
commit d40348add3
31 changed files with 2361 additions and 74 deletions
+71 -16
View File
@@ -9,6 +9,7 @@ from ....core import app
from ....entity.persistence import model as persistence_model
from ....entity.persistence import pipeline as persistence_pipeline
from ....provider.modelmgr import requester as model_requester
from ....provider.modelmgr import reasoning as model_reasoning
from ....workspace.errors import WorkspaceNotFoundError
from .secrets import mask_secret_value, redact_secrets, restore_secret_placeholders
from .tenant import TenantContext, require_workspace_uuid, scope_statement
@@ -54,6 +55,53 @@ def _redact_model_secrets(model_data: dict) -> dict:
return redacted
def _normalize_llm_reasoning(model_data: dict) -> None:
model_data['reasoning_config'] = model_reasoning.validate_reasoning_config(
model_data.get('reasoning_config'),
model_data.get('abilities'),
model_data.get('extra_args'),
)
def _validate_llm_reasoning_capability(
model_entity: persistence_model.LLMModel,
runtime_provider: model_requester.RuntimeProvider,
) -> None:
config = model_reasoning.normalize_reasoning_config(model_entity.reasoning_config)
if config['level'] == 'provider_default':
return
runtime_model = model_requester.RuntimeLLMModel(
execution_context=runtime_provider.execution_context,
model_entity=model_entity,
provider=runtime_provider,
)
capabilities = runtime_provider.requester.get_reasoning_capabilities(runtime_model)
model_reasoning.validate_reasoning_capabilities(config, capabilities, model_entity.name)
def _reasoning_capabilities(ap: app.Application, model: persistence_model.LLMModel) -> dict:
model_mgr = getattr(ap, 'model_mgr', None)
runtime_models = getattr(model_mgr, 'llm_model_dict', {}) if model_mgr is not None else {}
for runtime_model in runtime_models.values():
if (
runtime_model.model_entity.uuid == model.uuid
and runtime_model.model_entity.workspace_uuid == model.workspace_uuid
):
return runtime_model.provider.requester.get_reasoning_capabilities(runtime_model)
return model_reasoning.default_reasoning_capabilities(
supported='reasoning' in (model.abilities or []),
source='manual' if 'reasoning' in (model.abilities or []) else 'unknown',
)
def _serialize_llm_model(ap: app.Application, model: persistence_model.LLMModel) -> dict:
model_dict = ap.persistence_mgr.serialize_model(persistence_model.LLMModel, model)
model_dict['reasoning_config'] = model_reasoning.normalize_reasoning_config(model_dict.get('reasoning_config'))
model_dict['reasoning_capabilities'] = _reasoning_capabilities(ap, model)
return model_dict
async def _validate_provider_supports(
ap: app.Application,
context: TenantContext,
@@ -147,7 +195,7 @@ class LLMModelsService:
models_list = []
for model in models:
model_dict = self.ap.persistence_mgr.serialize_model(persistence_model.LLMModel, model)
model_dict = _serialize_llm_model(self.ap, model)
provider = providers.get(model.provider_uuid)
if provider:
provider_dict = self.ap.persistence_mgr.serialize_model(persistence_model.ModelProvider, provider)
@@ -178,7 +226,7 @@ class LLMModelsService:
)
)
models = result.all()
serialized = [self.ap.persistence_mgr.serialize_model(persistence_model.LLMModel, m) for m in models]
serialized = [_serialize_llm_model(self.ap, model) for model in models]
return serialized if include_secret else [_redact_model_secrets(model) for model in serialized]
async def create_llm_model(
@@ -214,13 +262,17 @@ class LLMModelsService:
await _require_workspace_provider(self.ap, context, model_data['provider_uuid'])
await _validate_provider_supports(self.ap, context, model_data['provider_uuid'], 'llm')
_normalize_llm_reasoning(model_data)
runtime_provider = await _require_runtime_provider(self.ap, context, model_data['provider_uuid'])
model_entity = persistence_model.LLMModel(**model_data)
_validate_llm_reasoning_capability(model_entity, runtime_provider)
await self.ap.persistence_mgr.execute_async(sqlalchemy.insert(persistence_model.LLMModel).values(**model_data))
runtime_provider = await _require_runtime_provider(self.ap, context, model_data['provider_uuid'])
runtime_llm_model = await self.ap.model_mgr.load_llm_model_with_provider(
context,
persistence_model.LLMModel(**model_data),
model_entity,
runtime_provider,
)
await self.ap.model_mgr.cache_llm_model(context, runtime_llm_model)
@@ -268,7 +320,7 @@ class LLMModelsService:
if model is None:
return None
model_dict = self.ap.persistence_mgr.serialize_model(persistence_model.LLMModel, model)
model_dict = _serialize_llm_model(self.ap, model)
# Get provider
provider_result = await self.ap.persistence_mgr.execute_async(
@@ -323,6 +375,18 @@ class LLMModelsService:
await _require_workspace_provider(self.ap, context, provider_uuid)
await _validate_provider_supports(self.ap, context, provider_uuid, 'llm')
merged_model_data = {
key: value
for key, value in {**existing_model, **model_data, 'provider_uuid': provider_uuid}.items()
if key not in {'provider', 'created_at', 'updated_at', 'reasoning_capabilities'}
}
_normalize_llm_reasoning(merged_model_data)
model_data['reasoning_config'] = merged_model_data['reasoning_config']
runtime_provider = await _require_runtime_provider(self.ap, context, provider_uuid)
model_entity = persistence_model.LLMModel(**_runtime_model_data(model_uuid, merged_model_data))
_validate_llm_reasoning_capability(model_entity, runtime_provider)
result = await self.ap.persistence_mgr.execute_async(
scope_statement(
sqlalchemy.update(persistence_model.LLMModel)
@@ -336,19 +400,9 @@ class LLMModelsService:
raise WorkspaceNotFoundError('Model not found')
await self.ap.model_mgr.remove_llm_model(context, model_uuid)
runtime_provider = await _require_runtime_provider(self.ap, context, provider_uuid)
runtime_llm_model = await self.ap.model_mgr.load_llm_model_with_provider(
context,
persistence_model.LLMModel(
**_runtime_model_data(
model_uuid,
{
key: value
for key, value in {**existing_model, **model_data, 'provider_uuid': provider_uuid}.items()
if key not in {'provider', 'created_at', 'updated_at'}
},
)
),
model_entity,
runtime_provider,
)
await self.ap.model_mgr.cache_llm_model(context, runtime_llm_model)
@@ -376,6 +430,7 @@ class LLMModelsService:
raise WorkspaceNotFoundError('Model not found')
runtime_llm_model = await self.ap.model_mgr.get_model_by_uuid(context, model_uuid)
else:
_normalize_llm_reasoning(model_data)
runtime_llm_model = await self.ap.model_mgr.init_temporary_runtime_llm_model(context, model_data)
extra_args = model_data.get('extra_args', {})
@@ -48,6 +48,12 @@ class LLMModel(Base):
provider_uuid = sqlalchemy.Column(sqlalchemy.String(255), nullable=False)
abilities = sqlalchemy.Column(sqlalchemy.JSON, nullable=False, default=[])
context_length = sqlalchemy.Column(sqlalchemy.Integer, nullable=True)
reasoning_config = sqlalchemy.Column(
sqlalchemy.JSON,
nullable=False,
default=lambda: {'level': 'provider_default'},
server_default=sqlalchemy.text('\'{"level":"provider_default"}\''),
)
extra_args = sqlalchemy.Column(sqlalchemy.JSON, nullable=False, default={})
prefered_ranking = sqlalchemy.Column(sqlalchemy.Integer, nullable=False, default=0)
created_at = sqlalchemy.Column(sqlalchemy.DateTime, nullable=False, server_default=sqlalchemy.func.now())
@@ -0,0 +1,57 @@
"""add llm reasoning config
Revision ID: 0018_llm_reasoning_config
Revises: 0017_oss_workspace_identity
Create Date: 2026-07-27
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = '0018_llm_reasoning_config'
down_revision = '0017_oss_workspace_identity'
branch_labels = None
depends_on = None
_LLM_MODELS = sa.table(
'llm_models',
sa.column('reasoning_config', sa.JSON()),
)
def upgrade() -> None:
conn = op.get_bind()
inspector = sa.inspect(conn)
if 'llm_models' not in inspector.get_table_names():
return
columns = {column['name'] for column in inspector.get_columns('llm_models')}
if 'reasoning_config' in columns:
return
op.add_column(
'llm_models',
sa.Column(
'reasoning_config',
sa.JSON(),
nullable=True,
server_default=sa.text('\'{"level":"provider_default"}\''),
),
)
conn.execute(_LLM_MODELS.update().values(reasoning_config={'level': 'provider_default'}))
with op.batch_alter_table('llm_models') as batch_op:
batch_op.alter_column('reasoning_config', existing_type=sa.JSON(), nullable=False)
def downgrade() -> None:
conn = op.get_bind()
inspector = sa.inspect(conn)
if 'llm_models' not in inspector.get_table_names():
return
columns = {column['name'] for column in inspector.get_columns('llm_models')}
if 'reasoning_config' in columns:
with op.batch_alter_table('llm_models') as batch_op:
batch_op.drop_column('reasoning_config')
@@ -649,6 +649,7 @@ class ModelManager:
provider_uuid=runtime_provider.provider_entity.uuid,
abilities=model_info.get('abilities', []),
context_length=model_info.get('context_length'),
reasoning_config=model_info.get('reasoning_config', {'level': 'provider_default'}),
extra_args=model_info.get('extra_args', {}),
)
return self._build_llm_model(execution_context, model_entity, runtime_provider)
@@ -0,0 +1,110 @@
from __future__ import annotations
import typing
ReasoningLevel = typing.Literal[
'provider_default',
'disabled',
'enabled',
'minimal',
'low',
'medium',
'high',
'xhigh',
'max',
]
REASONING_LEVELS: tuple[str, ...] = (
'provider_default',
'disabled',
'enabled',
'minimal',
'low',
'medium',
'high',
'xhigh',
'max',
)
DEFAULT_REASONING_CONFIG: dict[str, str] = {'level': 'provider_default'}
_CONFLICTING_TOP_LEVEL_ARGS = {'reasoning_effort', 'thinking', 'reasoning'}
_CONFLICTING_EXTRA_BODY_ARGS = {'thinking', 'enable_thinking', 'thinking_budget', 'reasoning'}
def normalize_reasoning_config(value: typing.Any) -> dict[str, str]:
"""Return the canonical model reasoning configuration."""
if value is None:
return dict(DEFAULT_REASONING_CONFIG)
if not isinstance(value, dict):
raise ValueError('reasoning_config must be an object')
unknown_fields = set(value) - {'level'}
if unknown_fields:
raise ValueError(f'Unsupported reasoning_config fields: {", ".join(sorted(unknown_fields))}')
level = value.get('level', 'provider_default')
if level not in REASONING_LEVELS:
raise ValueError(f'Unsupported reasoning level: {level}')
return {'level': typing.cast(str, level)}
def validate_reasoning_config(
value: typing.Any,
abilities: typing.Iterable[str] | None,
extra_args: typing.Any,
) -> dict[str, str]:
"""Validate a model-facing reasoning config and conflicting raw arguments."""
config = normalize_reasoning_config(value)
if config['level'] == 'provider_default':
return config
if 'reasoning' not in set(abilities or []):
raise ValueError('The reasoning ability must be enabled before selecting a reasoning level')
conflicts = find_reasoning_arg_conflicts(extra_args)
if conflicts:
raise ValueError('reasoning_config conflicts with advanced parameters: ' + ', '.join(conflicts))
return config
def find_reasoning_arg_conflicts(extra_args: typing.Any) -> list[str]:
if not isinstance(extra_args, dict):
return []
conflicts = [key for key in sorted(_CONFLICTING_TOP_LEVEL_ARGS) if key in extra_args]
extra_body = extra_args.get('extra_body')
if isinstance(extra_body, dict):
conflicts.extend(f'extra_body.{key}' for key in sorted(_CONFLICTING_EXTRA_BODY_ARGS) if key in extra_body)
return conflicts
def validate_reasoning_capabilities(
config: typing.Any,
capabilities: typing.Mapping[str, typing.Any],
model_name: str,
) -> None:
"""Ensure an explicit reasoning level can be honored by the requester."""
level = normalize_reasoning_config(config)['level']
if level == 'provider_default':
return
available_levels = capabilities.get('levels')
if not isinstance(available_levels, list):
available_levels = []
if capabilities.get('supported') is not True or level not in available_levels:
available_text = ', '.join(str(item) for item in available_levels) or 'provider_default'
raise ValueError(
f'Reasoning level "{level}" is not supported by model {model_name}. Available levels: {available_text}'
)
def default_reasoning_capabilities(
supported: bool = False,
source: str = 'unknown',
) -> dict[str, typing.Any]:
return {
'supported': supported,
'levels': ['provider_default'],
'source': source,
}
@@ -10,6 +10,7 @@ from ...entity.persistence import model as persistence_model
from ...workspace.errors import WorkspaceInvariantError
import langbot_plugin.api.entities.builtin.resource.tool as resource_tool
from . import token
from . import reasoning
import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query
import langbot_plugin.api.entities.builtin.provider.message as provider_message
@@ -377,11 +378,15 @@ class RuntimeLLMModel:
provider: RuntimeProvider
"""提供商实例"""
reasoning_config_override: dict[str, str] | None
"""Request-scoped reasoning policy supplied by the active pipeline."""
def __init__(
self,
execution_context: ExecutionContext,
model_entity: persistence_model.LLMModel,
provider: RuntimeProvider,
reasoning_config_override: dict[str, str] | None = None,
):
_ensure_same_execution_scope(provider.execution_context, execution_context, resource='LLM model')
if model_entity.workspace_uuid != execution_context.workspace_uuid:
@@ -391,6 +396,7 @@ class RuntimeLLMModel:
self.execution_context = execution_context
self.model_entity = model_entity
self.provider = provider
self.reasoning_config_override = reasoning_config_override
class RuntimeEmbeddingModel:
@@ -482,6 +488,13 @@ class ProviderAPIRequester(metaclass=abc.ABCMeta):
"""
raise NotImplementedError('This provider does not support model scanning')
def get_reasoning_capabilities(self, model: RuntimeLLMModel) -> dict[str, typing.Any]:
"""Return normalized reasoning controls supported by a model."""
return reasoning.default_reasoning_capabilities(
supported='reasoning' in (model.model_entity.abilities or []),
source='manual' if 'reasoning' in (model.model_entity.abilities or []) else 'unknown',
)
@abc.abstractmethod
async def invoke_llm(
self,
@@ -7,7 +7,7 @@ import typing
import litellm
from litellm import acompletion, aembedding, arerank
from .. import errors, requester
from .. import errors, reasoning, requester
from ....utils import httpclient
import langbot_plugin.api.entities.builtin.resource.tool as resource_tool
import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query
@@ -164,6 +164,19 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
_EMBEDDING_MODEL_HINTS = ('embedding', 'embed', 'bge-', 'e5-', 'm3e', 'gte-', 'text-embedding')
_RERANK_MODEL_HINTS = ('rerank', 're-rank', 're_rank')
_INFERRED_EFFORT_PROVIDERS = frozenset(
{
'anthropic',
'gemini',
'groq',
'mistral',
'openai',
'openrouter',
'together_ai',
'xai',
}
)
_INFERRED_TOGGLE_PROVIDERS = frozenset({'deepseek', 'ollama', 'volcengine'})
default_config: dict[str, typing.Any] = {
'base_url': '',
@@ -201,7 +214,10 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
return False
provider = self._get_custom_llm_provider()
candidates: list[tuple[str, str | None]] = [(model_name, provider)]
candidates: list[tuple[str, str | None]] = [
(candidate, None) for candidate in self._metadata_model_candidates(model_name)
]
candidates.append((model_name, provider))
litellm_model_name = self._build_litellm_model_name(model_name)
if litellm_model_name != model_name:
candidates.append((litellm_model_name, None))
@@ -268,6 +284,14 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
deduped_candidates.append(candidate)
return deduped_candidates
@staticmethod
def _metadata_model_candidates(model_name: str) -> list[str]:
"""Return known equivalent model IDs used only for LiteLLM metadata lookup."""
normalized_model_name = (model_name or '').lower()
if normalized_model_name.startswith('mimo-v2.5'):
return [f'openrouter/xiaomi/{normalized_model_name}']
return []
def _known_context_length_fallback(self, model_name: str) -> int | None:
normalized_model_name = (model_name or '').lower()
if normalized_model_name.startswith('deepseek-v4-'):
@@ -287,7 +311,8 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
if not callable(helper):
return self._known_context_length_fallback(model_name)
candidates = [model_name]
candidates = self._metadata_model_candidates(model_name)
candidates.append(model_name)
litellm_model_name = self._build_litellm_model_name(model_name)
if litellm_model_name != model_name:
candidates.append(litellm_model_name)
@@ -314,6 +339,142 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
def _supports_vision(self, model_name: str) -> bool:
return self._safe_litellm_bool_helper('supports_vision', model_name)
def _supports_reasoning(self, model_name: str) -> bool:
return self._safe_litellm_bool_helper('supports_reasoning', model_name)
def _reasoning_provider(self, model_name: str) -> str:
provider = (self._get_custom_llm_provider() or '').lower()
if provider:
return provider
normalized_name = (model_name or '').lower()
if '/' in normalized_name:
prefix = normalized_name.split('/', 1)[0]
if prefix in {
'anthropic',
'deepseek',
'gemini',
'groq',
'mistral',
'ollama',
'openai',
'openrouter',
'together_ai',
'volcengine',
'xai',
}:
return prefix
candidates = self._metadata_provider_candidates(model_name)
return candidates[0] if candidates else ''
def _safe_model_info(self, model_name: str) -> dict[str, typing.Any]:
helper = getattr(litellm, 'get_model_info', None)
if not callable(helper):
return {}
candidates = [
*self._metadata_model_candidates(model_name),
model_name,
self._build_litellm_model_name(model_name),
]
for candidate in candidates:
try:
info = helper(candidate)
except Exception:
continue
if isinstance(info, dict):
return info
model_dump = getattr(info, 'model_dump', None)
if callable(model_dump):
try:
dumped = model_dump()
if isinstance(dumped, dict):
return dumped
except Exception:
continue
return {}
def get_reasoning_capabilities(self, model: requester.RuntimeLLMModel) -> dict[str, typing.Any]:
model_name = model.model_entity.name
abilities = model.model_entity.abilities or []
detected = self._supports_reasoning(model_name)
declared = 'reasoning' in abilities
provider = self._reasoning_provider(model_name)
inferred = provider in self._INFERRED_EFFORT_PROVIDERS | self._INFERRED_TOGGLE_PROVIDERS
supported = detected or declared or inferred
if not supported:
return reasoning.default_reasoning_capabilities()
normalized_name = model_name.lower()
levels = ['provider_default']
if provider == 'deepseek':
if 'reasoner' not in normalized_name and '-r1' not in normalized_name:
levels.append('disabled')
levels.append('enabled')
elif provider == 'volcengine':
levels.extend(['disabled', 'enabled'])
elif provider == 'ollama':
levels.append('disabled')
if normalized_name.startswith('gpt-oss') or '/gpt-oss' in normalized_name:
levels.extend(['low', 'medium', 'high'])
else:
levels.append('enabled')
elif not detected:
levels.extend(['low', 'medium', 'high'])
else:
model_info = self._safe_model_info(model_name)
supports_none = model_info.get('supports_none_reasoning_effort') is True
if provider == 'anthropic':
supports_none = True
if provider == 'gemini' and 'gemini-3' in normalized_name:
supports_none = False
if supports_none:
levels.append('disabled')
for level in ('minimal', 'low', 'medium', 'high'):
flag = model_info.get(f'supports_{level}_reasoning_effort')
if flag is not False:
levels.append(level)
for level in ('xhigh', 'max'):
if model_info.get(f'supports_{level}_reasoning_effort') is True:
levels.append(level)
return {
'supported': True,
'levels': list(dict.fromkeys(levels)),
'source': 'litellm' if detected else ('provider' if inferred else 'manual'),
}
def _build_reasoning_args(self, model: requester.RuntimeLLMModel) -> dict[str, typing.Any]:
raw_config = getattr(model, 'reasoning_config_override', None)
if raw_config is None:
raw_config = getattr(model.model_entity, 'reasoning_config', None)
if not isinstance(raw_config, dict):
raw_config = None
config = reasoning.normalize_reasoning_config(raw_config)
level = config['level']
if level == 'provider_default':
return {}
capabilities = self.get_reasoning_capabilities(model)
try:
reasoning.validate_reasoning_capabilities(config, capabilities, model.model_entity.name)
except ValueError as exc:
raise errors.RequesterError(str(exc)) from exc
provider = self._reasoning_provider(model.model_entity.name)
if level == 'disabled':
if provider == 'volcengine':
return {'thinking': {'type': 'disabled'}}
return {'reasoning_effort': 'none'}
if level == 'enabled':
if provider in {'deepseek', 'volcengine'}:
return {'thinking': {'type': 'enabled'}}
return {'reasoning_effort': 'low'}
return {'reasoning_effort': level}
def _infer_model_type(self, model_id: str) -> str:
normalized_id = (model_id or '').lower()
if any(kw in normalized_id for kw in self._RERANK_MODEL_HINTS):
@@ -344,6 +505,11 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
)
if supports_provider_reported_vision or self._supports_vision(model_id):
abilities.append('vision')
supports_provider_reported_reasoning = bool(
model_payload and model_payload.get('supports_reasoning') is True
)
if supports_provider_reported_reasoning or self._supports_reasoning(model_id):
abilities.append('reasoning')
scanned_model['abilities'] = abilities
context_length = self._context_length_from_scan_payload(model_payload)
@@ -670,6 +836,21 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
args.update(model.model_entity.extra_args)
args.update(extra_args)
reasoning_args = self._build_reasoning_args(model)
if reasoning_args:
conflicts = reasoning.find_reasoning_arg_conflicts(model.model_entity.extra_args)
conflicts.extend(reasoning.find_reasoning_arg_conflicts(extra_args))
if conflicts:
raise errors.RequesterError(
'reasoning_config conflicts with advanced parameters: ' + ', '.join(dict.fromkeys(conflicts))
)
args.update(reasoning_args)
if 'reasoning_effort' in reasoning_args and self._reasoning_provider(model.model_entity.name) == 'openai':
allowed_openai_params = args.get('allowed_openai_params') or []
if not isinstance(allowed_openai_params, (list, tuple, set)):
raise errors.RequesterError('allowed_openai_params must be an array')
args['allowed_openai_params'] = list(dict.fromkeys([*allowed_openai_params, 'reasoning_effort']))
if funcs:
tools = await self.ap.tool_mgr.generate_tools_for_openai(funcs)
if tools:
@@ -699,6 +880,10 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
content = message_data.get('content', '')
reasoning_content = message_data.get('reasoning_content', None)
if reasoning_content:
provider_fields = dict(message_data.get('provider_specific_fields') or {})
provider_fields['reasoning_content'] = reasoning_content
message_data['provider_specific_fields'] = provider_fields
message_data['content'] = self._process_thinking_content(content, reasoning_content, remove_think)
if 'reasoning_content' in message_data:
@@ -760,13 +945,13 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
delta_content = delta.get('content', '')
reasoning_content = delta.get('reasoning_content', '')
provider_fields = dict(delta.get('provider_specific_fields') or {})
# Handle reasoning_content based on remove_think flag
if reasoning_content:
provider_fields['reasoning_content'] = reasoning_content
if remove_think:
# Skip reasoning content when remove_think is True
chunk_idx += 1
continue
delta_content = None
else:
# Use reasoning_content as the displayed content
delta_content = reasoning_content
@@ -779,7 +964,7 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
tool_calls = self._normalize_stream_tool_calls(delta.get('tool_calls'), tool_call_state)
if chunk_idx == 0 and not delta_content and not tool_calls:
if chunk_idx == 0 and not delta_content and not tool_calls and not provider_fields:
chunk_idx += 1
continue
@@ -791,8 +976,8 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
}
# Preserve provider_specific_fields from delta (e.g., Gemini thought_signatures)
if delta.get('provider_specific_fields'):
chunk_data['provider_specific_fields'] = delta['provider_specific_fields']
if provider_fields:
chunk_data['provider_specific_fields'] = provider_fields
chunk_data = {k: v for k, v in chunk_data.items() if v is not None}
yield provider_message.MessageChunk(**chunk_data)
+37 -2
View File
@@ -6,6 +6,7 @@ import typing
from .. import runner
from ...telemetry import features as telemetry_features
from ..modelmgr import requester as modelmgr_requester
from ..modelmgr import reasoning as modelmgr_reasoning
from ..tools.loaders.native import EXEC_TOOL_NAME
import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query
import langbot_plugin.api.entities.builtin.provider.message as provider_message
@@ -60,6 +61,7 @@ class _StreamAccumulator:
self.msg_idx = 0
self.accumulated_content = initial_content or ''
self.last_role = 'assistant'
self.provider_specific_fields: dict[str, typing.Any] = {}
self.msg_sequence = msg_sequence
self.remove_think = remove_think
self._think_state = None
@@ -94,6 +96,14 @@ class _StreamAccumulator:
if tool_call.function and tool_call.function.arguments:
self.tool_calls_map[tool_call.id].function.arguments += tool_call.function.arguments
if msg.provider_specific_fields:
for key, value in msg.provider_specific_fields.items():
if key == 'reasoning_content' and isinstance(value, str):
previous = self.provider_specific_fields.get(key, '')
self.provider_specific_fields[key] = f'{previous}{value}'
else:
self.provider_specific_fields[key] = value
if msg.is_final:
self._flush_think_state()
@@ -103,6 +113,7 @@ class _StreamAccumulator:
role=self.last_role,
content=self._maybe_strip_think(self.accumulated_content),
tool_calls=list(self.tool_calls_map.values()) if (self.tool_calls_map and msg.is_final) else None,
provider_specific_fields=(self.provider_specific_fields or None) if msg.is_final else None,
is_final=msg.is_final,
msg_sequence=self.msg_sequence,
)
@@ -115,6 +126,7 @@ class _StreamAccumulator:
role=self.last_role,
content=self._maybe_strip_think(self.accumulated_content),
tool_calls=list(self.tool_calls_map.values()) if self.tool_calls_map else None,
provider_specific_fields=self.provider_specific_fields or None,
msg_sequence=self.msg_sequence,
)
@@ -233,9 +245,10 @@ class LocalAgentRunner(runner.RequestRunner):
execution_context,
query.use_llm_model_uuid,
)
candidates.append(primary)
except ValueError:
self.ap.logger.warning(f'Primary model {query.use_llm_model_uuid} not found')
else:
candidates.append(LocalAgentRunner._apply_pipeline_reasoning_config(query, primary))
# Fallback models
fallback_uuids = (query.variables or {}).get('_fallback_model_uuids', [])
@@ -245,12 +258,34 @@ class LocalAgentRunner(runner.RequestRunner):
execution_context,
fb_uuid,
)
candidates.append(fb_model)
except ValueError:
self.ap.logger.warning(f'Fallback model {fb_uuid} not found, skipping')
else:
candidates.append(LocalAgentRunner._apply_pipeline_reasoning_config(query, fb_model))
return candidates
@staticmethod
def _apply_pipeline_reasoning_config(
query: pipeline_query.Query,
model: modelmgr_requester.RuntimeLLMModel,
) -> modelmgr_requester.RuntimeLLMModel:
local_agent_config = query.pipeline_config.get('ai', {}).get('local-agent', {})
model_config = local_agent_config.get('model', {})
reasoning_by_model = model_config.get('reasoning', {}) if isinstance(model_config, dict) else {}
level = (
reasoning_by_model.get(model.model_entity.uuid, 'provider_default')
if isinstance(reasoning_by_model, dict)
else 'provider_default'
)
reasoning_config = modelmgr_reasoning.normalize_reasoning_config({'level': level})
return modelmgr_requester.RuntimeLLMModel(
execution_context=model.execution_context,
model_entity=model.model_entity,
provider=model.provider,
reasoning_config_override=reasoning_config,
)
async def _invoke_with_fallback(
self,
query: pipeline_query.Query,