AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(blocks): support explicit credential-free Ollama routes (#14135)
primorLee5bdd479ec0c1
diff --git a/autogpt_platform/backend/backend/blocks/_base.py b/autogpt_platform/backend/backend/blocks/_base.pyindex 110f40b284..f459b3ceac 100644--- a/autogpt_platform/backend/backend/blocks/_base.py+++ b/autogpt_platform/backend/backend/blocks/_base.py@@ -14,6 +14,7 @@ from typing import (TypeAlias,TypeVar,cast,+ get_args,get_origin,)@@ -378,17 +379,29 @@ class BlockSchema(BaseModel):@classmethoddef get_credentials_fields(cls) -> dict[str, type[CredentialsMetaInput]]:- return {- field_name: info.annotation- for field_name, info in cls.model_fields.items()- if (- inspect.isclass(info.annotation)- and issubclass(- get_origin(info.annotation) or info.annotation,- CredentialsMetaInput,- )+ result = {}+ for field_name, info in cls.model_fields.items():+ annotation = info.annotation+ # Conditional credentials can be nullable at runtime while their+ # JSON schema remains the credential object shape. Inspect union+ # members so those fields are still discovered and validated.+ candidates = [annotation, *get_args(annotation)]++ credentials_model = next(+ (+ candidate+ for candidate in candidates+ if inspect.isclass(candidate)+ and issubclass(+ get_origin(candidate) or candidate,+ CredentialsMetaInput,+ )+ ),+ None,)- }+ if credentials_model is not None:+ result[field_name] = credentials_model+ return result@classmethoddef get_auto_credentials_fields(cls) -> dict[str, dict[str, Any]]:diff --git a/autogpt_platform/backend/backend/blocks/ai_condition.py b/autogpt_platform/backend/backend/blocks/ai_condition.pyindex cb9e8f82a6..f2697131b2 100644--- a/autogpt_platform/backend/backend/blocks/ai_condition.py+++ b/autogpt_platform/backend/backend/blocks/ai_condition.py@@ -137,7 +137,7 @@ class AIConditionBlock(AIBlockBase):async def llm_call(self,- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,llm_model: LLMModel,prompt: list,max_tokens: int,@@ -154,7 +154,11 @@ class AIConditionBlock(AIBlockBase):)async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ self,+ input_data: Input,+ *,+ credentials: APIKeyCredentials | None = None,+ **kwargs,) -> BlockOutput:"""Evaluate the AI condition and return appropriate outputs.diff --git a/autogpt_platform/backend/backend/blocks/autopilot.py b/autogpt_platform/backend/backend/blocks/autopilot.pyindex 7b683d6265..6306f4d9cd 100644--- a/autogpt_platform/backend/backend/blocks/autopilot.py+++ b/autogpt_platform/backend/backend/blocks/autopilot.py@@ -169,12 +169,12 @@ class AutoPilotBlock(Block):default=None,credential_reference_only=True,discriminator="transport",- # `platform` is deliberately absent: it needs no credential at all,- # and an unmapped discriminator value makes the credential input- # hide itself rather than asking for something that does not exist.discriminator_mapping={AutoPilotTransport.CODEX_APP_SERVER.value: ProviderName.CODEX,},+ credential_free_discriminator_values={+ AutoPilotTransport.PLATFORM.value,+ },json_schema_extra={"secret": True,"advanced": False,diff --git a/autogpt_platform/backend/backend/blocks/llm.py b/autogpt_platform/backend/backend/blocks/llm.pyindex 7a73a2cc51..0695045b62 100644--- a/autogpt_platform/backend/backend/blocks/llm.py+++ b/autogpt_platform/backend/backend/blocks/llm.py@@ -17,6 +17,8 @@ import openaifrom anthropic.types import ToolParamfrom openai.types.chat import ChatCompletion as OpenAIChatCompletionfrom pydantic import BaseModel, SecretStr+from pydantic.json_schema import SkipJsonSchema+from pydantic_core import PydanticUndefinedfrom backend.blocks._base import (Block,@@ -40,7 +42,7 @@ from backend.data.model import (NodeExecutionStats,SchemaField,)-from backend.integrations.providers import ProviderName+from backend.integrations.providers import ProviderName, provider_keyfrom backend.util import json# ``ToolCall`` and ``ToolContentBlock`` live in the shared@@ -89,7 +91,9 @@ LLMProviderName = Literal[ProviderName.LLAMA_API,ProviderName.V0,]-AICredentials = CredentialsMetaInput[LLMProviderName, Literal["api_key"]]+AICredentials = (+ CredentialsMetaInput[LLMProviderName, Literal["api_key"]] | SkipJsonSchema[None]+)# Providers whose credential use is a model call rather than an action taken# on the user's behalf; activity feeds leave these out.LLM_PROVIDER_NAMES: frozenset[str] = frozenset(@@ -111,13 +115,21 @@ TEST_CREDENTIALS_INPUT = {}-def AICredentialsField() -> AICredentials:+def AICredentialsField(*, allow_credential_free: bool = True) -> AICredentials:return CredentialsField(description="API key for the LLM provider.",discriminator="model",discriminator_mapping={- model.value: model.metadata.provider for model in LLMModel+ model.value: model.metadata.provider+ for model in LLMModel+ if model.metadata.provider != ProviderName.OLLAMA+ },+ credential_free_discriminator_values={+ model.value+ for model in LLMModel+ if allow_credential_free and model.metadata.provider == ProviderName.OLLAMA},+ default=None if allow_credential_free else PydanticUndefined,)@@ -241,7 +253,7 @@ def get_parallel_tool_calls_param(async def llm_call(- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,llm_model: LLMModel,prompt: list[dict],max_tokens: int | None,@@ -303,7 +315,7 @@ async def llm_call(async def _llm_call(- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,llm_model: LLMModel,prompt: list[dict],max_tokens: int | None,@@ -335,6 +347,11 @@ async def _llm_call("""provider = llm_model.metadata.providercontext_window = llm_model.context_window+ if credentials is None and provider != ProviderName.OLLAMA:+ raise ValueError(+ f"Credentials are required for {provider_key(provider)}/{llm_model.value}."+ )+ api_key = credentials.api_key.get_secret_value() if credentials else ""if compress_prompt_to_fit:# Pass the model so compaction measures in the same corrected token@@ -387,7 +404,7 @@ async def _llm_call(provider_response = await call_provider(provider=cast(Any, provider),model=llm_model.value,- api_key=credentials.api_key.get_secret_value(),+ api_key=api_key,messages=prompt,max_tokens=max_tokens,tools=tools,@@ -549,7 +566,7 @@ class AIStructuredResponseGeneratorBlock(AIBlockBase):async def llm_call(self,- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,llm_model: LLMModel,prompt: list[dict],max_tokens: int | None,@@ -577,7 +594,11 @@ class AIStructuredResponseGeneratorBlock(AIBlockBase):)async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ self,+ input_data: Input,+ *,+ credentials: APIKeyCredentials | None = None,+ **kwargs,) -> BlockOutput:logger.debug(f"Calling LLM with input data: {input_data}")prompt = [json.to_dict(p) for p in input_data.conversation_history or [] if p]@@ -1050,7 +1071,7 @@ class AITextGeneratorBlock(AIBlockBase):async def llm_call(self,input_data: AIStructuredResponseGeneratorBlock.Input,- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,execution_context: "ExecutionContext | None" = None,) -> dict:block = AIStructuredResponseGeneratorBlock()@@ -1064,7 +1085,11 @@ class AITextGeneratorBlock(AIBlockBase):return response["response"]async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ self,+ input_data: Input,+ *,+ credentials: APIKeyCredentials | None = None,+ **kwargs,) -> BlockOutput:object_input_data = AIStructuredResponseGeneratorBlock.Input(**{@@ -1158,7 +1183,11 @@ class AITextSummarizerBlock(AIBlockBase):)async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ self,+ input_data: Input,+ *,+ credentials: APIKeyCredentials | None = None,+ **kwargs,) -> BlockOutput:async for output_name, output_data in self._run(input_data, credentials, kwargs.get("execution_context")@@ -1168,7 +1197,7 @@ class AITextSummarizerBlock(AIBlockBase):async def _run(self,input_data: Input,- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,execution_context: "ExecutionContext | None" = None,) -> BlockOutput:chunks = self._split_text(@@ -1219,7 +1248,7 @@ class AITextSummarizerBlock(AIBlockBase):async def llm_call(self,input_data: AIStructuredResponseGeneratorBlock.Input,- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,execution_context: "ExecutionContext | None" = None,) -> dict:block = AIStructuredResponseGeneratorBlock()@@ -1236,7 +1265,7 @@ class AITextSummarizerBlock(AIBlockBase):self,chunk: str,input_data: Input,- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,execution_context: "ExecutionContext | None" = None,) -> str:prompt = f"Summarize the following text in a {input_data.style} form. Focus your summary on the topic of `{input_data.focus}` if present, otherwise just provide a general summary:\n\n```{chunk}```"@@ -1271,7 +1300,7 @@ class AITextSummarizerBlock(AIBlockBase):self,summaries: list[str],input_data: Input,- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,execution_context: "ExecutionContext | None" = None,) -> str:combined_text = "\n\n".join(summaries)@@ -1395,7 +1424,7 @@ class AIConversationBlock(AIBlockBase):async def llm_call(self,input_data: AIStructuredResponseGeneratorBlock.Input,- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,execution_context: "ExecutionContext | None" = None,) -> dict:block = AIStructuredResponseGeneratorBlock()@@ -1409,7 +1438,11 @@ class AIConversationBlock(AIBlockBase):return responseasync def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ self,+ input_data: Input,+ *,+ credentials: APIKeyCredentials | None = None,+ **kwargs,) -> BlockOutput:has_messages = any(isinstance(m, dict)@@ -1548,7 +1581,7 @@ class AIListGeneratorBlock(AIBlockBase):async def llm_call(self,input_data: AIStructuredResponseGeneratorBlock.Input,- credentials: APIKeyCredentials,+ credentials: APIKeyCredentials | None,execution_context: "ExecutionContext | None" = None,) -> dict[str, Any]:llm_block = AIStructuredResponseGeneratorBlock()@@ -1562,7 +1595,11 @@ class AIListGeneratorBlock(AIBlockBase):return responseasync def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ self,+ input_data: Input,+ *,+ credentials: APIKeyCredentials | None = None,+ **kwargs,) -> BlockOutput:logger.debug(f"Starting AIListGeneratorBlock.run with input data: {input_data}")diff --git a/autogpt_platform/backend/backend/blocks/orchestrator.py b/autogpt_platform/backend/backend/blocks/orchestrator.pyindex 6052eae9d1..490faff8a1 100644--- a/autogpt_platform/backend/backend/blocks/orchestrator.py+++ b/autogpt_platform/backend/backend/blocks/orchestrator.py@@ -895,7 +895,7 @@ class OrchestratorBlock(Block):async def _attempt_llm_call_with_validation(self,- credentials: llm.APIKeyCredentials,+ credentials: llm.APIKeyCredentials | None,input_data: Input,current_prompt: list[dict[str, Any]],tool_functions: list[dict[str, Any]],@@ -1322,7 +1322,7 @@ class OrchestratorBlock(Block):messages: list[dict[str, Any]],tools: Sequence[Any],*,- credentials: llm.APIKeyCredentials,+ credentials: llm.APIKeyCredentials | None,input_data: "OrchestratorBlock.Input",) -> LLMLoopResponse:"""LLM caller callback for agent mode: wraps _attempt_llm_call_with_validation."""@@ -1462,7 +1462,7 @@ class OrchestratorBlock(Block):async def _execute_tools_agent_mode(self,input_data: "OrchestratorBlock.Input",- credentials: llm.APIKeyCredentials,+ credentials: llm.APIKeyCredentials | None,tool_functions: list[dict[str, Any]],prompt: list[dict[str, Any]],graph_exec_id: str,@@ -1657,7 +1657,7 @@ class OrchestratorBlock(Block):async def _execute_tools_sdk_mode(self,input_data: "OrchestratorBlock.Input",- credentials: llm.APIKeyCredentials,+ credentials: llm.APIKeyCredentials | None,tool_functions: list[dict[str, Any]],prompt: list[dict[str, Any]],execution_params: ExecutionParams,@@ -1697,8 +1697,7 @@ class OrchestratorBlock(Block):# Extended thinking does not support subscription-mode (platform-managed credits).# Use *credential* provider for routing (not model metadata provider),# because a user may select an Anthropic model but route through OpenRouter.- provider = credentials.provider- if not credentials.api_key:+ if credentials is None or not credentials.api_key:yield ("error",(@@ -1707,6 +1706,7 @@ class OrchestratorBlock(Block):),)return+ provider = credentials.providerapi_key = credentials.api_key.get_secret_value()if provider == "open_router":# Route through OpenRouter proxy: point ``ANTHROPIC_BASE_URL`` at@@ -1979,7 +1979,7 @@ class OrchestratorBlock(Block):self,input_data: Input,*,- credentials: llm.APIKeyCredentials,+ credentials: llm.APIKeyCredentials | None = None,graph_id: str,node_id: str,graph_exec_id: str,diff --git a/autogpt_platform/backend/backend/blocks/stagehand/blocks.py b/autogpt_platform/backend/backend/blocks/stagehand/blocks.pyindex 63b0627e47..f4a8c43257 100644--- a/autogpt_platform/backend/backend/blocks/stagehand/blocks.py+++ b/autogpt_platform/backend/backend/blocks/stagehand/blocks.py@@ -95,7 +95,9 @@ class StagehandObserveBlock(Block):default=StagehandRecommendedLLMModel.CLAUDE_4_6_SONNET,advanced=False,)- model_credentials: AICredentials = AICredentialsField()+ model_credentials: AICredentials = AICredentialsField(+ allow_credential_free=False+ )url: str = SchemaField(description="URL to navigate to.",)@@ -178,7 +180,9 @@ class StagehandActBlock(Block):default=StagehandRecommendedLLMModel.CLAUDE_4_6_SONNET,advanced=False,)- model_credentials: AICredentials = AICredentialsField()+ model_credentials: AICredentials = AICredentialsField(+ allow_credential_free=False+ )url: str = SchemaField(description="URL to navigate to.",)@@ -274,7 +278,9 @@ class StagehandExtractBlock(Block):default=StagehandRecommendedLLMModel.CLAUDE_4_6_SONNET,advanced=False,)- model_credentials: AICredentials = AICredentialsField()+ model_credentials: AICredentials = AICredentialsField(+ allow_credential_free=False+ )url: str = SchemaField(description="URL to navigate to.",)diff --git a/autogpt_platform/backend/backend/blocks/test/test_llm.py b/autogpt_platform/backend/backend/blocks/test/test_llm.pyindex 5921256b03..a81ee6bff7 100644--- a/autogpt_platform/backend/backend/blocks/test/test_llm.py+++ b/autogpt_platform/backend/backend/blocks/test/test_llm.py@@ -15,7 +15,7 @@ from backend.blocks._base import DEFAULT_BLOCK_EXECUTION_TIMEOUT_SECONDSfrom backend.data.execution import ExecutionContextfrom backend.data.model import NodeExecutionStatsfrom backend.util.llm import saturation-from backend.util.llm.providers import FAST_FAIL_TIMEOUT_SECONDS+from backend.util.llm.providers import FAST_FAIL_TIMEOUT_SECONDS, ProviderResponsefrom backend.util.settings import Config# TEST_CREDENTIALS_INPUT is a plain dict that satisfies AICredentials at runtime@@ -1972,3 +1972,118 @@ class TestClaude5ModelThreading:est_5 = estimate_token_count(prompt, model=m5.value)assert est_5 == int(est_46 * 1.5)assert (m5.context_window - est_5) < (m46.context_window - est_46)+++class TestOllamaCredentials:+ def test_ai_credentials_only_require_keys_for_remote_models(self):+ info = (+ llm.AIStructuredResponseGeneratorBlock.Input.get_credentials_fields_info()[+ "credentials"+ ]+ )++ assert (+ "credentials"+ not in llm.AIStructuredResponseGeneratorBlock.Input.get_required_fields()+ )+ for model in llm.LLMModel:+ assert info.requires_credentials(model.value) is (+ model.metadata.provider != llm.ProviderName.OLLAMA+ )++ # A model removed from the registry must not be mistaken for a known+ # credential-free local model.+ assert info.requires_credentials("retired-model") is True+ assert llm.ProviderName.OLLAMA in info.provider+ assert llm.LLMModel.OLLAMA_LLAMA3_3.value not in info.discriminator_mapping++ @pytest.mark.asyncio+ async def test_ollama_call_does_not_require_credentials(self):+ provider_response = ProviderResponse(+ content="local response",+ prompt_tokens=2,+ completion_tokens=3,+ )++ with patch(+ "backend.util.llm.providers.call_provider",+ new=AsyncMock(return_value=provider_response),+ ) as call_provider:+ response = await llm._llm_call(+ credentials=None,+ llm_model=llm.LLMModel.OLLAMA_LLAMA3_3,+ prompt=[{"role": "user", "content": "Hello"}],+ max_tokens=100,+ compress_prompt_to_fit=False,+ )++ assert response.response == "local response"+ call_provider.assert_awaited_once()+ assert call_provider.call_args.kwargs["api_key"] == ""+ assert call_provider.call_args.kwargs["provider"] == llm.ProviderName.OLLAMA++ @pytest.mark.asyncio+ async def test_remote_model_without_credentials_fails_before_provider_call(self):+ with (+ patch(+ "backend.util.llm.providers.call_provider", new_callable=AsyncMock+ ) as call_provider,+ pytest.raises(ValueError, match=r"Credentials are required for openai/"),+ ):+ await llm._llm_call(+ credentials=None,+ llm_model=llm.DEFAULT_LLM_MODEL,+ prompt=[{"role": "user", "content": "Hello"}],+ max_tokens=100,+ compress_prompt_to_fit=False,+ )++ call_provider.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_text_block_runs_ollama_without_credentials_kwarg(self):+ block = llm.AITextGeneratorBlock()+ input_data = block.Input(+ prompt="Hello",+ model=llm.LLMModel.OLLAMA_LLAMA3_3,+ )++ with patch.object(+ block,+ "llm_call",+ new_callable=AsyncMock,+ return_value="local response",+ ) as mock_llm_call:+ execution_context = ExecutionContext()+ outputs = [+ item+ async for item in block.execute(+ input_data.model_dump(), execution_context=execution_context+ )+ ]++ assert ("response", "local response") in outputs+ mock_llm_call.assert_awaited_once()+ assert mock_llm_call.await_args is not None+ structured_input, credentials, execution_context = mock_llm_call.await_args.args+ assert credentials is None+ assert isinstance(execution_context, ExecutionContext)+ assert structured_input.credentials is None+ assert structured_input.model == llm.LLMModel.OLLAMA_LLAMA3_3+++ "block_name",+ ["StagehandObserveBlock", "StagehandActBlock", "StagehandExtractBlock"],+)+def test_stagehand_keeps_remote_model_credentials_required(block_name):+ from backend.blocks.stagehand import blocks++ schema = getattr(blocks, block_name).Input+ assert "model_credentials" in schema.get_required_fields()+ assert (+ schema.get_field_schema("model_credentials")[+ "credential_free_discriminator_values"+ ]+ == []+ )diff --git a/autogpt_platform/backend/backend/data/block_cost_config.py b/autogpt_platform/backend/backend/data/block_cost_config.pyindex 20cdc7551f..a20e9c2101 100644--- a/autogpt_platform/backend/backend/data/block_cost_config.py+++ b/autogpt_platform/backend/backend/data/block_cost_config.py@@ -89,7 +89,6 @@ from backend.integrations.credentials_store import (llama_api_credentials,mem0_credentials,nvidia_credentials,- ollama_credentials,open_router_credentials,openai_credentials,replicate_credentials,@@ -359,14 +358,7 @@ LLM_COST = (BlockCost(cost_type=BlockCostType.RUN,cost_amount=0,- cost_filter={- "model": model,- "credentials": {- "id": ollama_credentials.id,- "provider": ollama_credentials.provider,- "type": ollama_credentials.type,- },- },+ cost_filter={"model": model},)for model in MODEL_COSTif MODEL_METADATA[model].provider == "ollama"diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.pyindex 72faee0dfa..d496490747 100644--- a/autogpt_platform/backend/backend/data/graph.py+++ b/autogpt_platform/backend/backend/data/graph.py@@ -585,17 +585,10 @@ class GraphModel(Graph, GraphMeta):}for node in graph.nodes:- # A node's credentials are optional if either:- # 1. The node metadata says so (credentials_optional=True), or- # 2. All credential fields on the block have defaults (not required by schema)+ # Conditional credential fields can have a schema default while+ # still requiring credentials for the currently selected route.block_required = node.block.input_schema.get_required_fields()- creds_required_by_schema = any(- fname in block_required- for fname in node.block.input_schema.get_credentials_fields()- )- node_required_map[node.id] = (- not node.credentials_optional and creds_required_by_schema- )+ node_required_map[node.id] = Falsefor (field_name,@@ -603,6 +596,11 @@ class GraphModel(Graph, GraphMeta):) in node.block.input_schema.get_credentials_fields_info().items():discriminator = field_info.discriminatorif not discriminator:+ if (+ not node.credentials_optional+ and field_name in block_required+ ):+ node_required_map[node.id] = Truenode_credential_data.append((field_info, (node.id, field_name)))continue@@ -638,6 +636,35 @@ class GraphModel(Graph, GraphMeta):node.block.input_schema, field_info)+ required_discriminator_value = discriminator_value+ if (+ required_discriminator_value is None+ and not discriminator_is_linked+ ):+ required_discriminator_value = (+ node.block.input_schema.get_field_schema(discriminator).get(+ "default"+ )+ )+ if not node.credentials_optional and (+ field_name in block_required+ or (+ discriminator_is_linked+ and bool(field_info.credential_free_discriminator_values)+ and any(+ field_info.requires_credentials(value)+ for value in field_info.discriminator_mapping or {}+ )+ )+ or (+ required_discriminator_value is not None+ and field_info.requires_credentials(+ required_discriminator_value+ )+ )+ ):+ node_required_map[node.id] = True+if discriminator_value is None:node_credential_data.append((field_info, (node.id, field_name)))continuediff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.pyindex 4a1f4c0bef..fc54bb9ef0 100644--- a/autogpt_platform/backend/backend/data/graph_test.py+++ b/autogpt_platform/backend/backend/data/graph_test.py@@ -2951,9 +2951,7 @@ def test_codex_transport_node_merges_with_autopilot_codex_slot():def test_llm_block_union_is_left_intact_without_model():- """Regression guard: mapping-only discriminators keep their union slot key.- Persisted preset/schedule credentials are keyed by this name, so collapsing- it would silently orphan them."""+ """Remote providers keep their union slot; local Ollama needs no slot."""from backend.blocks.llm import AITextGeneratorBlockgraph = _graph_with([_node("n1", AITextGeneratorBlock().id, {"prompt": "hi"})])@@ -2963,7 +2961,16 @@ def test_llm_block_union_is_left_intact_without_model():"aiml_api-anthropic-groq-llama_api-ollama-open_router-openai-v0_api_key_credentials"]providers, types, required = slots[list(slots)[0]]- assert len(providers) == 8+ assert providers == {+ "aiml_api",+ "anthropic",+ "groq",+ "llama_api",+ "ollama",+ "open_router",+ "openai",+ "v0",+ }assert types == {"api_key"}assert required is True@@ -2980,6 +2987,22 @@ def test_llm_block_with_model_discriminates_normally():}+def test_llm_block_with_ollama_model_contributes_no_credential():+ from backend.blocks.llm import AITextGeneratorBlock++ graph = _graph_with(+ [+ _node(+ "n1",+ AITextGeneratorBlock().id,+ {"prompt": "hi", "model": "llama3.3"},+ )+ ]+ )++ assert _slots(graph) == {}++def test_only_known_blocks_use_discriminator_type_mapping():"""Guard on the fallback's trigger condition. If a new block addsdiscriminator_type_mapping, it silently inherits schema-default@@ -3177,3 +3200,20 @@ def test_autopilot_node_with_an_explicit_transport_is_valid(errors = GraphModel._validate_graph_get_errors(graph, for_run=True)assert errors.get(graph.nodes[0].id, {}) == {}, errors+++def test_linked_llm_model_preserves_required_legacy_credential_slot():+ from backend.blocks.llm import AITextGeneratorBlock++ graph = _graph_with(+ [_node("n1", AITextGeneratorBlock().id, {"prompt": "hi", "model": "llama3.3"})]+ )+ graph.links = [+ Link(source_id="source", sink_id="n1", source_name="value", sink_name="model")+ ]++ slots = _slots(graph)+ assert list(slots) == [+ "aiml_api-anthropic-groq-llama_api-ollama-open_router-openai-v0_api_key_credentials"+ ]+ assert next(iter(slots.values()))[2] is Truediff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.pyindex b035c92088..ba2fa070ff 100644--- a/autogpt_platform/backend/backend/data/model.py+++ b/autogpt_platform/backend/backend/data/model.py@@ -618,6 +618,7 @@ class CredentialsFieldInfo(BaseModel, Generic[CP, CT]):discriminator_mapping: Optional[dict[str, CP]] = Nonediscriminator_type_mapping: Optional[dict[str, frozenset[CT]]] = Nonediscriminator_values: set[Any] = Field(default_factory=set)+ credential_free_discriminator_values: set[Any] = Field(default_factory=set)is_auto_credential: bool = Falsecredential_reference_only: bool = Falseinput_field_name: Optional[str] = None@@ -699,6 +700,12 @@ class CredentialsFieldInfo(BaseModel, Generic[CP, CT]):if value not in all_discriminator_values:all_discriminator_values.append(value)+ all_credential_free_values = set()+ for _, field in group:+ all_credential_free_values.update(+ field.credential_free_discriminator_values+ )+# Generate the key for the combined resultproviders_key, supported_types_key = keygroup_key = (@@ -720,6 +727,7 @@ class CredentialsFieldInfo(BaseModel, Generic[CP, CT]):discriminator_mapping=combined.discriminator_mapping,discriminator_type_mapping=combined.discriminator_type_mapping,discriminator_values=set(all_discriminator_values),+ credential_free_discriminator_values=all_credential_free_values,is_auto_credential=combined.is_auto_credential,credential_reference_only=all(field.credential_reference_only for _, field in group@@ -734,20 +742,19 @@ class CredentialsFieldInfo(BaseModel, Generic[CP, CT]):def requires_credentials(self, discriminator_value: Any) -> bool:"""Whether this selection needs a credential at all.- A field may declare a discriminator value that maps to no provider,- meaning that choice is credential-free — Otto's `platform`- transport runs on platform credits and needs nothing connected.+ Credential-free choices are explicit so an unknown or retired+ discriminator value is not silently treated as unauthenticated.Callers must consult this before resolving, discriminating, orenforcing entitlement on a field: `discriminate()` raises on an- unmapped value, and resolving a credential the selection will never- use can fail a run that was not going to touch that provider.+ unsupported value, and resolving a credential for an explicitly free+ selection can fail a run that was not going to touch that provider."""if not (self.discriminator and self.discriminator_mapping):return Trueif discriminator_value is None:return True- return discriminator_value in self.discriminator_mapping+ return discriminator_value not in self.credential_free_discriminator_valuesdef discriminate(self, discriminator_value: Any) -> CredentialsFieldInfo:if not (self.discriminator and self.discriminator_mapping):@@ -778,6 +785,9 @@ class CredentialsFieldInfo(BaseModel, Generic[CP, CT]):discriminator_mapping=self.discriminator_mapping,discriminator_type_mapping=self.discriminator_type_mapping,discriminator_values=set(self.discriminator_values),+ credential_free_discriminator_values=set(+ self.credential_free_discriminator_values+ ),is_auto_credential=self.is_auto_credential,credential_reference_only=self.credential_reference_only,input_field_name=self.input_field_name,@@ -791,6 +801,7 @@ def CredentialsField(discriminator_mapping: Optional[dict[str, Any]] = None,discriminator_type_mapping: Optional[dict[str, Any]] = None,discriminator_values: Optional[set[Any]] = None,+ credential_free_discriminator_values: Optional[set[Any]] = None,title: Optional[str] = None,description: Optional[str] = None,**kwargs,@@ -808,6 +819,7 @@ def CredentialsField("discriminator_mapping": discriminator_mapping,"discriminator_type_mapping": discriminator_type_mapping,"discriminator_values": discriminator_values,+ "credential_free_discriminator_values": credential_free_discriminator_values,"credential_reference_only": kwargs.pop("credential_reference_only", None),}.items()if v is not Nonediff --git a/autogpt_platform/backend/backend/executor/block_usage_cost_test.py b/autogpt_platform/backend/backend/executor/block_usage_cost_test.pyindex 498962e5c1..02d443c837 100644--- a/autogpt_platform/backend/backend/executor/block_usage_cost_test.py+++ b/autogpt_platform/backend/backend/executor/block_usage_cost_test.py@@ -233,6 +233,18 @@ def test_tokens_falls_back_to_flat_model_cost_when_rate_missing(assert cost == expected+def test_ollama_zero_cost_entry_matches_without_credentials():+ ollama_model = LLMModel.OLLAMA_LLAMA3_2++ cost, matching_filter = block_usage_cost(+ AITextGeneratorBlock(),+ {"model": ollama_model.value},+ )++ assert cost == 0+ assert matching_filter == {"model": ollama_model}++def test_e2b_sandbox_blocks_bill_one_credit_per_ten_seconds():"""End-to-end: E2B blocks use the real SECOND/divisor=10 BlockCost entry."""creds = {diff --git a/autogpt_platform/backend/backend/executor/manager_credential_lease_test.py b/autogpt_platform/backend/backend/executor/manager_credential_lease_test.pyindex 87a2eaca9a..d3597dd804 100644--- a/autogpt_platform/backend/backend/executor/manager_credential_lease_test.py+++ b/autogpt_platform/backend/backend/executor/manager_credential_lease_test.py@@ -173,6 +173,7 @@ def _discriminated_reference_block(credential_reference_only=True,discriminator="transport",discriminator_mapping={"codex_app_server": ProviderName.CODEX},+ credential_free_discriminator_values={"platform"},)}block.input_schema.get_required_fields.return_value = (diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsxindex 256e52aed1..f2d6ffaa13 100644--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsx+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsx@@ -404,6 +404,7 @@ describe("An optional discriminator is still gated", () => {credentials_types: ["oauth2"],discriminator: "transport",discriminator_mapping: { codex_app_server: "codex" },+ credential_free_discriminator_values: ["platform"],properties: {id: { type: "string" },provider: { enum: ["codex"], type: "string" },@@ -515,13 +516,13 @@ describe("LLM blocks keep every model option", () => {type: "string",},credentials: {+ credential_free_discriminator_values: ["llama3.3"],credentials_provider: ["openai", "anthropic", "ollama"],credentials_types: ["api_key"],discriminator: "model",discriminator_mapping: {"gpt-4o": "openai","claude-opus-4-5-20251101": "anthropic",- "llama3.3": "ollama",},properties: {id: { type: "string" },@@ -536,7 +537,7 @@ describe("LLM blocks keep every model option", () => {type: "object",},},- required: ["prompt", "credentials"],+ required: ["prompt"],} as unknown as RJSFSchema;it("keeps all models when every LLM provider is present, as list_providers guarantees", () => {@@ -575,5 +576,13 @@ describe("LLM blocks keep every model option", () => {expect(Array.from(model.querySelectorAll("option")).map((o) => o.textContent),).toEqual(["gpt-4o", "claude-opus-4-5-20251101", "llama3.3"]);+ expect(screen.getByText(/openai credential/i)).not.toBeNull();++ const localModel = Array.from(model.querySelectorAll("option")).find(+ (option) => option.textContent === "llama3.3",+ );+ if (!localModel) throw new Error("expected the local model option");+ fireEvent.change(model, { target: { value: localModel.value } });+ expect(screen.queryByText(/credential/i)).toBeNull();});});diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/CredentialField.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/CredentialField.tsxindex 6b3873fe86..91f743c1f4 100644--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/CredentialField.tsx+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/CredentialField.tsx@@ -11,7 +11,12 @@ import { useMemo } from "react";import { useShallow } from "zustand/react/shallow";import { CredentialFieldTitle } from "./components/CredentialFieldTitle";import { useCredentialAvailability } from "./useCredentialAvailability";-import { credentialNotApplicable } from "./helpers";+import {+ credentialNotApplicable,+ credentialRequiredForSelection,+ getCredentialProviderFromSchema,+ getDiscriminatorValue,+} from "./helpers";export const CredentialsField = (props: FieldProps) => {const { formData, onChange, schema, registry, fieldPathId, required } = props;@@ -70,14 +75,13 @@ export const CredentialsField = (props: FieldProps) => {[formData?.id, formData?.provider, formData?.title, formData?.type],);- // Combines the schema's `required` array with the node-level toggle, which- // is why it is not named for the schema alone: in the builder canvas the- // toggle can relax a required field to optional. It must never mark a- // schema-optional field required — blocks declaring an optional credential- // (default=None) would otherwise render an unfillable star.+ const credentialSchema = schema as BlockIOCredentialsSubSchema;+ const selectionRequired =+ required ||+ credentialRequiredForSelection(hardcodedValues, credentialSchema);const effectiveRequired = nodeId- ? !credentialsOptional && required- : required;+ ? !credentialsOptional && selectionRequired+ : selectionRequired;// Nothing to ask for: the selected discriminator value maps to no provider// (Otto's `platform` transport), so the row is not merely unavailable —@@ -96,6 +100,11 @@ export const CredentialsField = (props: FieldProps) => {selectedCredentials?.provider,);const isUnavailable = availability === "unavailable";+ const unsupportedSelection =+ !notApplicable &&+ getDiscriminatorValue(hardcodedValues, credentialSchema) !== undefined &&+ !!credentialSchema.discriminator_mapping &&+ !getCredentialProviderFromSchema(hardcodedValues, credentialSchema);// CredentialsInput renders nothing when the provider is missing from the// providers map, which used to leave a bare title with no control under it.@@ -109,7 +118,7 @@ export const CredentialsField = (props: FieldProps) => {return null;}- if (isUnavailable && !required) {+ if (isUnavailable && !selectionRequired) {return null;}@@ -136,6 +145,12 @@ export const CredentialsField = (props: FieldProps) => {required={isRequired}selectedProvider={selectedCredentials?.provider}/>+ {unsupportedSelection && (+ <Text variant="small" role="alert">+ This selection is no longer supported. Choose another model or+ transport.+ </Text>+ )}{availability === "unavailable" && (<Textid={unavailableNoteId}diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/__tests__/helpers.test.tsindex 39af55415f..df1945f779 100644--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/__tests__/helpers.test.ts@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api";import {credentialNotApplicable,+ credentialRequiredForSelection,getCredentialProviderFromSchema,} from "../helpers";@@ -14,6 +15,7 @@ const autopilotSchema: BlockIOCredentialsSubSchema = {credentials_types: ["oauth2"],discriminator: "transport",discriminator_mapping: { codex_app_server: "codex" },+ credential_free_discriminator_values: ["platform"],};// A plain single-provider field with no discriminator at all.@@ -120,3 +122,42 @@ describe("credentialNotApplicable", () => {expect(credentialNotApplicable({}, githubSchema)).toBe(false);});});++describe("explicit credential-free selections", () => {+ it("keeps unknown routes visible instead of treating them as free", () => {+ expect(+ credentialNotApplicable(+ { transport: "retired-transport" },+ autopilotSchema,+ ),+ ).toBe(false);+ });++ it("does not silently exempt an unmapped model without an explicit free route", () => {+ expect(+ credentialNotApplicable(+ { transport: "typo" },+ {+ ...autopilotSchema,+ credential_free_discriminator_values: undefined,+ },+ ),+ ).toBe(false);+ });+});++describe("conditional credential requirements", () => {+ it.each([+ ["platform", false],+ ["codex_app_server", true],+ ["retired-transport", true],+ [undefined, false],+ ])(+ "marks %s required only when a credential is needed",+ (transport, expected) => {+ expect(+ credentialRequiredForSelection({ transport }, autopilotSchema),+ ).toBe(expected);+ },+ );+});diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/helpers.ts b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/helpers.tsindex bea6e58cd3..1cabafe003 100644--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/helpers.ts+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/helpers.ts@@ -184,11 +184,6 @@ export const getCredentialProviderFromSchema = (return discriminatedProvider;}- // Single-provider fields used to return their one provider unconditionally,- // ignoring the discriminator. That is wrong when a field declares a mapping:- // an unmapped value means "this choice needs no credential" — Otto's- // `platform` transport, which is deliberately absent from the mapping — and- // the input must hide rather than ask for a credential nothing will use.if (discriminator && discriminatorMapping) {return discriminatedProvider ?? null;}@@ -196,12 +191,6 @@ export const getCredentialProviderFromSchema = (return providers[0];};-/**- * True when the field has no usable credential route for the current state.- *- * An unmapped value needs no credential. An unset discriminator also has no- * actionable control unless a saved provider identifies a legacy selection.- */export const credentialNotApplicable = (formData: Record<string, unknown>,schema: BlockIOCredentialsSubSchema,@@ -213,5 +202,20 @@ export const credentialNotApplicable = (const value = getDiscriminatorValue(formData, schema);if (value === undefined || value === null) return !selectedProvider;- return !Object.hasOwn(mapping, String(value));+ return (+ schema.credential_free_discriminator_values?.some(+ (freeValue) => String(freeValue) === value,+ ) ?? false+ );};++export function credentialRequiredForSelection(+ formData: Record<string, unknown>,+ schema: BlockIOCredentialsSubSchema,+): boolean {+ return (+ schema.credential_free_discriminator_values !== undefined &&+ getDiscriminatorValue(formData, schema) !== undefined &&+ !credentialNotApplicable(formData, schema)+ );+}diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.tsindex 5b3c9d7621..9dbcfe3dd3 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts@@ -239,6 +239,7 @@ export type BlockIOCredentialsSubSchema = BlockIOObjectSubSchema & {discriminator_mapping?: Record<string, CredentialsProviderName>;discriminator_type_mapping?: Record<string, CredentialsType[]>;discriminator_values?: any[];+ credential_free_discriminator_values?: unknown[];secret?: boolean;};