Skip to content

Providers

Bases: LLM

OpenAI LLM provider.

Implements the LLM interface for OpenAI's GPT models, including support for structured outputs via the responses.parse API.

The API key is read from the OPENAI_API_KEY environment variable.

Attributes:

Name Type Description
client

The async OpenAI client instance.

Example

llm = OpenAI( ... model="gpt-6.1-sol", ... input_cost=2.5, ... output_cost=10.0, ... ) response = await llm.get_response("Hello, GPT!")

Source code in majordomo_llm/providers/openai.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 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
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
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
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
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
418
419
420
421
422
class OpenAI(LLM):
    """OpenAI LLM provider.

    Implements the LLM interface for OpenAI's GPT models, including
    support for structured outputs via the responses.parse API.

    The API key is read from the ``OPENAI_API_KEY`` environment variable.

    Attributes:
        client: The async OpenAI client instance.

    Example:
        >>> llm = OpenAI(
        ...     model="gpt-6.1-sol",
        ...     input_cost=2.5,
        ...     output_cost=10.0,
        ... )
        >>> response = await llm.get_response("Hello, GPT!")
    """

    def __init__(
        self,
        model: str,
        input_cost: float,
        output_cost: float,
        supports_temperature_top_p: bool = True,
        use_web_search: bool = False,
        supports_image_input: bool = False,
        *,
        cached_input_cost: float | None = None,
        cache_write_cost: float | None = None,
        api_key: str | None = None,
        api_key_alias: str | None = None,
        base_url: str | None = None,
        default_headers: dict[str, str] | None = None,
    ) -> None:
        """Initialize the OpenAI provider.

        Args:
            model: The GPT model identifier (e.g., "gpt-6.1-sol", "gpt-5").
            input_cost: Cost per million input tokens in USD.
            output_cost: Cost per million output tokens in USD.
            supports_temperature_top_p: Whether temperature/top_p are supported.
            use_web_search: Enable Responses API ``web_search_preview`` tool.
            supports_image_input: Whether this model accepts image inputs.
            cached_input_cost: Cost per million cache-read tokens in USD. OpenAI
                reports cached tokens as a subset of input tokens, so this
                re-prices them below ``input_cost``.
            cache_write_cost: Unused by OpenAI (no distinct cache-write rate);
                accepted for a uniform factory signature.
            api_key: Optional API key. Defaults to ``OPENAI_API_KEY`` env var.
            api_key_alias: Optional human-readable name for the API key.
            base_url: Optional custom base URL for routing through a proxy.
            default_headers: Optional headers sent with every request.

        Raises:
            ConfigurationError: If no API key is provided and env var is not set.
        """
        resolved_api_key = resolve_api_key(api_key, "OPENAI_API_KEY", "OpenAI")
        super().__init__(
            provider="openai",
            model=model,
            input_cost=input_cost,
            output_cost=output_cost,
            cached_input_cost=cached_input_cost,
            cache_write_cost=cache_write_cost,
            supports_temperature_top_p=supports_temperature_top_p,
            use_web_search=use_web_search,
            supports_image_input=supports_image_input,
            api_key=resolved_api_key,
            api_key_alias=api_key_alias,
            base_url=base_url,
            default_headers=default_headers,
        )
        self.client = openai.AsyncOpenAI(
            api_key=resolved_api_key,
            base_url=self.base_url,
            default_headers=self.default_headers,
        )

    def _web_search_kwargs(self) -> dict[str, Any]:
        """Return ``tools=`` kwarg for the Responses API when web search is on.

        OpenAI bills the web_search_preview tool's tokens through normal output
        tokens, so no separate ``tool_use_cost`` is added.
        """
        if not self.use_web_search:
            return {}
        return {"tools": [{"type": "web_search_preview"}]}

    @retry_provider_call
    async def _get_response_impl(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        """Get a plain text response from OpenAI."""
        return await self._get_response(
            user_prompt, system_prompt, temperature, top_p, extra_headers=extra_headers
        )

    @retry_provider_call
    async def _get_response_with_images_impl(
        self,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        return await self._get_response(
            user_prompt,
            system_prompt,
            temperature,
            top_p,
            extra_headers=extra_headers,
            images=images,
        )

    async def _get_response(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        images: tuple[ImageInput, ...] = (),
    ) -> LLMResponse:
        """Internal method to get a response from OpenAI."""
        start_time = time.time()
        web_search_kwargs = self._web_search_kwargs()
        try:
            response = await self.client.responses.create(
                model=self.model,
                instructions=system_prompt,
                input=_openai_input(user_prompt, images),
                extra_headers=extra_headers,
                **web_search_kwargs,
                **self._sampling_params(temperature, top_p),
            )
        except openai.APIError as e:
            raise ProviderError(
                f"OpenAI API error: {e}",
                provider="openai",
                original_error=e,
            ) from e

        execution_time = time.time() - start_time
        assert response.usage is not None
        input_tokens = response.usage.input_tokens
        output_tokens = response.usage.output_tokens
        cached_tokens = response.usage.input_tokens_details.cached_tokens
        input_cost, output_cost, total_cost = self._calculate_costs(
            input_tokens, output_tokens, cached_tokens
        )

        return LLMResponse(
            content=response.output_text,
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            cached_tokens=cached_tokens,
            input_cost=input_cost,
            output_cost=output_cost,
            total_cost=total_cost,
            response_time=execution_time,
            deprecation_warning=self.deprecation_warning,
        )

    async def _get_response_stream_impl(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMStreamResponse:
        """Get a streaming text response from OpenAI."""
        state = _StreamState()
        web_search_kwargs = self._web_search_kwargs()

        try:
            response = await self.client.responses.create(
                model=self.model,
                instructions=system_prompt,
                input=user_prompt,
                stream=True,
                extra_headers=extra_headers,
                **web_search_kwargs,
                **self._sampling_params(temperature, top_p),
            )
        except openai.APIError as e:
            raise ProviderError(
                f"OpenAI API error: {e}",
                provider="openai",
                original_error=e,
            ) from e

        async def generator() -> AsyncIterator[str]:
            try:
                async for event in response:
                    if event.type == "response.output_text.delta":
                        yield event.delta
                    elif event.type == "response.completed":
                        assert event.response.usage is not None
                        state.input_tokens = event.response.usage.input_tokens
                        state.output_tokens = event.response.usage.output_tokens
                        cached = event.response.usage.input_tokens_details
                        state.cached_tokens = cached.cached_tokens
            except openai.APIError as e:
                raise ProviderError(
                    f"OpenAI API error: {e}",
                    provider="openai",
                    original_error=e,
                ) from e

        return LLMStreamResponse(stream=generator(), state=state, llm=self)

    async def _get_response_stream_with_images_impl(
        self,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMStreamResponse:
        state = _StreamState()
        web_search_kwargs = self._web_search_kwargs()
        try:
            response = await self.client.responses.create(
                model=self.model,
                instructions=system_prompt,
                input=_openai_input(user_prompt, images),
                stream=True,
                extra_headers=extra_headers,
                **web_search_kwargs,
                **self._sampling_params(temperature, top_p),
            )
        except openai.APIError as e:
            raise ProviderError(
                f"OpenAI API error: {e}", provider="openai", original_error=e
            ) from e

        async def generator() -> AsyncIterator[str]:
            try:
                async for event in response:
                    if event.type == "response.output_text.delta":
                        yield event.delta
                    elif event.type == "response.completed":
                        assert event.response.usage is not None
                        state.input_tokens = event.response.usage.input_tokens
                        state.output_tokens = event.response.usage.output_tokens
                        state.cached_tokens = (
                            event.response.usage.input_tokens_details.cached_tokens
                        )
            except openai.APIError as e:
                raise ProviderError(
                    f"OpenAI API error: {e}", provider="openai", original_error=e
                ) from e

        return LLMStreamResponse(stream=generator(), state=state, llm=self)

    async def _get_json_schema_response(
        self,
        user_prompt: str,
        response_schema: dict[str, object],
        system_prompt: str | None = None,
        schema_name: str = "Response",
        schema_description: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        """OpenAI-specific implementation using structured outputs with JSON Schema."""
        return await self._get_json_schema_response_common(
            user_prompt=user_prompt,
            images=(),
            response_schema=response_schema,
            system_prompt=system_prompt,
            schema_name=schema_name,
            schema_description=schema_description,
            temperature=temperature,
            top_p=top_p,
            extra_headers=extra_headers,
        )

    async def _get_json_schema_response_with_images(
        self,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        response_schema: dict[str, Any],
        system_prompt: str | None = None,
        schema_name: str = "Response",
        schema_description: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        return await self._get_json_schema_response_common(
            user_prompt=user_prompt,
            images=images,
            response_schema=response_schema,
            system_prompt=system_prompt,
            schema_name=schema_name,
            schema_description=schema_description,
            temperature=temperature,
            top_p=top_p,
            extra_headers=extra_headers,
        )

    async def _get_json_schema_response_common(
        self,
        *,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        response_schema: dict[str, Any],
        system_prompt: str | None,
        schema_name: str,
        schema_description: str | None,
        temperature: float | None,
        top_p: float | None,
        extra_headers: dict[str, str] | None,
    ) -> LLMResponse:
        start_time = time.time()
        strict_schema = _enforce_openai_strict_schema(response_schema)
        response_format: dict[str, object] = {
            "type": "json_schema",
            "name": schema_name,
            "schema": strict_schema,
            "strict": True,
        }
        if schema_description is not None:
            response_format["description"] = schema_description
        text_config: Any = {"format": response_format}
        web_search_kwargs = self._web_search_kwargs()

        try:
            response = await self.client.responses.create(
                model=self.model,
                instructions=system_prompt,
                input=_openai_input(user_prompt, images),
                text=text_config,
                extra_headers=extra_headers,
                **web_search_kwargs,
                **self._sampling_params(temperature, top_p),
            )
        except openai.APIError as e:
            raise ProviderError(
                f"OpenAI API error: {e}",
                provider="openai",
                original_error=e,
            ) from e

        execution_time = time.time() - start_time
        assert response.usage is not None
        input_tokens = response.usage.input_tokens
        output_tokens = response.usage.output_tokens
        cached_tokens = (
            getattr(
                getattr(response.usage, "input_tokens_details", None),
                "cached_tokens",
                0,
            )
            or 0
        )
        input_cost, output_cost, total_cost = self._calculate_costs(
            input_tokens, output_tokens, cached_tokens
        )

        result = LLMResponse(
            content=response.output_text,
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            cached_tokens=cached_tokens,
            input_cost=input_cost,
            output_cost=output_cost,
            total_cost=total_cost,
            response_time=execution_time,
        )
        # Priced before parsing, so a parse error carries what the call cost.
        with self._usage_on_parse_error(result):
            result.content = canonicalize_json_schema_output(result.content, response_schema)
        return result

__init__

__init__(model, input_cost, output_cost, supports_temperature_top_p=True, use_web_search=False, supports_image_input=False, *, cached_input_cost=None, cache_write_cost=None, api_key=None, api_key_alias=None, base_url=None, default_headers=None)

Initialize the OpenAI provider.

Parameters:

Name Type Description Default
model str

The GPT model identifier (e.g., "gpt-6.1-sol", "gpt-5").

required
input_cost float

Cost per million input tokens in USD.

required
output_cost float

Cost per million output tokens in USD.

required
supports_temperature_top_p bool

Whether temperature/top_p are supported.

True
use_web_search bool

Enable Responses API web_search_preview tool.

False
supports_image_input bool

Whether this model accepts image inputs.

False
cached_input_cost float | None

Cost per million cache-read tokens in USD. OpenAI reports cached tokens as a subset of input tokens, so this re-prices them below input_cost.

None
cache_write_cost float | None

Unused by OpenAI (no distinct cache-write rate); accepted for a uniform factory signature.

None
api_key str | None

Optional API key. Defaults to OPENAI_API_KEY env var.

None
api_key_alias str | None

Optional human-readable name for the API key.

None
base_url str | None

Optional custom base URL for routing through a proxy.

None
default_headers dict[str, str] | None

Optional headers sent with every request.

None

Raises:

Type Description
ConfigurationError

If no API key is provided and env var is not set.

Source code in majordomo_llm/providers/openai.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def __init__(
    self,
    model: str,
    input_cost: float,
    output_cost: float,
    supports_temperature_top_p: bool = True,
    use_web_search: bool = False,
    supports_image_input: bool = False,
    *,
    cached_input_cost: float | None = None,
    cache_write_cost: float | None = None,
    api_key: str | None = None,
    api_key_alias: str | None = None,
    base_url: str | None = None,
    default_headers: dict[str, str] | None = None,
) -> None:
    """Initialize the OpenAI provider.

    Args:
        model: The GPT model identifier (e.g., "gpt-6.1-sol", "gpt-5").
        input_cost: Cost per million input tokens in USD.
        output_cost: Cost per million output tokens in USD.
        supports_temperature_top_p: Whether temperature/top_p are supported.
        use_web_search: Enable Responses API ``web_search_preview`` tool.
        supports_image_input: Whether this model accepts image inputs.
        cached_input_cost: Cost per million cache-read tokens in USD. OpenAI
            reports cached tokens as a subset of input tokens, so this
            re-prices them below ``input_cost``.
        cache_write_cost: Unused by OpenAI (no distinct cache-write rate);
            accepted for a uniform factory signature.
        api_key: Optional API key. Defaults to ``OPENAI_API_KEY`` env var.
        api_key_alias: Optional human-readable name for the API key.
        base_url: Optional custom base URL for routing through a proxy.
        default_headers: Optional headers sent with every request.

    Raises:
        ConfigurationError: If no API key is provided and env var is not set.
    """
    resolved_api_key = resolve_api_key(api_key, "OPENAI_API_KEY", "OpenAI")
    super().__init__(
        provider="openai",
        model=model,
        input_cost=input_cost,
        output_cost=output_cost,
        cached_input_cost=cached_input_cost,
        cache_write_cost=cache_write_cost,
        supports_temperature_top_p=supports_temperature_top_p,
        use_web_search=use_web_search,
        supports_image_input=supports_image_input,
        api_key=resolved_api_key,
        api_key_alias=api_key_alias,
        base_url=base_url,
        default_headers=default_headers,
    )
    self.client = openai.AsyncOpenAI(
        api_key=resolved_api_key,
        base_url=self.base_url,
        default_headers=self.default_headers,
    )

Bases: LLM

Anthropic (Claude) LLM provider.

Implements the LLM interface for Anthropic's Claude models, including support for tool calling for structured outputs and optional web search.

The API key is read from the ANTHROPIC_API_KEY environment variable.

Attributes:

Name Type Description
client

The async Anthropic client instance.

Example

llm = Anthropic( ... model="claude-sonnet-5", ... input_cost=3.0, ... output_cost=15.0, ... ) response = await llm.get_response("Hello, Claude!")

Source code in majordomo_llm/providers/anthropic.py
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
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
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
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
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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
class Anthropic(LLM):
    """Anthropic (Claude) LLM provider.

    Implements the LLM interface for Anthropic's Claude models, including
    support for tool calling for structured outputs and optional web search.

    The API key is read from the ``ANTHROPIC_API_KEY`` environment variable.

    Attributes:
        client: The async Anthropic client instance.

    Example:
        >>> llm = Anthropic(
        ...     model="claude-sonnet-5",
        ...     input_cost=3.0,
        ...     output_cost=15.0,
        ... )
        >>> response = await llm.get_response("Hello, Claude!")
    """

    #: Anthropic reports cache-read/cache-write tokens separately from
    #: ``input_tokens``, so cache cost is added on top of the uncached input.
    _cache_accounting = "additive"

    def __init__(
        self,
        model: str,
        input_cost: float,
        output_cost: float,
        supports_temperature_top_p: bool = True,
        use_web_search: bool = False,
        supports_structured_outputs: bool = False,
        supports_image_input: bool = False,
        reasoning_effort: str | None = None,
        thinking: str | None = None,
        *,
        cached_input_cost: float | None = None,
        cache_write_cost: float | None = None,
        use_prompt_caching: bool = True,
        supports_forced_tool_choice: bool = True,
        api_key: str | None = None,
        api_key_alias: str | None = None,
        base_url: str | None = None,
        default_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> None:
        """Initialize the Anthropic provider.

        Args:
            model: The Claude model identifier (e.g., "claude-sonnet-5").
            input_cost: Cost per million input tokens in USD.
            output_cost: Cost per million output tokens in USD.
            supports_temperature_top_p: Whether temperature/top_p are supported.
            use_web_search: Enable web search. The factory only allows it on
                models with ``supports_web_search: true`` in ``llm_config.yaml``.
            supports_structured_outputs: Whether the model supports native
                structured outputs (constrained decoding via
                ``output_config.format``). When False, structured JSON requests
                fall back to forced tool calling. Defaults to False.
            supports_image_input: Whether this model accepts image inputs.
            reasoning_effort: Optional ``output_config.effort`` level applied to
                every request — one of ``low``, ``medium``, ``high``, ``xhigh``,
                ``max``. Controls thinking depth and overall token spend on the
                4.7+/5 generation. ``None`` (default) sends no effort, so the
                API default (``high``) applies. Register the same SKU under
                multiple YAML keys (via the ``model`` override) to expose
                distinct effort profiles.
            thinking: Optional ``thinking.type`` mode applied to every request —
                ``adaptive`` (Claude decides how much to think; the on-mode for
                the 4.6+/5 generation), ``disabled``, or ``between_tools``
                (how ``claude-sonnet-5-5`` spells "off"). Sent exactly as given;
                :func:`~majordomo_llm.factory.get_llm_instance` is what turns a
                model-neutral ``disabled`` into the model's own spelling.
                ``None`` (default) omits the field, which leaves the model's own
                default in force. That varies by model and by prompt: on a
                one-word prompt ``claude-opus-5`` and Fable 5 thought and the
                5.5 models did not, while ``claude-sonnet-5-5`` thought heavily
                on a long rewrite. Thinking is billed as output.
                Effort only meaningfully modulates depth when thinking is on.
                Note: ``claude-opus-5-5``, ``claude-fable-5-1`` and Fable 5
                reject every "off" value, and with thinking on ``max_tokens``
                covers thinking + answer, so a deep-thinking profile needs
                headroom for both. Raise it with the
                ``max_tokens`` key in ``llm_config.yaml`` or the per-request
                ``max_tokens`` argument; a response that hits the cap raises
                :class:`~majordomo_llm.exceptions.ResponseTruncatedError` rather
                than returning silently truncated content.
            cached_input_cost: Cost per million cache-read tokens in USD
                (``cache_read_input_tokens``), billed on top of uncached input.
            cache_write_cost: Cost per million cache-creation tokens in USD
                (``cache_creation_input_tokens``), billed on top of uncached input.
            use_prompt_caching: When ``True`` (default), the system prompt is sent
                with an ephemeral ``cache_control`` breakpoint so Anthropic caches
                it. Set ``False`` to disable prompt caching (e.g. for short,
                non-reused system prompts where the cache-write premium is wasted).
            supports_forced_tool_choice: Whether the model accepts a forced
                ``tool_choice`` (``type: "tool"`` / ``"any"``). Opus 5.5,
                Sonnet 5.5 and Fable 5.1 reject it with a 400. When ``False``,
                the web-search structured path finishes with ``tool_choice:
                auto`` plus an explicit instruction instead of forcing the
                schema tool, and ``supports_structured_outputs`` must be
                ``True`` because the forced-tool fallback is unavailable.
            api_key: Optional API key. Defaults to ``ANTHROPIC_API_KEY`` env var.
            api_key_alias: Optional human-readable name for the API key.
            base_url: Optional custom base URL for routing through a proxy.
            default_headers: Optional headers sent with every request.
            max_tokens: Default output cap for this model. ``None`` uses the
                library defaults (16000 non-streaming, 64000 streaming).

        Raises:
            ConfigurationError: If no API key is provided and env var is not set.
            ValueError: If ``reasoning_effort`` or ``thinking`` is invalid, or if
                the model supports neither native structured outputs nor a
                forced ``tool_choice``.
        """
        if reasoning_effort is not None and reasoning_effort not in _EFFORT_LEVELS:
            valid = ", ".join(sorted(_EFFORT_LEVELS))
            raise ValueError(
                f"Invalid Anthropic reasoning_effort '{reasoning_effort}'. Valid: {valid}"
            )
        if thinking is not None and thinking not in _THINKING_MODES:
            valid = ", ".join(sorted(_THINKING_MODES))
            raise ValueError(f"Invalid Anthropic thinking mode '{thinking}'. Valid: {valid}")
        if not supports_forced_tool_choice and not supports_structured_outputs:
            raise ValueError(
                f"Anthropic model '{model}' rejects a forced tool_choice, so it must set "
                f"supports_structured_outputs=True; there is no other structured-output path."
            )
        resolved_api_key = resolve_api_key(api_key, "ANTHROPIC_API_KEY", "Anthropic")
        self.supports_structured_outputs = supports_structured_outputs
        self.supports_forced_tool_choice = supports_forced_tool_choice
        self.reasoning_effort = reasoning_effort
        self.thinking = thinking
        super().__init__(
            provider="anthropic",
            model=model,
            input_cost=input_cost,
            output_cost=output_cost,
            cached_input_cost=cached_input_cost,
            cache_write_cost=cache_write_cost,
            use_prompt_caching=use_prompt_caching,
            supports_temperature_top_p=supports_temperature_top_p,
            use_web_search=use_web_search,
            supports_image_input=supports_image_input,
            api_key=resolved_api_key,
            api_key_alias=api_key_alias,
            base_url=base_url,
            default_headers=default_headers,
            max_tokens=max_tokens,
        )
        self.client = anthropic.AsyncAnthropic(
            api_key=resolved_api_key,
            base_url=self.base_url,
            default_headers=self.default_headers,
        )

    def _resolve_nonstreaming_max_tokens(self, max_tokens: int | None) -> int:
        """Resolve the cap for a non-streaming call, rejecting one the SDK cannot send.

        Args:
            max_tokens: Per-request override, or None.

        Returns:
            The cap to send.

        Raises:
            InvalidRequestError: If the resolved cap exceeds
                :data:`MAX_NONSTREAMING_TOKENS`.
        """
        resolved = self._resolve_max_tokens(max_tokens)
        if resolved > MAX_NONSTREAMING_TOKENS:
            raise InvalidRequestError(
                f"max_tokens={resolved} exceeds the {MAX_NONSTREAMING_TOKENS} limit the "
                f"Anthropic SDK allows on a non-streaming request. Lower it, or use "
                f"get_response_stream(), which has no such limit."
            )
        return resolved

    def _config_create_kwargs(self, fmt: dict[str, Any] | None = None) -> dict[str, Any]:
        """Build config-derived ``messages.create`` kwargs, for splatting.

        Combines the optional structured-output ``format`` with the configured
        ``reasoning_effort`` (both under ``output_config``) and the configured
        ``thinking`` mode. Returns ``{}`` (a no-op splat) when none are present,
        so callers can uniformly write ``**self._config_create_kwargs()`` without
        a conditional.
        """
        kwargs: dict[str, Any] = {}
        output_config: dict[str, Any] = {}
        if fmt is not None:
            output_config["format"] = fmt
        if self.reasoning_effort is not None:
            output_config["effort"] = self.reasoning_effort
        if output_config:
            kwargs["output_config"] = output_config
        if self.thinking is not None:
            kwargs["thinking"] = {"type": self.thinking}
        return kwargs

    # Anthropic bills server-side web search at $10 per 1,000 requests.
    _WEB_SEARCH_COST_PER_REQUEST = 0.01

    def _compute_web_search_cost(self, response: Any) -> float:
        """Return the per-call web-search fee charged by Anthropic.

        Reads ``response.usage.server_tool_use.web_search_requests`` which is
        populated only when the web_search tool was actually invoked.
        """
        return _web_search_requests(response.usage) * self._WEB_SEARCH_COST_PER_REQUEST

    @retry_provider_call
    async def _get_response_impl(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        """Get a plain text response from Anthropic."""
        if system_prompt is None:
            system_prompt = "You are a helpful assistant"
        start_time = time.time()

        messages = _anthropic_user_message(user_prompt)
        system_message = _anthropic_system_prompt(system_prompt, self.use_prompt_caching)

        tools: list[Any] = []
        if self.use_web_search:
            tools.append(WebSearchTool20250305Param(type="web_search_20250305", name="web_search"))

        resolved_max_tokens = self._resolve_nonstreaming_max_tokens(max_tokens)

        try:
            response_message = await self.client.messages.create(
                model=self.model,
                max_tokens=resolved_max_tokens,
                system=system_message,
                messages=messages,
                tools=tools,
                tool_choice=ToolChoiceAutoParam(type="auto"),
                **self._config_create_kwargs(),
                extra_headers=extra_headers,
                **self._sampling_params(temperature, top_p),
            )
        except anthropic.APIError as e:
            raise ProviderError(
                f"Anthropic API error: {e}",
                provider="anthropic",
                original_error=e,
            ) from e

        return self._finalize_text_response(
            response_message, resolved_max_tokens, time.time() - start_time
        )

    @retry_provider_call
    async def _get_response_with_images_impl(
        self,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        if system_prompt is None:
            system_prompt = "You are a helpful assistant"
        start_time = time.time()
        resolved_max_tokens = self._resolve_nonstreaming_max_tokens(max_tokens)
        tools: list[Any] = []
        if self.use_web_search:
            tools.append(WebSearchTool20250305Param(type="web_search_20250305", name="web_search"))
        try:
            response_message = await self.client.messages.create(
                model=self.model,
                max_tokens=resolved_max_tokens,
                system=_anthropic_system_prompt(system_prompt, self.use_prompt_caching),
                messages=_anthropic_user_message(user_prompt, images),
                tools=tools,
                tool_choice=ToolChoiceAutoParam(type="auto"),
                **self._config_create_kwargs(),
                extra_headers=extra_headers,
                **self._sampling_params(temperature, top_p),
            )
        except anthropic.APIError as e:
            raise ProviderError(
                f"Anthropic API error: {e}", provider="anthropic", original_error=e
            ) from e

        return self._finalize_text_response(
            response_message, resolved_max_tokens, time.time() - start_time
        )

    def _finalize_text_response(
        self, response_message: Any, max_tokens: int, execution_time: float
    ) -> LLMResponse:
        """Price a text response and raise if it was cut off at ``max_tokens``.

        Priced before the truncation check, so a truncated call's error carries
        what it cost.
        """
        content = _join_text_blocks(
            block.text for block in response_message.content if block.type == "text"
        )
        usage = self._priced_usage(
            response_message.usage.input_tokens,
            response_message.usage.output_tokens,
            response_message.usage.cache_read_input_tokens or 0,
            response_message.usage.cache_creation_input_tokens or 0,
            execution_time,
            tool_use_cost=self._compute_web_search_cost(response_message),
        )
        self._check_truncation(
            response_message.stop_reason,
            max_tokens,
            response_message.usage.output_tokens,
            content,
            usage=usage,
        )
        return LLMResponse(
            content=content,
            **usage_fields(usage),
            deprecation_warning=self.deprecation_warning,
            stop_reason=response_message.stop_reason,
        )

    async def _get_response_stream_impl(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMStreamResponse:
        """Get a streaming text response from Anthropic."""
        if system_prompt is None:
            system_prompt = "You are a helpful assistant"

        state = _StreamState()
        resolved_max_tokens = self._resolve_max_tokens(max_tokens, streaming=True)
        messages = _anthropic_user_message(user_prompt)
        system_message = _anthropic_system_prompt(system_prompt, self.use_prompt_caching)

        try:
            response = await self.client.messages.create(
                model=self.model,
                max_tokens=resolved_max_tokens,
                system=system_message,
                messages=messages,
                stream=True,
                **self._config_create_kwargs(),
                extra_headers=extra_headers,
                **self._sampling_params(temperature, top_p),
            )
        except anthropic.APIError as e:
            raise ProviderError(
                f"Anthropic API error: {e}",
                provider="anthropic",
                original_error=e,
            ) from e

        async def generator() -> AsyncIterator[str]:
            try:
                async for event in response:
                    if event.type == "message_start":
                        state.input_tokens = event.message.usage.input_tokens
                        state.cached_tokens = event.message.usage.cache_read_input_tokens or 0
                        state.cache_creation_tokens = (
                            event.message.usage.cache_creation_input_tokens or 0
                        )
                    elif event.type == "content_block_delta" and event.delta.type == "text_delta":
                        yield event.delta.text
                    elif event.type == "message_delta":
                        state.output_tokens = event.usage.output_tokens
                        state.stop_reason = event.delta.stop_reason
            except anthropic.APIError as e:
                raise ProviderError(
                    f"Anthropic API error: {e}",
                    provider="anthropic",
                    original_error=e,
                ) from e
            # Raised after the last chunk is yielded, so a truncated stream fails
            # the same way a truncated non-streaming call does rather than ending
            # quietly mid-sentence.
            self._check_truncation(
                state.stop_reason, resolved_max_tokens, state.output_tokens, "", usage=None
            )

        return LLMStreamResponse(stream=generator(), state=state, llm=self)

    async def _get_response_stream_with_images_impl(
        self,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMStreamResponse:
        if system_prompt is None:
            system_prompt = "You are a helpful assistant"
        state = _StreamState()
        resolved_max_tokens = self._resolve_max_tokens(max_tokens, streaming=True)
        try:
            response = await self.client.messages.create(
                model=self.model,
                max_tokens=resolved_max_tokens,
                system=_anthropic_system_prompt(system_prompt, self.use_prompt_caching),
                messages=_anthropic_user_message(user_prompt, images),
                stream=True,
                **self._config_create_kwargs(),
                extra_headers=extra_headers,
                **self._sampling_params(temperature, top_p),
            )
        except anthropic.APIError as e:
            raise ProviderError(
                f"Anthropic API error: {e}", provider="anthropic", original_error=e
            ) from e

        async def generator() -> AsyncIterator[str]:
            try:
                async for event in response:
                    if event.type == "message_start":
                        state.input_tokens = event.message.usage.input_tokens
                        state.cached_tokens = event.message.usage.cache_read_input_tokens or 0
                        state.cache_creation_tokens = (
                            event.message.usage.cache_creation_input_tokens or 0
                        )
                    elif event.type == "content_block_delta" and event.delta.type == "text_delta":
                        yield event.delta.text
                    elif event.type == "message_delta":
                        state.output_tokens = event.usage.output_tokens
                        state.stop_reason = event.delta.stop_reason
            except anthropic.APIError as e:
                raise ProviderError(
                    f"Anthropic API error: {e}", provider="anthropic", original_error=e
                ) from e
            self._check_truncation(
                state.stop_reason, resolved_max_tokens, state.output_tokens, "", usage=None
            )

        return LLMStreamResponse(stream=generator(), state=state, llm=self)

    async def _get_json_schema_response(
        self,
        user_prompt: str,
        response_schema: dict[str, Any],
        system_prompt: str | None = None,
        schema_name: str = "Response",
        schema_description: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        """Anthropic structured JSON output."""
        return await self._get_json_schema_response_common(
            user_prompt=user_prompt,
            images=(),
            response_schema=response_schema,
            system_prompt=system_prompt,
            schema_name=schema_name,
            schema_description=schema_description,
            temperature=temperature,
            top_p=top_p,
            extra_headers=extra_headers,
            max_tokens=max_tokens,
        )

    async def _get_json_schema_response_with_images(
        self,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        response_schema: dict[str, Any],
        system_prompt: str | None = None,
        schema_name: str = "Response",
        schema_description: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        return await self._get_json_schema_response_common(
            user_prompt=user_prompt,
            images=images,
            response_schema=response_schema,
            system_prompt=system_prompt,
            schema_name=schema_name,
            schema_description=schema_description,
            temperature=temperature,
            top_p=top_p,
            extra_headers=extra_headers,
            max_tokens=max_tokens,
        )

    async def _get_json_schema_response_common(
        self,
        *,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        response_schema: dict[str, Any],
        system_prompt: str | None,
        schema_name: str,
        schema_description: str | None,
        temperature: float | None,
        top_p: float | None,
        extra_headers: dict[str, str] | None,
        max_tokens: int | None,
    ) -> LLMResponse:
        """Anthropic structured JSON output.

        Uses native structured outputs (constrained decoding via
        ``output_config.format``) on models that support it — the model
        physically cannot emit malformed or missing-key output. Falls back to
        forced tool calling on models without native support, and always uses
        the schema-tool path when web search is enabled (structured outputs and
        the ``web_search`` tool cannot be combined). That path forces the tool on
        its final turn only where the model allows it; see
        ``supports_forced_tool_choice``. Every path validates
        against the caller's original schema and rejects an empty/all-null
        result via :func:`canonicalize_json_schema_output`.
        """
        resolved_max_tokens = self._resolve_nonstreaming_max_tokens(max_tokens)

        if self.use_web_search:
            (
                response,
                usage,
                execution_time,
            ) = await self._json_schema_response_with_web_search_helper(
                user_prompt=user_prompt,
                response_schema=response_schema,
                system_prompt=system_prompt,
                schema_name=schema_name,
                schema_description=schema_description,
                extra_headers=extra_headers,
                max_tokens=resolved_max_tokens,
                images=images,
            )
            return self._finalize_json_schema_response(
                lambda: _extract_tool_use_content(response.content, schema_name),
                response,
                execution_time,
                response_schema,
                resolved_max_tokens,
                usage,
            )

        if self.supports_structured_outputs:
            return await self._native_json_schema_response(
                user_prompt=user_prompt,
                response_schema=response_schema,
                system_prompt=system_prompt,
                temperature=temperature,
                top_p=top_p,
                extra_headers=extra_headers,
                max_tokens=resolved_max_tokens,
                images=images,
            )

        return await self._forced_tool_json_schema_response(
            user_prompt=user_prompt,
            response_schema=response_schema,
            system_prompt=system_prompt,
            schema_name=schema_name,
            schema_description=schema_description,
            temperature=temperature,
            top_p=top_p,
            extra_headers=extra_headers,
            max_tokens=resolved_max_tokens,
            images=images,
        )

    async def _native_json_schema_response(
        self,
        user_prompt: str,
        response_schema: dict[str, Any],
        system_prompt: str | None,
        temperature: float | None,
        top_p: float | None,
        extra_headers: dict[str, str] | None,
        max_tokens: int,
        images: tuple[ImageInput, ...] = (),
    ) -> LLMResponse:
        """Native structured outputs via ``output_config.format`` (constrained decoding).

        The constrained decoder requires strict object schemas
        (``additionalProperties: false`` + full ``required``) and rejects a set
        of validation keywords (numeric/string/array bounds, ``pattern``,
        ``format``). Those are stripped from the wire schema and re-enforced
        post-hoc by validating the response against the original schema.
        """
        sent_schema = strip_unsupported_schema_constraints(
            enforce_strict_object_schema(response_schema)
        )
        output_config = self._config_create_kwargs(
            fmt={"type": "json_schema", "schema": sent_schema}
        )

        if system_prompt is None:
            system_prompt = "You are a helpful assistant."
        messages = _anthropic_user_message(user_prompt, images)
        system_message = _anthropic_system_prompt(system_prompt, self.use_prompt_caching)

        start_time = time.time()
        try:
            response = await self.client.messages.create(
                model=self.model,
                max_tokens=max_tokens,
                system=system_message,
                messages=messages,
                **output_config,
                extra_headers=extra_headers,
                **self._sampling_params(temperature, top_p),
            )
        except anthropic.APIError as e:
            raise ProviderError(
                f"Anthropic API error: {e}",
                provider="anthropic",
                original_error=e,
            ) from e

        execution_time = time.time() - start_time

        def extract() -> str:
            if response.stop_reason == "refusal":
                raise ResponseParsingError(
                    "Anthropic refused the structured-output request.",
                    raw_content=str(response.content),
                )
            return _extract_structured_text(response.content)

        return self._finalize_json_schema_response(
            extract, response, execution_time, response_schema, max_tokens
        )

    async def _forced_tool_json_schema_response(
        self,
        user_prompt: str,
        response_schema: dict[str, Any],
        system_prompt: str | None,
        schema_name: str,
        schema_description: str | None,
        temperature: float | None,
        top_p: float | None,
        extra_headers: dict[str, str] | None,
        max_tokens: int,
        images: tuple[ImageInput, ...] = (),
    ) -> LLMResponse:
        """Forced-tool fallback for models without native structured outputs.

        Sends the schema in strict form (full ``required``) so an empty ``{}``
        fails schema validation loudly; an all-null result is caught by the
        emptiness check in :func:`canonicalize_json_schema_output`. Both surface
        as :class:`EmptyStructuredResponseError`, which
        :func:`~majordomo_llm.retry.retry_provider_call` re-samples before it
        propagates.
        """
        tool_instruction = f"Use the {schema_name} tool to provide your answer."
        if system_prompt is None:
            system_prompt = f"You are a helpful assistant. {tool_instruction}"
        else:
            system_prompt = f"{system_prompt}\n\n{tool_instruction}"

        messages = _anthropic_user_message(user_prompt, images)
        system_message = _anthropic_system_prompt(system_prompt, self.use_prompt_caching)
        tools = [
            ToolParam(
                name=schema_name,
                description=schema_description
                or f"Provide a structured response using the {schema_name} JSON schema",
                input_schema=enforce_strict_object_schema(response_schema),
            )
        ]

        start_time = time.time()
        try:
            response = await self.client.messages.create(
                model=self.model,
                max_tokens=max_tokens,
                system=system_message,
                messages=messages,
                tools=tools,
                tool_choice=ToolChoiceToolParam(type="tool", name=schema_name),
                **self._config_create_kwargs(),
                extra_headers=extra_headers,
                **self._sampling_params(temperature, top_p),
            )
        except anthropic.APIError as e:
            raise ProviderError(
                f"Anthropic API error: {e}",
                provider="anthropic",
                original_error=e,
            ) from e

        execution_time = time.time() - start_time
        return self._finalize_json_schema_response(
            lambda: _extract_tool_use_content(response.content, schema_name),
            response,
            execution_time,
            response_schema,
            max_tokens,
        )

    def _finalize_json_schema_response(
        self,
        extract: Callable[[], Any],
        response: Any,
        execution_time: float,
        response_schema: dict[str, Any],
        max_tokens: int,
        usage: _TurnUsage | None = None,
    ) -> LLMResponse:
        """Price a structured response, then extract and validate its content.

        ``extract`` pulls the structured content out of ``response`` and may raise
        :class:`ResponseParsingError`. ``usage`` is the total across every turn
        that produced ``response``; it defaults to that response's own usage for
        the single-request paths.

        The call is priced first, so a truncation or parse error carries what
        the call cost. Truncation is checked before ``extract`` runs: a
        structured response cut off at the cap is malformed or missing, and
        reporting the cause beats a parse error that names the symptom.
        ``max_tokens`` caps each turn separately, so the check reads the final
        turn's output rather than the total.
        """
        if usage is None:
            usage = _TurnUsage.from_response(response)
        priced = self._priced_usage(
            usage.input_tokens,
            usage.output_tokens,
            usage.cached_tokens,
            usage.cache_creation_tokens,
            execution_time,
            tool_use_cost=usage.web_search_requests * self._WEB_SEARCH_COST_PER_REQUEST,
        )
        self._check_truncation(
            response.stop_reason,
            max_tokens,
            response.usage.output_tokens,
            _join_text_blocks(block.text for block in response.content if block.type == "text"),
            usage=priced,
        )
        with self._usage_on_parse_error(priced):
            content = canonicalize_json_schema_output(extract(), response_schema)

        return LLMResponse(
            content=content,
            **usage_fields(priced),
            stop_reason=response.stop_reason,
        )

    async def _json_schema_response_with_web_search_helper(
        self,
        user_prompt: str,
        response_schema: dict[str, Any],
        system_prompt: str | None = None,
        schema_name: str = "Response",
        schema_description: str | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int = DEFAULT_MAX_TOKENS,
        images: tuple[ImageInput, ...] = (),
    ) -> tuple[Any, _TurnUsage, float]:
        """Helper for web search with raw JSON-schema structured response.

        Returns the response carrying the schema tool call, the usage summed
        over every turn it took to get there, and the elapsed time.
        """
        structured_response_tool = ToolParam(
            name=schema_name,
            description=schema_description
            or f"Provide a structured response using the {schema_name} JSON schema",
            input_schema=enforce_strict_object_schema(response_schema),
        )
        web_search_tool = WebSearchTool20250305Param(
            name="web_search",
            type="web_search_20250305",
        )
        tools: list[Any] = [structured_response_tool, web_search_tool]

        tool_instruction = f"Use the {schema_name} tool to provide your answer."
        if system_prompt is None:
            system_prompt = f"You are a helpful assistant. {tool_instruction}"
        else:
            system_prompt = f"{system_prompt}\n\n{tool_instruction}"

        messages = _anthropic_user_message(user_prompt, images)
        system_message = _anthropic_system_prompt(system_prompt, self.use_prompt_caching)

        start_time = time.time()
        current_messages = messages.copy()
        search_count = 0
        usage = _TurnUsage()

        try:
            while search_count < 3:
                response = await self.client.messages.create(
                    model=self.model,
                    max_tokens=max_tokens,
                    system=system_message,
                    messages=current_messages,
                    tools=tools,
                    tool_choice=ToolChoiceAutoParam(type="auto"),
                    **self._config_create_kwargs(),
                    extra_headers=extra_headers,
                )
                usage += _TurnUsage.from_response(response)

                if response.stop_reason == "tool_use":
                    tool_uses = [block for block in response.content if block.type == "tool_use"]
                    if any(tool_use.name == schema_name for tool_use in tool_uses):
                        execution_time = time.time() - start_time
                        return response, usage, execution_time

                    if any(tool_use.name == "web_search" for tool_use in tool_uses):
                        logger.info("Web search initiated (turn %d)", search_count + 1)
                        search_count += 1
                        current_messages.append({"role": "assistant", "content": response.content})
                        current_messages.append(
                            {
                                "role": "user",
                                "content": (
                                    "Continue with your analysis. Use the structured response "
                                    "tool when ready to generate the final output."
                                ),
                            }
                        )
                        continue

                # The model answered in prose instead of calling the schema
                # tool. Its reply holds the search results, so it goes into the
                # final request; without it the model answers from memory.
                # Only a completed turn is carried: one cut short may end on a
                # search with no result, which is not a valid message.
                if response.stop_reason == "end_turn" and response.content:
                    current_messages.append({"role": "assistant", "content": response.content})
                break

            # Ask for the answer with only the schema tool on offer. Models that
            # reject a forced tool_choice get ``auto``; every model gets the
            # explicit instruction, which also closes the carried-over turn.
            final_tool_choice: ToolChoiceToolParam | ToolChoiceAutoParam
            if self.supports_forced_tool_choice:
                final_tool_choice = ToolChoiceToolParam(type="tool", name=schema_name)
            else:
                final_tool_choice = ToolChoiceAutoParam(type="auto")
            current_messages.append(
                {
                    "role": "user",
                    "content": (
                        f"Call the {schema_name} tool now with your final answer. "
                        "Do not reply in plain text."
                    ),
                }
            )

            final_response = await self.client.messages.create(
                model=self.model,
                max_tokens=max_tokens,
                system=_anthropic_system_prompt(system_prompt, self.use_prompt_caching),
                messages=current_messages,
                tools=[structured_response_tool],
                tool_choice=final_tool_choice,
                **self._config_create_kwargs(),
                extra_headers=extra_headers,
            )
        except anthropic.APIError as e:
            raise ProviderError(
                f"Anthropic API error: {e}",
                provider="anthropic",
                original_error=e,
            ) from e

        execution_time = time.time() - start_time
        return final_response, usage + _TurnUsage.from_response(final_response), execution_time

__init__

__init__(model, input_cost, output_cost, supports_temperature_top_p=True, use_web_search=False, supports_structured_outputs=False, supports_image_input=False, reasoning_effort=None, thinking=None, *, cached_input_cost=None, cache_write_cost=None, use_prompt_caching=True, supports_forced_tool_choice=True, api_key=None, api_key_alias=None, base_url=None, default_headers=None, max_tokens=None)

Initialize the Anthropic provider.

Parameters:

Name Type Description Default
model str

The Claude model identifier (e.g., "claude-sonnet-5").

required
input_cost float

Cost per million input tokens in USD.

required
output_cost float

Cost per million output tokens in USD.

required
supports_temperature_top_p bool

Whether temperature/top_p are supported.

True
use_web_search bool

Enable web search. The factory only allows it on models with supports_web_search: true in llm_config.yaml.

False
supports_structured_outputs bool

Whether the model supports native structured outputs (constrained decoding via output_config.format). When False, structured JSON requests fall back to forced tool calling. Defaults to False.

False
supports_image_input bool

Whether this model accepts image inputs.

False
reasoning_effort str | None

Optional output_config.effort level applied to every request — one of low, medium, high, xhigh, max. Controls thinking depth and overall token spend on the 4.7+/5 generation. None (default) sends no effort, so the API default (high) applies. Register the same SKU under multiple YAML keys (via the model override) to expose distinct effort profiles.

None
thinking str | None

Optional thinking.type mode applied to every request — adaptive (Claude decides how much to think; the on-mode for the 4.6+/5 generation), disabled, or between_tools (how claude-sonnet-5-5 spells "off"). Sent exactly as given; :func:~majordomo_llm.factory.get_llm_instance is what turns a model-neutral disabled into the model's own spelling. None (default) omits the field, which leaves the model's own default in force. That varies by model and by prompt: on a one-word prompt claude-opus-5 and Fable 5 thought and the 5.5 models did not, while claude-sonnet-5-5 thought heavily on a long rewrite. Thinking is billed as output. Effort only meaningfully modulates depth when thinking is on. Note: claude-opus-5-5, claude-fable-5-1 and Fable 5 reject every "off" value, and with thinking on max_tokens covers thinking + answer, so a deep-thinking profile needs headroom for both. Raise it with the max_tokens key in llm_config.yaml or the per-request max_tokens argument; a response that hits the cap raises :class:~majordomo_llm.exceptions.ResponseTruncatedError rather than returning silently truncated content.

None
cached_input_cost float | None

Cost per million cache-read tokens in USD (cache_read_input_tokens), billed on top of uncached input.

None
cache_write_cost float | None

Cost per million cache-creation tokens in USD (cache_creation_input_tokens), billed on top of uncached input.

None
use_prompt_caching bool

When True (default), the system prompt is sent with an ephemeral cache_control breakpoint so Anthropic caches it. Set False to disable prompt caching (e.g. for short, non-reused system prompts where the cache-write premium is wasted).

True
supports_forced_tool_choice bool

Whether the model accepts a forced tool_choice (type: "tool" / "any"). Opus 5.5, Sonnet 5.5 and Fable 5.1 reject it with a 400. When False, the web-search structured path finishes with tool_choice: auto plus an explicit instruction instead of forcing the schema tool, and supports_structured_outputs must be True because the forced-tool fallback is unavailable.

True
api_key str | None

Optional API key. Defaults to ANTHROPIC_API_KEY env var.

None
api_key_alias str | None

Optional human-readable name for the API key.

None
base_url str | None

Optional custom base URL for routing through a proxy.

None
default_headers dict[str, str] | None

Optional headers sent with every request.

None
max_tokens int | None

Default output cap for this model. None uses the library defaults (16000 non-streaming, 64000 streaming).

None

Raises:

Type Description
ConfigurationError

If no API key is provided and env var is not set.

ValueError

If reasoning_effort or thinking is invalid, or if the model supports neither native structured outputs nor a forced tool_choice.

Source code in majordomo_llm/providers/anthropic.py
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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def __init__(
    self,
    model: str,
    input_cost: float,
    output_cost: float,
    supports_temperature_top_p: bool = True,
    use_web_search: bool = False,
    supports_structured_outputs: bool = False,
    supports_image_input: bool = False,
    reasoning_effort: str | None = None,
    thinking: str | None = None,
    *,
    cached_input_cost: float | None = None,
    cache_write_cost: float | None = None,
    use_prompt_caching: bool = True,
    supports_forced_tool_choice: bool = True,
    api_key: str | None = None,
    api_key_alias: str | None = None,
    base_url: str | None = None,
    default_headers: dict[str, str] | None = None,
    max_tokens: int | None = None,
) -> None:
    """Initialize the Anthropic provider.

    Args:
        model: The Claude model identifier (e.g., "claude-sonnet-5").
        input_cost: Cost per million input tokens in USD.
        output_cost: Cost per million output tokens in USD.
        supports_temperature_top_p: Whether temperature/top_p are supported.
        use_web_search: Enable web search. The factory only allows it on
            models with ``supports_web_search: true`` in ``llm_config.yaml``.
        supports_structured_outputs: Whether the model supports native
            structured outputs (constrained decoding via
            ``output_config.format``). When False, structured JSON requests
            fall back to forced tool calling. Defaults to False.
        supports_image_input: Whether this model accepts image inputs.
        reasoning_effort: Optional ``output_config.effort`` level applied to
            every request — one of ``low``, ``medium``, ``high``, ``xhigh``,
            ``max``. Controls thinking depth and overall token spend on the
            4.7+/5 generation. ``None`` (default) sends no effort, so the
            API default (``high``) applies. Register the same SKU under
            multiple YAML keys (via the ``model`` override) to expose
            distinct effort profiles.
        thinking: Optional ``thinking.type`` mode applied to every request —
            ``adaptive`` (Claude decides how much to think; the on-mode for
            the 4.6+/5 generation), ``disabled``, or ``between_tools``
            (how ``claude-sonnet-5-5`` spells "off"). Sent exactly as given;
            :func:`~majordomo_llm.factory.get_llm_instance` is what turns a
            model-neutral ``disabled`` into the model's own spelling.
            ``None`` (default) omits the field, which leaves the model's own
            default in force. That varies by model and by prompt: on a
            one-word prompt ``claude-opus-5`` and Fable 5 thought and the
            5.5 models did not, while ``claude-sonnet-5-5`` thought heavily
            on a long rewrite. Thinking is billed as output.
            Effort only meaningfully modulates depth when thinking is on.
            Note: ``claude-opus-5-5``, ``claude-fable-5-1`` and Fable 5
            reject every "off" value, and with thinking on ``max_tokens``
            covers thinking + answer, so a deep-thinking profile needs
            headroom for both. Raise it with the
            ``max_tokens`` key in ``llm_config.yaml`` or the per-request
            ``max_tokens`` argument; a response that hits the cap raises
            :class:`~majordomo_llm.exceptions.ResponseTruncatedError` rather
            than returning silently truncated content.
        cached_input_cost: Cost per million cache-read tokens in USD
            (``cache_read_input_tokens``), billed on top of uncached input.
        cache_write_cost: Cost per million cache-creation tokens in USD
            (``cache_creation_input_tokens``), billed on top of uncached input.
        use_prompt_caching: When ``True`` (default), the system prompt is sent
            with an ephemeral ``cache_control`` breakpoint so Anthropic caches
            it. Set ``False`` to disable prompt caching (e.g. for short,
            non-reused system prompts where the cache-write premium is wasted).
        supports_forced_tool_choice: Whether the model accepts a forced
            ``tool_choice`` (``type: "tool"`` / ``"any"``). Opus 5.5,
            Sonnet 5.5 and Fable 5.1 reject it with a 400. When ``False``,
            the web-search structured path finishes with ``tool_choice:
            auto`` plus an explicit instruction instead of forcing the
            schema tool, and ``supports_structured_outputs`` must be
            ``True`` because the forced-tool fallback is unavailable.
        api_key: Optional API key. Defaults to ``ANTHROPIC_API_KEY`` env var.
        api_key_alias: Optional human-readable name for the API key.
        base_url: Optional custom base URL for routing through a proxy.
        default_headers: Optional headers sent with every request.
        max_tokens: Default output cap for this model. ``None`` uses the
            library defaults (16000 non-streaming, 64000 streaming).

    Raises:
        ConfigurationError: If no API key is provided and env var is not set.
        ValueError: If ``reasoning_effort`` or ``thinking`` is invalid, or if
            the model supports neither native structured outputs nor a
            forced ``tool_choice``.
    """
    if reasoning_effort is not None and reasoning_effort not in _EFFORT_LEVELS:
        valid = ", ".join(sorted(_EFFORT_LEVELS))
        raise ValueError(
            f"Invalid Anthropic reasoning_effort '{reasoning_effort}'. Valid: {valid}"
        )
    if thinking is not None and thinking not in _THINKING_MODES:
        valid = ", ".join(sorted(_THINKING_MODES))
        raise ValueError(f"Invalid Anthropic thinking mode '{thinking}'. Valid: {valid}")
    if not supports_forced_tool_choice and not supports_structured_outputs:
        raise ValueError(
            f"Anthropic model '{model}' rejects a forced tool_choice, so it must set "
            f"supports_structured_outputs=True; there is no other structured-output path."
        )
    resolved_api_key = resolve_api_key(api_key, "ANTHROPIC_API_KEY", "Anthropic")
    self.supports_structured_outputs = supports_structured_outputs
    self.supports_forced_tool_choice = supports_forced_tool_choice
    self.reasoning_effort = reasoning_effort
    self.thinking = thinking
    super().__init__(
        provider="anthropic",
        model=model,
        input_cost=input_cost,
        output_cost=output_cost,
        cached_input_cost=cached_input_cost,
        cache_write_cost=cache_write_cost,
        use_prompt_caching=use_prompt_caching,
        supports_temperature_top_p=supports_temperature_top_p,
        use_web_search=use_web_search,
        supports_image_input=supports_image_input,
        api_key=resolved_api_key,
        api_key_alias=api_key_alias,
        base_url=base_url,
        default_headers=default_headers,
        max_tokens=max_tokens,
    )
    self.client = anthropic.AsyncAnthropic(
        api_key=resolved_api_key,
        base_url=self.base_url,
        default_headers=self.default_headers,
    )

Bases: LLM

Google Gemini LLM provider.

Implements the LLM interface for Google's Gemini models, including support for structured outputs via response schemas.

The API key is read from the GEMINI_API_KEY environment variable.

Attributes:

Name Type Description
client

The Google GenAI client instance.

Example

llm = Gemini( ... model="gemini-3.8-flash", ... input_cost=0.30, ... output_cost=2.50, ... ) response = await llm.get_response("Hello, Gemini!")

Source code in majordomo_llm/providers/gemini.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 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
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
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
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
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
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
class Gemini(LLM):
    """Google Gemini LLM provider.

    Implements the LLM interface for Google's Gemini models, including
    support for structured outputs via response schemas.

    The API key is read from the ``GEMINI_API_KEY`` environment variable.

    Attributes:
        client: The Google GenAI client instance.

    Example:
        >>> llm = Gemini(
        ...     model="gemini-3.8-flash",
        ...     input_cost=0.30,
        ...     output_cost=2.50,
        ... )
        >>> response = await llm.get_response("Hello, Gemini!")
    """

    def __init__(
        self,
        model: str,
        input_cost: float,
        output_cost: float,
        *,
        supports_temperature_top_p: bool = True,
        use_web_search: bool = False,
        supports_image_input: bool = False,
        cached_input_cost: float | None = None,
        cache_write_cost: float | None = None,
        api_key: str | None = None,
        api_key_alias: str | None = None,
        base_url: str | None = None,
        default_headers: dict[str, str] | None = None,
    ) -> None:
        """Initialize the Gemini provider.

        Args:
            model: The Gemini model identifier (e.g., "gemini-3.8-flash").
            input_cost: Cost per million input tokens in USD.
            output_cost: Cost per million output tokens in USD.
            supports_temperature_top_p: Whether the model supports temperature/top_p.
            use_web_search: Enable the Google Search grounding tool.
            supports_image_input: Whether this model accepts image inputs.
            cached_input_cost: Cost per million cached-content (cache-read) tokens
                in USD. Gemini reports cached content as a subset of prompt
                tokens, so this re-prices them below ``input_cost``.
            cache_write_cost: Unused by Gemini (implicit caching has no per-token
                write fee); accepted for a uniform factory signature.
            api_key: Optional API key. Defaults to ``GEMINI_API_KEY`` env var.
            api_key_alias: Optional human-readable name for the API key.
            base_url: Optional custom base URL for routing through a proxy.
            default_headers: Optional headers sent with every request.

        Raises:
            ConfigurationError: If no API key is provided and env var is not set.
        """
        resolved_api_key = resolve_api_key(api_key, "GEMINI_API_KEY", "Gemini")
        super().__init__(
            provider="gemini",
            model=model,
            input_cost=input_cost,
            output_cost=output_cost,
            cached_input_cost=cached_input_cost,
            cache_write_cost=cache_write_cost,
            supports_temperature_top_p=True,
            use_web_search=use_web_search,
            supports_image_input=supports_image_input,
            api_key=resolved_api_key,
            api_key_alias=api_key_alias,
            base_url=base_url,
            default_headers=default_headers,
        )
        http_options = None
        if self.base_url or self.default_headers:
            http_options = types.HttpOptions(
                base_url=self.base_url,
                headers=self.default_headers,
            )
        self.client = genai.Client(api_key=resolved_api_key, http_options=http_options)

    # Gemini bills grounded queries at $35 per 1,000 requests.
    _GROUNDED_QUERY_COST = 0.035

    def _apply_web_search(self, config_kwargs: dict[str, Any]) -> None:
        """Attach the Google Search tool to a request config when enabled."""
        if not self.use_web_search:
            return
        config_kwargs["tools"] = [types.Tool(google_search=types.GoogleSearch())]

    def _supports_search_with_structured_output(self) -> bool:
        """Whether this model can combine a grounding tool with a response schema.

        Grounded structured outputs are a Gemini 3 series preview feature; 2.5
        and earlier reject a request that sets both a grounding tool and a
        response schema.
        """
        return (
            self.model.startswith("gemini-3.")
            or self.model.startswith("gemini-3-")
            or self.model == "gemini-3"
        )

    def _compute_web_search_cost(self, response: Any) -> float:
        """Return the per-call grounded-query fee charged by Gemini.

        Counts response candidates that carry ``grounding_metadata`` — the
        only signal the API surfaces when a grounded query was actually
        performed.
        """
        candidates = getattr(response, "candidates", None) or []
        grounded = sum(1 for c in candidates if getattr(c, "grounding_metadata", None) is not None)
        return grounded * self._GROUNDED_QUERY_COST

    def _compute_structured_web_search_cost(self, response: Any) -> float:
        """Return the grounded-query fee for a structured response.

        A response produced with both a grounding tool and a response schema
        carries no ``grounding_metadata`` even when the search ran (observed on
        gemini-3.6-flash, gemini-3.8-flash and gemini-3.1-pro-preview,
        2026-10-11), so nothing in it says whether or how often the model
        searched. One query is billed as a floor whenever web search is
        enabled. This is an estimate: it over-reports by one query if the model
        chose not to search and under-reports if it issued several.
        """
        cost = self._compute_web_search_cost(response)
        if not self.use_web_search:
            return cost
        return max(cost, self._GROUNDED_QUERY_COST)

    @retry_provider_call
    async def _get_response_impl(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        """Get a plain text response from Gemini."""
        return await self._get_response(
            user_prompt, system_prompt, temperature, top_p, extra_headers=extra_headers
        )

    @retry_provider_call
    async def _get_response_with_images_impl(
        self,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        return await self._get_response(
            user_prompt,
            system_prompt,
            temperature,
            top_p,
            extra_headers=extra_headers,
            images=images,
        )

    async def _get_response(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        images: tuple[ImageInput, ...] = (),
    ) -> LLMResponse:
        """Internal method to get a response from Gemini."""
        start_time = time.time()
        config_kwargs: dict[str, Any] = {
            "system_instruction": system_prompt,
            **self._sampling_params(temperature, top_p),
        }
        if extra_headers:
            config_kwargs["http_options"] = types.HttpOptions(headers=extra_headers)
        self._apply_web_search(config_kwargs)
        try:
            response = await self.client.aio.models.generate_content(
                model=self.model,
                config=types.GenerateContentConfig(**config_kwargs),
                contents=_gemini_contents(user_prompt, images),
            )
        except genai_errors.APIError as e:
            raise ProviderError(
                f"Gemini API error: {e}",
                provider="gemini",
                original_error=e,
            ) from e
        execution_time = time.time() - start_time

        input_tokens, output_tokens, cached_tokens = _gemini_token_counts(response)
        input_cost, output_cost, total_cost = self._calculate_costs(
            input_tokens, output_tokens, cached_tokens
        )
        tool_use_cost = self._compute_web_search_cost(response)
        total_cost += tool_use_cost

        return LLMResponse(
            content=response.text or "",
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            cached_tokens=cached_tokens,
            input_cost=input_cost,
            output_cost=output_cost,
            total_cost=total_cost,
            response_time=execution_time,
            tool_use_cost=tool_use_cost,
            deprecation_warning=self.deprecation_warning,
        )

    async def _get_response_stream_impl(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMStreamResponse:
        """Get a streaming text response from Gemini."""
        state = _StreamState()
        config_kwargs: dict[str, Any] = {
            "system_instruction": system_prompt,
            **self._sampling_params(temperature, top_p),
        }
        if extra_headers:
            config_kwargs["http_options"] = types.HttpOptions(headers=extra_headers)
        self._apply_web_search(config_kwargs)

        try:
            response = await self.client.aio.models.generate_content_stream(
                model=self.model,
                config=types.GenerateContentConfig(**config_kwargs),
                contents=user_prompt,
            )
        except genai_errors.APIError as e:
            raise ProviderError(
                f"Gemini API error: {e}",
                provider="gemini",
                original_error=e,
            ) from e

        async def generator() -> AsyncIterator[str]:
            try:
                async for chunk in response:
                    if chunk.text:
                        yield chunk.text
                    if chunk.usage_metadata:
                        counts = _gemini_token_counts(chunk)
                        state.input_tokens, state.output_tokens, state.cached_tokens = counts
            except genai_errors.APIError as e:
                raise ProviderError(
                    f"Gemini API error: {e}",
                    provider="gemini",
                    original_error=e,
                ) from e

        return LLMStreamResponse(stream=generator(), state=state, llm=self)

    async def _get_response_stream_with_images_impl(
        self,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMStreamResponse:
        state = _StreamState()
        config_kwargs: dict[str, Any] = {
            "system_instruction": system_prompt,
            **self._sampling_params(temperature, top_p),
        }
        if extra_headers:
            config_kwargs["http_options"] = types.HttpOptions(headers=extra_headers)
        self._apply_web_search(config_kwargs)
        try:
            response = await self.client.aio.models.generate_content_stream(
                model=self.model,
                config=types.GenerateContentConfig(**config_kwargs),
                contents=_gemini_contents(user_prompt, images),
            )
        except genai_errors.APIError as e:
            raise ProviderError(
                f"Gemini API error: {e}", provider="gemini", original_error=e
            ) from e

        async def generator() -> AsyncIterator[str]:
            try:
                async for chunk in response:
                    if chunk.text:
                        yield chunk.text
                    if chunk.usage_metadata:
                        counts = _gemini_token_counts(chunk)
                        state.input_tokens, state.output_tokens, state.cached_tokens = counts
            except genai_errors.APIError as e:
                raise ProviderError(
                    f"Gemini API error: {e}", provider="gemini", original_error=e
                ) from e

        return LLMStreamResponse(stream=generator(), state=state, llm=self)

    async def _get_json_schema_response(
        self,
        user_prompt: str,
        response_schema: dict[str, Any],
        system_prompt: str | None = None,
        schema_name: str = "Response",
        schema_description: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        """Gemini-specific implementation using response schema for structured outputs."""
        return await self._get_json_schema_response_common(
            user_prompt=user_prompt,
            images=(),
            response_schema=response_schema,
            system_prompt=system_prompt,
            temperature=temperature,
            top_p=top_p,
            extra_headers=extra_headers,
        )

    async def _get_json_schema_response_with_images(
        self,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        response_schema: dict[str, Any],
        system_prompt: str | None = None,
        schema_name: str = "Response",
        schema_description: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        return await self._get_json_schema_response_common(
            user_prompt=user_prompt,
            images=images,
            response_schema=response_schema,
            system_prompt=system_prompt,
            temperature=temperature,
            top_p=top_p,
            extra_headers=extra_headers,
        )

    async def _get_json_schema_response_common(
        self,
        *,
        user_prompt: str,
        images: tuple[ImageInput, ...],
        response_schema: dict[str, Any],
        system_prompt: str | None,
        temperature: float | None,
        top_p: float | None,
        extra_headers: dict[str, str] | None,
    ) -> LLMResponse:
        if self.use_web_search and not self._supports_search_with_structured_output():
            raise ConfigurationError(
                f"Gemini model '{self.model}' does not support combining grounded "
                "web search with response_schema in the same request. Only Gemini 3 "
                "series models support grounded structured outputs. Use a separate "
                "Gemini instance with use_web_search=False for structured calls."
            )
        config_kwargs: dict[str, Any] = {
            "system_instruction": system_prompt,
            **self._sampling_params(temperature, top_p),
            "response_schema": _gemini_schema(response_schema),
            "response_mime_type": "application/json",
        }
        if extra_headers:
            config_kwargs["http_options"] = types.HttpOptions(headers=extra_headers)
        self._apply_web_search(config_kwargs)

        start_time = time.time()
        try:
            response = await self.client.aio.models.generate_content(
                model=self.model,
                config=types.GenerateContentConfig(**config_kwargs),
                contents=_gemini_contents(user_prompt, images),
            )
        except genai_errors.APIError as e:
            raise ProviderError(
                f"Gemini API error: {e}",
                provider="gemini",
                original_error=e,
            ) from e
        execution_time = time.time() - start_time

        input_tokens, output_tokens, cached_tokens = _gemini_token_counts(response)
        input_cost, output_cost, total_cost = self._calculate_costs(
            input_tokens, output_tokens, cached_tokens
        )
        tool_use_cost = self._compute_structured_web_search_cost(response)
        total_cost += tool_use_cost

        result = LLMResponse(
            content=response.text or "",
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            cached_tokens=cached_tokens,
            input_cost=input_cost,
            output_cost=output_cost,
            total_cost=total_cost,
            response_time=execution_time,
            tool_use_cost=tool_use_cost,
        )
        # Priced before parsing, so a parse error carries what the call cost.
        with self._usage_on_parse_error(result):
            result.content = canonicalize_json_schema_output(result.content, response_schema)
        return result

__init__

__init__(model, input_cost, output_cost, *, supports_temperature_top_p=True, use_web_search=False, supports_image_input=False, cached_input_cost=None, cache_write_cost=None, api_key=None, api_key_alias=None, base_url=None, default_headers=None)

Initialize the Gemini provider.

Parameters:

Name Type Description Default
model str

The Gemini model identifier (e.g., "gemini-3.8-flash").

required
input_cost float

Cost per million input tokens in USD.

required
output_cost float

Cost per million output tokens in USD.

required
supports_temperature_top_p bool

Whether the model supports temperature/top_p.

True
use_web_search bool

Enable the Google Search grounding tool.

False
supports_image_input bool

Whether this model accepts image inputs.

False
cached_input_cost float | None

Cost per million cached-content (cache-read) tokens in USD. Gemini reports cached content as a subset of prompt tokens, so this re-prices them below input_cost.

None
cache_write_cost float | None

Unused by Gemini (implicit caching has no per-token write fee); accepted for a uniform factory signature.

None
api_key str | None

Optional API key. Defaults to GEMINI_API_KEY env var.

None
api_key_alias str | None

Optional human-readable name for the API key.

None
base_url str | None

Optional custom base URL for routing through a proxy.

None
default_headers dict[str, str] | None

Optional headers sent with every request.

None

Raises:

Type Description
ConfigurationError

If no API key is provided and env var is not set.

Source code in majordomo_llm/providers/gemini.py
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def __init__(
    self,
    model: str,
    input_cost: float,
    output_cost: float,
    *,
    supports_temperature_top_p: bool = True,
    use_web_search: bool = False,
    supports_image_input: bool = False,
    cached_input_cost: float | None = None,
    cache_write_cost: float | None = None,
    api_key: str | None = None,
    api_key_alias: str | None = None,
    base_url: str | None = None,
    default_headers: dict[str, str] | None = None,
) -> None:
    """Initialize the Gemini provider.

    Args:
        model: The Gemini model identifier (e.g., "gemini-3.8-flash").
        input_cost: Cost per million input tokens in USD.
        output_cost: Cost per million output tokens in USD.
        supports_temperature_top_p: Whether the model supports temperature/top_p.
        use_web_search: Enable the Google Search grounding tool.
        supports_image_input: Whether this model accepts image inputs.
        cached_input_cost: Cost per million cached-content (cache-read) tokens
            in USD. Gemini reports cached content as a subset of prompt
            tokens, so this re-prices them below ``input_cost``.
        cache_write_cost: Unused by Gemini (implicit caching has no per-token
            write fee); accepted for a uniform factory signature.
        api_key: Optional API key. Defaults to ``GEMINI_API_KEY`` env var.
        api_key_alias: Optional human-readable name for the API key.
        base_url: Optional custom base URL for routing through a proxy.
        default_headers: Optional headers sent with every request.

    Raises:
        ConfigurationError: If no API key is provided and env var is not set.
    """
    resolved_api_key = resolve_api_key(api_key, "GEMINI_API_KEY", "Gemini")
    super().__init__(
        provider="gemini",
        model=model,
        input_cost=input_cost,
        output_cost=output_cost,
        cached_input_cost=cached_input_cost,
        cache_write_cost=cache_write_cost,
        supports_temperature_top_p=True,
        use_web_search=use_web_search,
        supports_image_input=supports_image_input,
        api_key=resolved_api_key,
        api_key_alias=api_key_alias,
        base_url=base_url,
        default_headers=default_headers,
    )
    http_options = None
    if self.base_url or self.default_headers:
        http_options = types.HttpOptions(
            base_url=self.base_url,
            headers=self.default_headers,
        )
    self.client = genai.Client(api_key=resolved_api_key, http_options=http_options)

Bases: LLM

Cohere LLM provider.

Implements the LLM interface for Cohere's models using the V2 API. Supports Command A, Command R+, Command R, and Command R7B models.

The API key is read from the CO_API_KEY environment variable.

Attributes:

Name Type Description
client

The async Cohere client instance.

Example

llm = Cohere( ... model="command-a-03-2025", ... input_cost=2.50, ... output_cost=10.00, ... ) response = await llm.get_response("Hello, Cohere!")

Source code in majordomo_llm/providers/cohere.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 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
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
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
class Cohere(LLM):
    """Cohere LLM provider.

    Implements the LLM interface for Cohere's models using the V2 API.
    Supports Command A, Command R+, Command R, and Command R7B models.

    The API key is read from the ``CO_API_KEY`` environment variable.

    Attributes:
        client: The async Cohere client instance.

    Example:
        >>> llm = Cohere(
        ...     model="command-a-03-2025",
        ...     input_cost=2.50,
        ...     output_cost=10.00,
        ... )
        >>> response = await llm.get_response("Hello, Cohere!")
    """

    def __init__(
        self,
        model: str,
        input_cost: float,
        output_cost: float,
        supports_temperature_top_p: bool = True,
        *,
        cached_input_cost: float | None = None,
        cache_write_cost: float | None = None,
        api_key: str | None = None,
        api_key_alias: str | None = None,
        base_url: str | None = None,
        default_headers: dict[str, str] | None = None,
    ) -> None:
        """Initialize the Cohere provider.

        Args:
            model: The Cohere model identifier (e.g., "command-a-03-2025").
            input_cost: Cost per million input tokens in USD.
            output_cost: Cost per million output tokens in USD.
            supports_temperature_top_p: Whether temperature/top_p are supported.
            cached_input_cost: Unused by Cohere (no prompt caching); accepted for
                a uniform factory signature.
            cache_write_cost: Unused by Cohere; accepted for a uniform factory
                signature.
            api_key: Optional API key. Defaults to ``CO_API_KEY`` env var.
            api_key_alias: Optional human-readable name for the API key.
            base_url: Optional custom base URL for routing through a proxy.
            default_headers: Optional headers sent with every request.

        Raises:
            ConfigurationError: If no API key is provided and env var is not set.
        """
        resolved_api_key = resolve_api_key(api_key, "CO_API_KEY", "Cohere")
        super().__init__(
            provider="cohere",
            model=model,
            input_cost=input_cost,
            output_cost=output_cost,
            cached_input_cost=cached_input_cost,
            cache_write_cost=cache_write_cost,
            supports_temperature_top_p=supports_temperature_top_p,
            api_key=resolved_api_key,
            api_key_alias=api_key_alias,
            base_url=base_url,
            default_headers=default_headers,
        )
        self.client = cohere.AsyncClientV2(
            api_key=resolved_api_key,
            base_url=self.base_url,
        )

    def _cohere_request_options(
        self, extra_headers: dict[str, str] | None
    ) -> RequestOptions | None:
        """Build request_options with merged default + extra headers."""
        merged = dict(self.default_headers or {})
        if extra_headers:
            merged.update(extra_headers)
        if not merged:
            return None
        return RequestOptions(additional_headers=merged)

    def _cohere_sampling(
        self, temperature: float | None, top_p: float | None
    ) -> dict[str, Any]:
        """Translate the shared sampling params to Cohere's names.

        Cohere calls nucleus sampling ``p``, not ``top_p``.
        """
        params = self._sampling_params(temperature, top_p)
        if "top_p" in params:
            params["p"] = params.pop("top_p")
        return params

    @retry_provider_call
    async def _get_response_impl(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        """Get a plain text response from Cohere."""
        return await self._get_response(
            user_prompt, system_prompt, temperature, top_p, extra_headers=extra_headers
        )

    async def _get_response(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
    ) -> LLMResponse:
        """Internal method to get a response from Cohere."""
        messages: list[Any] = []
        if system_prompt:
            messages.append(SystemChatMessageV2(content=system_prompt))
        messages.append(UserChatMessageV2(content=user_prompt))

        request_options = self._cohere_request_options(extra_headers)

        start_time = time.time()
        try:
            response = await self.client.chat(
                model=self.model,
                messages=messages,
                request_options=request_options,
                **self._cohere_sampling(temperature, top_p),
            )
        except cohere.core.api_error.ApiError as e:
            raise ProviderError(
                f"Cohere API error: {e}",
                provider="cohere",
                original_error=e,
            ) from e

        execution_time = time.time() - start_time
        input_tokens, output_tokens = _cohere_token_counts(response)
        cached_tokens = 0
        input_cost, output_cost, total_cost = self._calculate_costs(input_tokens, output_tokens)

        return LLMResponse(
            content=_cohere_text_content(response),
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            cached_tokens=cached_tokens,
            input_cost=input_cost,
            output_cost=output_cost,
            total_cost=total_cost,
            response_time=execution_time,
            deprecation_warning=self.deprecation_warning,
        )

    async def _get_response_stream_impl(
        self,
        user_prompt: str,
        system_prompt: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMStreamResponse:
        """Get a streaming text response from Cohere."""
        messages: list[Any] = []
        if system_prompt:
            messages.append(SystemChatMessageV2(content=system_prompt))
        messages.append(UserChatMessageV2(content=user_prompt))

        state = _StreamState()
        request_options = self._cohere_request_options(extra_headers)

        try:
            response = self.client.chat_stream(
                model=self.model,
                messages=messages,
                request_options=request_options,
                **self._cohere_sampling(temperature, top_p),
            )
        except cohere.core.api_error.ApiError as e:
            raise ProviderError(
                f"Cohere API error: {e}",
                provider="cohere",
                original_error=e,
            ) from e

        async def generator() -> AsyncIterator[str]:
            try:
                async for event in response:
                    event_any: Any = event
                    if event_any.type == "content-delta":
                        yield event_any.delta.message.content.text or ""
                    elif event_any.type == "message-end":
                        state.input_tokens, state.output_tokens = _cohere_usage_tokens(
                            event_any.delta.usage
                        )
            except cohere.core.api_error.ApiError as e:
                raise ProviderError(
                    f"Cohere API error: {e}",
                    provider="cohere",
                    original_error=e,
                ) from e

        return LLMStreamResponse(stream=generator(), state=state, llm=self)

    async def _get_json_schema_response(
        self,
        user_prompt: str,
        response_schema: dict[str, Any],
        system_prompt: str | None = None,
        schema_name: str = "Response",
        schema_description: str | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        extra_headers: dict[str, str] | None = None,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        """Cohere-specific implementation using native JSON schema response format."""
        schema = _strip_cohere_unsupported_constraints(inline_schema_refs(response_schema))
        messages: list[Any] = []
        if system_prompt is not None:
            messages.append(SystemChatMessageV2(content=system_prompt))
        messages.append(UserChatMessageV2(content=user_prompt))

        request_options = self._cohere_request_options(extra_headers)

        start_time = time.time()
        try:
            response = await self.client.chat(
                model=self.model,
                messages=messages,
                response_format=JsonObjectResponseFormatV2(json_schema=schema),
                request_options=request_options,
                **self._cohere_sampling(temperature, top_p),
            )
        except cohere.core.api_error.ApiError as e:
            raise ProviderError(
                f"Cohere API error: {e}",
                provider="cohere",
                original_error=e,
            ) from e

        execution_time = time.time() - start_time

        input_tokens, output_tokens = _cohere_token_counts(response)
        cached_tokens = 0
        input_cost, output_cost, total_cost = self._calculate_costs(input_tokens, output_tokens)

        result = LLMResponse(
            content=_cohere_text_content(response),
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            cached_tokens=cached_tokens,
            input_cost=input_cost,
            output_cost=output_cost,
            total_cost=total_cost,
            response_time=execution_time,
        )
        # Priced before parsing, so a parse error carries what the call cost.
        with self._usage_on_parse_error(result):
            result.content = canonicalize_json_schema_output(result.content, response_schema)
        return result

__init__

__init__(model, input_cost, output_cost, supports_temperature_top_p=True, *, cached_input_cost=None, cache_write_cost=None, api_key=None, api_key_alias=None, base_url=None, default_headers=None)

Initialize the Cohere provider.

Parameters:

Name Type Description Default
model str

The Cohere model identifier (e.g., "command-a-03-2025").

required
input_cost float

Cost per million input tokens in USD.

required
output_cost float

Cost per million output tokens in USD.

required
supports_temperature_top_p bool

Whether temperature/top_p are supported.

True
cached_input_cost float | None

Unused by Cohere (no prompt caching); accepted for a uniform factory signature.

None
cache_write_cost float | None

Unused by Cohere; accepted for a uniform factory signature.

None
api_key str | None

Optional API key. Defaults to CO_API_KEY env var.

None
api_key_alias str | None

Optional human-readable name for the API key.

None
base_url str | None

Optional custom base URL for routing through a proxy.

None
default_headers dict[str, str] | None

Optional headers sent with every request.

None

Raises:

Type Description
ConfigurationError

If no API key is provided and env var is not set.

Source code in majordomo_llm/providers/cohere.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def __init__(
    self,
    model: str,
    input_cost: float,
    output_cost: float,
    supports_temperature_top_p: bool = True,
    *,
    cached_input_cost: float | None = None,
    cache_write_cost: float | None = None,
    api_key: str | None = None,
    api_key_alias: str | None = None,
    base_url: str | None = None,
    default_headers: dict[str, str] | None = None,
) -> None:
    """Initialize the Cohere provider.

    Args:
        model: The Cohere model identifier (e.g., "command-a-03-2025").
        input_cost: Cost per million input tokens in USD.
        output_cost: Cost per million output tokens in USD.
        supports_temperature_top_p: Whether temperature/top_p are supported.
        cached_input_cost: Unused by Cohere (no prompt caching); accepted for
            a uniform factory signature.
        cache_write_cost: Unused by Cohere; accepted for a uniform factory
            signature.
        api_key: Optional API key. Defaults to ``CO_API_KEY`` env var.
        api_key_alias: Optional human-readable name for the API key.
        base_url: Optional custom base URL for routing through a proxy.
        default_headers: Optional headers sent with every request.

    Raises:
        ConfigurationError: If no API key is provided and env var is not set.
    """
    resolved_api_key = resolve_api_key(api_key, "CO_API_KEY", "Cohere")
    super().__init__(
        provider="cohere",
        model=model,
        input_cost=input_cost,
        output_cost=output_cost,
        cached_input_cost=cached_input_cost,
        cache_write_cost=cache_write_cost,
        supports_temperature_top_p=supports_temperature_top_p,
        api_key=resolved_api_key,
        api_key_alias=api_key_alias,
        base_url=base_url,
        default_headers=default_headers,
    )
    self.client = cohere.AsyncClientV2(
        api_key=resolved_api_key,
        base_url=self.base_url,
    )