|
9 | 9 | agent = config_to_agent("config.json") |
10 | 10 | # Add tools that need code-based instantiation |
11 | 11 | agent.tool_registry.process_tools([ToolWithConfigArg(HttpsConnection("localhost"))]) |
| 12 | +
|
| 13 | +The ``model`` field supports two formats: |
| 14 | +
|
| 15 | +**String format (backward compatible — defaults to Bedrock):** |
| 16 | + {"model": "us.anthropic.claude-sonnet-4-20250514-v1:0"} |
| 17 | +
|
| 18 | +**Object format (supports all providers):** |
| 19 | + { |
| 20 | + "model": { |
| 21 | + "provider": "anthropic", |
| 22 | + "model_id": "claude-sonnet-4-20250514", |
| 23 | + "max_tokens": 10000, |
| 24 | + "client_args": {"api_key": "$ANTHROPIC_API_KEY"} |
| 25 | + } |
| 26 | + } |
| 27 | +
|
| 28 | +Environment variable references (``$VAR`` or ``${VAR}``) in model config values are resolved |
| 29 | +automatically before provider instantiation. |
| 30 | +
|
| 31 | +Note: The following constructor parameters cannot be specified from JSON because they require |
| 32 | +code-based instantiation: ``boto_session`` (Bedrock, SageMaker), ``client`` (OpenAI, Gemini), |
| 33 | +``gemini_tools`` (Gemini). Use ``region_name`` / ``client_args`` as JSON-friendly alternatives. |
12 | 34 | """ |
13 | 35 |
|
14 | 36 | import json |
| 37 | +import os |
| 38 | +import re |
15 | 39 | from pathlib import Path |
16 | 40 | from typing import Any |
17 | 41 |
|
|
27 | 51 | "properties": { |
28 | 52 | "name": {"description": "Name of the agent", "type": ["string", "null"], "default": None}, |
29 | 53 | "model": { |
30 | | - "description": "The model ID to use for this agent. If not specified, uses the default model.", |
31 | | - "type": ["string", "null"], |
| 54 | + "description": ( |
| 55 | + "The model to use for this agent. Can be a string (Bedrock model_id) " |
| 56 | + "or an object with a 'provider' field for any supported provider." |
| 57 | + ), |
| 58 | + "oneOf": [ |
| 59 | + {"type": "string"}, |
| 60 | + {"type": "null"}, |
| 61 | + { |
| 62 | + "type": "object", |
| 63 | + "properties": { |
| 64 | + "provider": { |
| 65 | + "description": "The model provider name", |
| 66 | + "type": "string", |
| 67 | + } |
| 68 | + }, |
| 69 | + "required": ["provider"], |
| 70 | + "additionalProperties": True, |
| 71 | + }, |
| 72 | + ], |
32 | 73 | "default": None, |
33 | 74 | }, |
34 | 75 | "prompt": { |
|
50 | 91 | # Pre-compile validator for better performance |
51 | 92 | _VALIDATOR = jsonschema.Draft7Validator(AGENT_CONFIG_SCHEMA) |
52 | 93 |
|
| 94 | +# Pattern for matching environment variable references |
| 95 | +_ENV_VAR_PATTERN = re.compile(r"^\$\{([^}]+)\}$|^\$([A-Za-z_][A-Za-z0-9_]*)$") |
| 96 | + |
| 97 | +# Provider name to model class name — resolved via strands.models lazy __getattr__ |
| 98 | +PROVIDER_MAP: dict[str, str] = { |
| 99 | + "bedrock": "BedrockModel", |
| 100 | + "anthropic": "AnthropicModel", |
| 101 | + "openai": "OpenAIModel", |
| 102 | + "gemini": "GeminiModel", |
| 103 | + "ollama": "OllamaModel", |
| 104 | + "litellm": "LiteLLMModel", |
| 105 | + "mistral": "MistralModel", |
| 106 | + "llamaapi": "LlamaAPIModel", |
| 107 | + "llamacpp": "LlamaCppModel", |
| 108 | + "sagemaker": "SageMakerAIModel", |
| 109 | + "writer": "WriterModel", |
| 110 | + "openai_responses": "OpenAIResponsesModel", |
| 111 | +} |
| 112 | + |
| 113 | + |
| 114 | +def _resolve_env_vars(value: Any) -> Any: |
| 115 | + """Recursively resolve environment variable references in config values. |
| 116 | +
|
| 117 | + String values matching ``$VAR_NAME`` or ``${VAR_NAME}`` are replaced with the |
| 118 | + corresponding environment variable value. Dicts and lists are traversed recursively. |
| 119 | +
|
| 120 | + Args: |
| 121 | + value: The value to resolve. Can be a string, dict, list, or any other type. |
| 122 | +
|
| 123 | + Returns: |
| 124 | + The resolved value with environment variable references replaced. |
| 125 | +
|
| 126 | + Raises: |
| 127 | + ValueError: If a referenced environment variable is not set. |
| 128 | + """ |
| 129 | + if isinstance(value, str): |
| 130 | + match = _ENV_VAR_PATTERN.match(value) |
| 131 | + if match: |
| 132 | + var_name = match.group(1) or match.group(2) |
| 133 | + env_value = os.environ.get(var_name) |
| 134 | + if env_value is None: |
| 135 | + raise ValueError(f"Environment variable '{var_name}' is not set") |
| 136 | + return env_value |
| 137 | + return value |
| 138 | + if isinstance(value, dict): |
| 139 | + return {k: _resolve_env_vars(v) for k, v in value.items()} |
| 140 | + if isinstance(value, list): |
| 141 | + return [_resolve_env_vars(item) for item in value] |
| 142 | + return value |
| 143 | + |
| 144 | + |
| 145 | +def _create_model_from_dict(model_config: dict[str, Any]) -> Any: |
| 146 | + """Create a Model instance from a provider config dict. |
| 147 | +
|
| 148 | + Routes the config to the appropriate model class based on the ``provider`` field, |
| 149 | + then delegates to the class's ``from_dict`` method. All imports are lazy to avoid |
| 150 | + requiring optional dependencies that are not installed. |
| 151 | +
|
| 152 | + Args: |
| 153 | + model_config: Dict containing at least a ``provider`` key and provider-specific params. |
| 154 | +
|
| 155 | + Returns: |
| 156 | + A configured Model instance for the specified provider. |
| 157 | +
|
| 158 | + Raises: |
| 159 | + ValueError: If the provider name is not recognized. |
| 160 | + ImportError: If the provider's optional dependencies are not installed. |
| 161 | + """ |
| 162 | + config = model_config.copy() |
| 163 | + provider = config.pop("provider") |
| 164 | + |
| 165 | + class_name = PROVIDER_MAP.get(provider) |
| 166 | + if class_name is None: |
| 167 | + supported = ", ".join(sorted(PROVIDER_MAP.keys())) |
| 168 | + raise ValueError(f"Unknown model provider: '{provider}'. Supported providers: {supported}") |
| 169 | + |
| 170 | + from .. import models |
| 171 | + |
| 172 | + model_cls = getattr(models, class_name) |
| 173 | + return model_cls.from_dict(config) |
| 174 | + |
53 | 175 |
|
54 | 176 | def config_to_agent(config: str | dict[str, Any], **kwargs: dict[str, Any]) -> Any: |
55 | 177 | """Create an Agent from a configuration file or dictionary. |
@@ -83,6 +205,12 @@ def config_to_agent(config: str | dict[str, Any], **kwargs: dict[str, Any]) -> A |
83 | 205 | Create agent from dictionary: |
84 | 206 | >>> config = {"model": "anthropic.claude-3-5-sonnet-20241022-v2:0", "tools": ["calculator"]} |
85 | 207 | >>> agent = config_to_agent(config) |
| 208 | +
|
| 209 | + Create agent with object model config: |
| 210 | + >>> config = { |
| 211 | + ... "model": {"provider": "openai", "model_id": "gpt-4o", "client_args": {"api_key": "$OPENAI_API_KEY"}} |
| 212 | + ... } |
| 213 | + >>> agent = config_to_agent(config) |
86 | 214 | """ |
87 | 215 | # Parse configuration |
88 | 216 | if isinstance(config, str): |
@@ -114,11 +242,20 @@ def config_to_agent(config: str | dict[str, Any], **kwargs: dict[str, Any]) -> A |
114 | 242 | raise ValueError(f"Configuration validation error at {error_path}: {e.message}") from e |
115 | 243 |
|
116 | 244 | # Prepare Agent constructor arguments |
117 | | - agent_kwargs = {} |
| 245 | + agent_kwargs: dict[str, Any] = {} |
| 246 | + |
| 247 | + # Handle model field — string vs object format |
| 248 | + model_value = config_dict.get("model") |
| 249 | + if isinstance(model_value, dict): |
| 250 | + # Object format: resolve env vars and create Model instance via factory |
| 251 | + resolved_config = _resolve_env_vars(model_value) |
| 252 | + agent_kwargs["model"] = _create_model_from_dict(resolved_config) |
| 253 | + elif model_value is not None: |
| 254 | + # String format (backward compat): pass directly as model_id to Agent |
| 255 | + agent_kwargs["model"] = model_value |
118 | 256 |
|
119 | | - # Map configuration keys to Agent constructor parameters |
| 257 | + # Map remaining configuration keys to Agent constructor parameters |
120 | 258 | config_mapping = { |
121 | | - "model": "model", |
122 | 259 | "prompt": "system_prompt", |
123 | 260 | "tools": "tools", |
124 | 261 | "name": "name", |
|
0 commit comments