Models¶
Native providers: OpenAI (openai:), Anthropic (anthropic:),
Azure OpenAI (azure:) and Amazon Bedrock (bedrock:). Also
routed by name: a table of OpenAI-compatible prefixes, such as ollama:,
vllm:, lmstudio:, groq:, together:, openrouter:, deepseek:,
mistral: and gemini:. Each prefix has its own default endpoint and
API-key variable. Any other OpenAI-compatible endpoint works through
openai-compatible:<model> with an explicit base_url=. See
OpenAI-compatible providers.
A model is a string — the prefix before the colon selects the provider.
For the concepts, start with Model providers.
Registry¶
String factory — routes "openai:gpt-4o",
"anthropic:claude-sonnet-4-6", etc. to the right client.
get_model ¶
Get a model from a string identifier.
Format: "provider:model_name"
Examples:
- "openai:gpt-4o"
- "anthropic:claude-sonnet-4-6"
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_string
|
str
|
Model identifier in "provider:model" format |
required |
**kwargs
|
Any
|
Provider-specific configuration |
{}
|
Returns:
| Type | Description |
|---|---|
ModelProtocol
|
Model instance |
Raises:
| Type | Description |
|---|---|
ValueError
|
If provider is unknown or model string is invalid |
Source code in src/locus/models/registry.py
list_providers ¶
register_provider ¶
Register a model provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Provider prefix (e.g., "openai", "anthropic") |
required |
factory
|
Callable[..., ModelProtocol]
|
Factory function that takes model name and kwargs |
required |
Source code in src/locus/models/registry.py
CompatibleProvider
dataclass
¶
CompatibleProvider(prefix: str, base_url: str | None, env_key: str, label: str, env_base_url: str | None = None, requires_key: bool = True)
One OpenAI-compatible endpoint, addressable by prefix.
Attributes:
| Name | Type | Description |
|---|---|---|
prefix |
str
|
The |
base_url |
str | None
|
Default endpoint. |
env_key |
str
|
Environment variable holding the API key. |
label |
str
|
Human-readable name, used in the provider table and errors. |
env_base_url |
str | None
|
Provider-conventional environment variable that
overrides |
requires_key |
bool
|
When |
locus_base_url_env
property
¶
The LOCUS_-namespaced base-URL override for this provider.
resolve_base_url ¶
Resolve the endpoint: explicit > LOCUS_ override > vendor env > default.
Source code in src/locus/models/providers/__init__.py
resolve_api_key ¶
Resolve the API key: explicit > provider env > placeholder-or-None.
Source code in src/locus/models/providers/__init__.py
register_compatible_providers ¶
Register every entry in :data:COMPATIBLE_PROVIDERS.
Called from the registry's default registration. Safe to call twice — registration is a dict assignment keyed by prefix.
Source code in src/locus/models/providers/__init__.py
Base contract¶
Every model provider implements ModelProtocol. RequestBuilder and
ResponseParser are the per-provider seams for translating between
Locus's ModelConfig / Message types and the provider's wire
format.
ModelProtocol ¶
Bases: Protocol
Protocol defining the model interface.
ModelConfig ¶
Bases: BaseModel
Base configuration for models.
ModelResponse ¶
Bases: BaseModel
Response from a model completion.
ResponseParser ¶
OCI Generative AI¶
Needs the oci extra (pip install "locus-sdk[oci]"). See
OCI Generative AI and
OCI GenAI models. get_model("oci:<model-id>")
picks the transport automatically.
OpenAI-compatible transport (V1)¶
OCIChatCompletionsModel targets the /openai/v1 transport — real SSE
streaming, day-0 support for new OpenAI / Meta / xAI / Mistral / Gemini
releases. Use this for everything except Cohere R-series and Dedicated AI
Cluster endpoints.
OCIChatCompletionsModel ¶
OCIChatCompletionsModel(model: str, *, profile: str | None = None, auth_type: str | None = None, compartment_id: str | None = None, region: str = DEFAULT_OCI_GENAI_REGION, config_file: str = '~/.oci/config', base_url: str | None = None, max_tokens: int = 4096, temperature: float = 0.7, **kwargs: Any)
Bases: OpenAIModel
OCI GenAI model accessed through the /openai/v1 endpoint.
Reuses :class:OpenAIModel for message conversion, tool handling,
response parsing, and streaming. The only thing this class adds is
the OCI-specific auth wiring.
Pass exactly one of profile, auth_type.
Initialize the OCI OpenAI-compat model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
OCI model identifier (e.g. |
required |
profile
|
str | None
|
OCI config profile name from |
None
|
auth_type
|
str | None
|
|
None
|
compartment_id
|
str | None
|
OCI compartment OCID, sent as
|
None
|
region
|
str
|
OCI region hosting the inference endpoint. |
DEFAULT_OCI_GENAI_REGION
|
config_file
|
str
|
Path to the OCI config file (used with |
'~/.oci/config'
|
base_url
|
str | None
|
Override the derived endpoint URL (e.g. for a custom
realm). Defaults to the OpenAI-compat URL for |
None
|
max_tokens
|
int
|
Default max tokens. For |
4096
|
temperature
|
float
|
Default sampling temperature. |
0.7
|
**kwargs
|
Any
|
Forwarded to :class: |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If zero or both auth modes are set, if |
Source code in src/locus/models/providers/oci/openai_compat.py
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
client
property
¶
Build the AsyncOpenAI client wired with the OCI request signer.
supports_structured_output
property
¶
Native response_format={"type":"json_schema",...} support.
OpenAI's chat-completions API accepts a JSON-schema response_format and guarantees a parseable instance. The agent loop uses this property to skip the prompted-JSON fallback when the provider ships native structured output.
close
async
¶
__aenter__
async
¶
__aexit__
async
¶
ainvoke
async
¶
LangChain-compatible alias — returns Message (AIMessage equivalent).
Source code in src/locus/models/native/openai.py
bind_tools ¶
LangChain-compatible bind_tools.
Source code in src/locus/models/native/openai.py
OCIChatCompletionsConfig ¶
Bases: OpenAIConfig
Configuration for :class:OCIChatCompletionsModel.
Inherits all OpenAI knobs from :class:OpenAIConfig. Adds region,
profile, auth_type, compartment_id, and config_file for OCI
auth selection.
Cohere R-series and Dedicated AI Cluster transport (SDK)¶
OCIModel targets the OCI SDK's /20231130/actions/v1 endpoint —
required for cohere.command-r-* (Cohere's Chat API shape isn't served
on the /openai/v1 transport) and for ocid1.generativeaiendpoint.…
Dedicated AI Cluster endpoints.
OCIModel ¶
OCIModel(model_id: str = 'cohere.command-r-plus', compartment_id: str | None = None, profile_name: str = 'DEFAULT', auth_type: str | OCIAuthType | None = None, config_file: str = '~/.oci/config', service_endpoint: str | None = None, region: str | None = None, max_tokens: int = 4096, temperature: float = 0.7, profile: str | None = None, **kwargs: Any)
Bases: BaseModel
OCI GenAI model provider.
Automatically selects the appropriate provider based on model_id: - cohere.command-r-* → CohereProvider - cohere.command-a-* → GenericProvider (A series uses generic format) - meta., openai., google., xai., mistral.* → GenericProvider
Example
model = OCIModel( ... model_id="openai.gpt-5.1-chat-latest", ... profile_name="DEFAULT", ... auth_type="api_key", ... ) response = await model.complete([Message.user("Hello!")])
Initialize OCI GenAI model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
OCI model identifier (e.g., "openai.gpt-oss-20b", "cohere.command-r-plus") |
'cohere.command-r-plus'
|
compartment_id
|
str | None
|
OCI compartment OCID (defaults to |
None
|
profile_name
|
str
|
OCI config profile name from ~/.oci/config |
'DEFAULT'
|
auth_type
|
str | OCIAuthType | None
|
Authentication type (api_key, security_token,
instance_principal). When |
None
|
config_file
|
str
|
Path to OCI config file |
'~/.oci/config'
|
service_endpoint
|
str | None
|
Full OCI GenAI service endpoint URL. Takes
precedence over |
None
|
region
|
str | None
|
OCI region for the GenAI inference endpoint (e.g.
|
None
|
max_tokens
|
int
|
Maximum tokens for response |
4096
|
temperature
|
float
|
Model temperature (0.0-1.0) |
0.7
|
profile
|
str | None
|
Alias for |
None
|
**kwargs
|
Any
|
Additional model parameters |
{}
|
Source code in src/locus/models/providers/oci/__init__.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
supports_structured_output
property
¶
OCI's native SDK transport (Cohere R-series) doesn't expose
OpenAI-style response_format. Use the V1 transport
(OCIChatCompletionsModel) for that.
complete
async
¶
complete(messages: list[Message], tools: list[dict[str, Any]] | None = None, **kwargs: Any) -> ModelResponse
Complete a chat request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[Message]
|
Conversation history |
required |
tools
|
list[dict[str, Any]] | None
|
Tool schemas in OpenAI format (overrides bound tools if set) |
None
|
**kwargs
|
Any
|
Additional OCI-specific options |
{}
|
Returns:
| Type | Description |
|---|---|
ModelResponse
|
Model response with message and metadata |
Source code in src/locus/models/providers/oci/__init__.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
ainvoke
async
¶
LangChain-compatible alias — returns Message (AIMessage equivalent).
Source code in src/locus/models/providers/oci/__init__.py
bind_tools ¶
LangChain-compatible bind_tools — stores tool schemas and passes them on complete().
Source code in src/locus/models/providers/oci/__init__.py
stream
async
¶
stream(messages: list[Message], tools: list[dict[str, Any]] | None = None, **kwargs: Any) -> AsyncIterator[ModelChunkEvent]
Stream a chat response via the OCI GenAI SDK.
Sets is_stream=True on the chat request so the SDK returns
an SSE event stream. Each data: event carries a JSON chunk
with message.content deltas and (on the last event)
finishReason. Works for both OnDemandServingMode
(model id) and DedicatedServingMode (DAC endpoint OCID).
On any exception the stream falls back to the non-streaming
complete() path and yields a single chunk with the full
content — robust to providers that reject is_stream.
Source code in src/locus/models/providers/oci/__init__.py
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | |
OCIConfig ¶
OCIAuthType ¶
Bases: StrEnum
OCI authentication types.
Responses API transport (opt-in)¶
OCIResponsesModel targets the server-stateful /v1/responses endpoint.
See OCI Responses API.
OCIResponsesModel ¶
OCIResponsesModel(model: str, *, profile: str | None = None, auth_type: str | None = None, compartment_id: str | None = None, project_ocid: str | None = None, region: str = DEFAULT_OCI_GENAI_REGION, config_file: str = '~/.oci/config', base_url: str | None = None, max_output_tokens: int = 4096, temperature: float = 0.7, request_timeout: float = 600.0, store: bool = True, **kwargs: Any)
Bases: BaseModel
OCI GenAI model via the Responses API.
Server-stateful transport — Locus's runtime loop sends only the
input added since the last turn and threads
previous_response_id through :attr:AgentState.provider_state
so the OCI server can reattach to the existing thread.
Example
model = OCIResponsesModel( ... model="openai.gpt-5.5-pro", ... profile="LUIGI_FRA_API", ... region="us-chicago-1", ... ) agent = Agent(model=model, tools=[my_tool]) result = agent.run_sync("Plan a trip to Tokyo.")
Pass exactly one of profile, auth_type.
Initialize the OCI Responses model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
OCI model identifier (e.g. |
required |
profile
|
str | None
|
OCI config profile name in |
None
|
auth_type
|
str | None
|
|
None
|
compartment_id
|
str | None
|
OCI compartment OCID, sent as
|
None
|
project_ocid
|
str | None
|
Optional GenAI Project OCID. Locus does not
require this — leave unset for the standard path.
|
None
|
region
|
str
|
OCI region (default us-chicago-1). |
DEFAULT_OCI_GENAI_REGION
|
config_file
|
str
|
Path to the OCI config file (with |
'~/.oci/config'
|
base_url
|
str | None
|
Override the derived endpoint URL. |
None
|
max_output_tokens
|
int
|
Default output token cap. |
4096
|
temperature
|
float
|
Default sampling temperature. |
0.7
|
request_timeout
|
float
|
HTTP request timeout in seconds. |
600.0
|
store
|
bool
|
When True (default) the OCI server persists responses
and the agent uses |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If zero or both auth modes are set, if
|
Source code in src/locus/models/providers/oci/responses.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
server_stateful
property
¶
Whether this model relies on OCI-side response persistence.
Reflects :attr:OCIResponsesConfig.store. The agent runtime
reads this to decide between the latest-turn-slice +
provider_state flow (True) and the stateless full-history
flow (False). ZDR tenancies set store=False at construction
so the agent automatically picks the stateless path and avoids
OCIResponsesStateLostError on every turn.
complete
async
¶
complete(messages: list[Message], tools: list[dict[str, Any]] | None = None, *, provider_state: dict[str, Any] | None = None, **kwargs: Any) -> ModelResponse
Send a Responses request and return the parsed reply.
provider_state is the continuation token from
:attr:AgentState.provider_state. On turn 1 it's None; on
subsequent turns it carries {"previous_response_id": <id>}.
Source code in src/locus/models/providers/oci/responses.py
stream
async
¶
stream(messages: list[Message], tools: list[dict[str, Any]] | None = None, *, provider_state: dict[str, Any] | None = None, **kwargs: Any) -> AsyncIterator[ModelChunkEvent]
Stream a Responses request as Locus ModelChunkEvents.
Accumulates function_call_arguments.delta events per call
id and emits a single :class:ToolCall per id once arguments
finish. Text deltas emit one event per chunk. done=True
fires on response.completed carrying the continuation id
in provider_state.
Source code in src/locus/models/providers/oci/responses.py
aclose
async
¶
OCIResponsesConfig ¶
Bases: BaseModel
Configuration for :class:OCIResponsesModel.
OpenAI¶
OpenAIModel ¶
OpenAIModel(model: str = 'gpt-4o', api_key: str | None = None, base_url: str | None = None, max_tokens: int = 4096, temperature: float = 0.7, **kwargs: Any)
Bases: BaseModel
OpenAI model provider.
Supports GPT-4o, GPT-4, o1, o3, gpt-5.x models with streaming and tool
calling. Speaks both OpenAI wire APIs: chat-completions (the default)
and the Responses API, selected via api= on the config or
automatically for model families that require it (gpt-5.6-*, which
reject function tools on chat-completions whenever reasoning is on).
Example
model = OpenAIModel(model="gpt-4o") response = await model.complete([Message.user("Hello!")])
Initialize OpenAI model.
Source code in src/locus/models/native/openai.py
supports_structured_output
property
¶
Native response_format={"type":"json_schema",...} support.
OpenAI's chat-completions API accepts a JSON-schema response_format and guarantees a parseable instance. The agent loop uses this property to skip the prompted-JSON fallback when the provider ships native structured output.
client
property
¶
Get or create the OpenAI client.
The client is configured with explicit max_retries and
timeout from :class:OpenAIConfig so transient errors
(429, 5xx, network resets) don't kill the agent loop on first
try. The openai SDK retries with exponential backoff between
attempts.
Bound to the event loop that built it: AsyncOpenAI wraps an
httpx pool, so a client cached across two loops fails on the second
with APIConnectionError: Connection error — which reads as a
provider outage and sends you to check your key and their status page.
See :func:~locus.core.loop_bound.loop_bound.
close
async
¶
__aenter__
async
¶
__aexit__
async
¶
complete
async
¶
complete(messages: list[Message], tools: list[dict[str, Any]] | None = None, **kwargs: Any) -> ModelResponse
Complete a chat request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[Message]
|
Conversation history |
required |
tools
|
list[dict[str, Any]] | None
|
Tool schemas in OpenAI format |
None
|
**kwargs
|
Any
|
Additional OpenAI-specific options |
{}
|
Returns:
| Type | Description |
|---|---|
ModelResponse
|
Model response with message and metadata |
Source code in src/locus/models/native/openai.py
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 | |
ainvoke
async
¶
LangChain-compatible alias — returns Message (AIMessage equivalent).
Source code in src/locus/models/native/openai.py
bind_tools ¶
LangChain-compatible bind_tools.
Source code in src/locus/models/native/openai.py
stream
async
¶
stream(messages: list[Message], tools: list[dict[str, Any]] | None = None, **kwargs: Any) -> AsyncIterator[ModelChunkEvent]
Stream a chat response.
With stream_reconnects (0 by default) each turn is read whole before any of it
is yielded, and a turn whose connection drops part way is asked again, up to that
many times. Partial output is never yielded, so the caller never sees half a turn
twice. Inside an NVIDIA OpenShell box a connection is cut whenever the box's policy
generation moves on (its first settings poll after start does so), and the OpenAI
client retries a request that failed but never a stream that broke after it began.
A refusal (an HTTP status, e.g. a guard's token_budget_exhausted) is not retried.
Source code in src/locus/models/native/openai.py
OpenAIConfig ¶
Anthropic¶
AnthropicModel ¶
AnthropicModel(model: str = 'claude-sonnet-4-6', api_key: str | None = None, base_url: str | None = None, max_tokens: int = 4096, temperature: float = 0.7, prompt_cache: bool = False, default_headers: dict[str, str] | None = None, auth_token: str | None = None, **kwargs: Any)
Bases: BaseModel
Anthropic model provider.
Supports Claude 4.6, 4.5, 3.5 models with streaming and tool calling.
Example
model = AnthropicModel(model="claude-sonnet-4-6") response = await model.complete([Message.user("Hello!")])
Source code in src/locus/models/native/anthropic.py
supports_structured_output
property
¶
Anthropic doesn't ship OpenAI-style response_format.
The agent loop falls back to the prompted-JSON path with post-hoc parsing for Anthropic models.
client
property
¶
Get or create the Anthropic client.
Configured with explicit max_retries + timeout so a
transient 529 (overloaded) / 5xx / connection reset doesn't
kill the agent loop on the first try. Retries use exponential
backoff inside the anthropic SDK.
base_url
property
¶
The endpoint requests go to: the configured one, else ANTHROPIC_BASE_URL.
wire_model
property
¶
The model id as the endpoint names it.
OpenRouter's Messages API takes its own slugs, so a Claude id is translated there; an id already written as a slug is sent unchanged.
close
async
¶
Close the underlying httpx client.
Agent.run_sync calls this in a finally block so the
loop-bound httpx connections are shut down inside the same
event loop that opened them. Without this, the next
asyncio.run invocation closes the prior loop and the
leftover client's __del__ later tries to aclose against
it, raising RuntimeError: Event loop is closed.
Source code in src/locus/models/native/anthropic.py
complete
async
¶
complete(messages: list[Message], tools: list[dict[str, Any]] | None = None, **kwargs: Any) -> ModelResponse
Complete a chat request.
Recognises an OpenAI-style response_format={"type": "json_schema", ...}
kwarg and translates it into Anthropic's tool-use mechanism: a synthetic
respond_with_schema tool is appended to the call and tool_choice
is pinned to it. The tool arguments are then surfaced as the message
content (canonical JSON) so callers can parse them with
:func:locus.core.structured.parse_structured exactly as they would
with native response_format providers.
Source code in src/locus/models/native/anthropic.py
stream
async
¶
stream(messages: list[Message], tools: list[dict[str, Any]] | None = None, **kwargs: Any) -> AsyncIterator[ModelChunkEvent]
Stream a chat response.
Sends the same request :meth:complete does — temperature, prompt
caching, native-tool betas and response_format included — and
reports the same usage, cache counters included.
Source code in src/locus/models/native/anthropic.py
AnthropicConfig ¶
Azure OpenAI¶
See Azure OpenAI.
AzureOpenAIModel ¶
AzureOpenAIModel(model: str, endpoint: str | None = None, api_version: str | None = None, api_key: str | None = None, **kwargs: Any)
Bases: OpenAIModel
Azure OpenAI provider.
Example
model = AzureOpenAIModel(model="gpt4o-prod") # a deployment name response = await model.complete([Message.user("Hello!")])
Source code in src/locus/models/native/azure.py
client
property
¶
An AsyncAzureOpenAI, which is an AsyncOpenAI subclass.
Loop-bound for the same reason as the OpenAI client: it wraps an httpx
pool, and one cached across two event loops fails on the second with
APIConnectionError — which reads as a provider outage rather than
the caching bug it is.
supports_structured_output
property
¶
Native response_format={"type":"json_schema",...} support.
OpenAI's chat-completions API accepts a JSON-schema response_format and guarantees a parseable instance. The agent loop uses this property to skip the prompted-JSON fallback when the provider ships native structured output.
close
async
¶
__aenter__
async
¶
__aexit__
async
¶
complete
async
¶
complete(messages: list[Message], tools: list[dict[str, Any]] | None = None, **kwargs: Any) -> ModelResponse
Complete a chat request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[Message]
|
Conversation history |
required |
tools
|
list[dict[str, Any]] | None
|
Tool schemas in OpenAI format |
None
|
**kwargs
|
Any
|
Additional OpenAI-specific options |
{}
|
Returns:
| Type | Description |
|---|---|
ModelResponse
|
Model response with message and metadata |
Source code in src/locus/models/native/openai.py
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 | |
ainvoke
async
¶
LangChain-compatible alias — returns Message (AIMessage equivalent).
Source code in src/locus/models/native/openai.py
bind_tools ¶
LangChain-compatible bind_tools.
Source code in src/locus/models/native/openai.py
stream
async
¶
stream(messages: list[Message], tools: list[dict[str, Any]] | None = None, **kwargs: Any) -> AsyncIterator[ModelChunkEvent]
Stream a chat response.
With stream_reconnects (0 by default) each turn is read whole before any of it
is yielded, and a turn whose connection drops part way is asked again, up to that
many times. Partial output is never yielded, so the caller never sees half a turn
twice. Inside an NVIDIA OpenShell box a connection is cut whenever the box's policy
generation moves on (its first settings poll after start does so), and the OpenAI
client retries a request that failed but never a stream that broke after it began.
A refusal (an HTTP status, e.g. a guard's token_budget_exhausted) is not retried.
Source code in src/locus/models/native/openai.py
AzureOpenAIConfig ¶
Amazon Bedrock¶
Needs the bedrock extra (pip install "locus-sdk[bedrock]"). See
Amazon Bedrock.
BedrockModel ¶
BedrockModel(model: str = 'us.amazon.nova-lite-v1:0', region: str | None = None, profile: str | None = None, max_tokens: int = 4096, temperature: float = 0.7, **kwargs: Any)
Bases: BaseModel
Amazon Bedrock provider, via the Converse API.
Example
model = BedrockModel(model="us.amazon.nova-micro-v1:0") response = await model.complete([Message.user("Hello!")])
Source code in src/locus/models/native/bedrock.py
supports_structured_output
property
¶
Converse has no response_format.
It could be emulated by forcing a single tool via toolChoice, the
way the Anthropic provider does — but toolChoice support varies by
model on Bedrock, and a structured-output path that works on Claude and
silently fails on Llama is worse than not claiming it. The agent loop
falls back to prompted JSON, which every Bedrock model handles.
client
property
¶
The bedrock-runtime client, built once and reused.
Deliberately not wrapped in :func:locus.core.loop_bound. That helper
exists for clients whose connection pool binds to the event loop that
created it — httpx, redis.asyncio, asyncpg. A botocore client is
synchronous and holds no loop reference, so it survives being used from
whatever thread :func:asyncio.to_thread happens to hand it to, and
rebuilding it per loop would only pay the (slow) client construction
cost again.
complete
async
¶
complete(messages: list[Message], tools: list[dict[str, Any]] | None = None, **kwargs: Any) -> ModelResponse
Complete a chat request through converse.
botocore is synchronous, so the call runs on a worker thread. Without that, every Bedrock request would block the event loop for its whole duration — which for an agent means no concurrent tool execution, no streaming consumer, and no timeout firing.
Source code in src/locus/models/native/bedrock.py
stream
async
¶
stream(messages: list[Message], tools: list[dict[str, Any]] | None = None, **kwargs: Any) -> AsyncIterator[ModelChunkEvent]
Stream a response through converse_stream.
botocore's event stream is a synchronous iterator, so it is drained on
a worker thread into a bounded thread-safe queue and read back with
:func:asyncio.to_thread. An asyncio.Queue would be the wrong tool:
its put_nowait is not safe to call from another thread, and the
resulting corruption shows up as dropped or duplicated chunks under
load rather than as an error.
Source code in src/locus/models/native/bedrock.py
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 | |
close
async
¶
Release the underlying client.