1// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
3package anthropic
4
5import (
6 "context"
7 "encoding/json"
8 "fmt"
9 "net/http"
10 "time"
11
12 "github.com/anthropics/anthropic-sdk-go/internal/apijson"
13 "github.com/anthropics/anthropic-sdk-go/internal/paramutil"
14 "github.com/anthropics/anthropic-sdk-go/internal/requestconfig"
15 "github.com/anthropics/anthropic-sdk-go/option"
16 "github.com/anthropics/anthropic-sdk-go/packages/param"
17 "github.com/anthropics/anthropic-sdk-go/packages/respjson"
18 "github.com/anthropics/anthropic-sdk-go/packages/ssestream"
19 "github.com/anthropics/anthropic-sdk-go/shared/constant"
20)
21
22// MessageService contains methods and other services that help with interacting
23// with the anthropic API.
24//
25// Note, unlike clients, this service does not read variables from the environment
26// automatically. You should not instantiate this service directly, and instead use
27// the [NewMessageService] method instead.
28type MessageService struct {
29 Options []option.RequestOption
30 Batches MessageBatchService
31}
32
33// NewMessageService generates a new service that applies the given options to each
34// request. These options are applied after the parent client's options (if there
35// is one), and before any request-specific options.
36func NewMessageService(opts ...option.RequestOption) (r MessageService) {
37 r = MessageService{}
38 r.Options = opts
39 r.Batches = NewMessageBatchService(opts...)
40 return
41}
42
43// Send a structured list of input messages with text and/or image content, and the
44// model will generate the next message in the conversation.
45//
46// The Messages API can be used for either single queries or stateless multi-turn
47// conversations.
48//
49// Learn more about the Messages API in our [user guide](/en/docs/initial-setup)
50//
51// Note: If you choose to set a timeout for this request, we recommend 10 minutes.
52func (r *MessageService) New(ctx context.Context, body MessageNewParams, opts ...option.RequestOption) (res *Message, err error) {
53 opts = append(r.Options[:], opts...)
54
55 // For non-streaming requests, calculate the appropriate timeout based on maxTokens
56 // and check against model-specific limits
57 timeout, timeoutErr := CalculateNonStreamingTimeout(int(body.MaxTokens), body.Model, opts)
58 if timeoutErr != nil {
59 return nil, timeoutErr
60 }
61 opts = append(opts, option.WithRequestTimeout(timeout))
62
63 path := "v1/messages"
64 err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
65 return
66}
67
68// Send a structured list of input messages with text and/or image content, and the
69// model will generate the next message in the conversation.
70//
71// The Messages API can be used for either single queries or stateless multi-turn
72// conversations.
73//
74// Learn more about the Messages API in our [user guide](/en/docs/initial-setup)
75//
76// Note: If you choose to set a timeout for this request, we recommend 10 minutes.
77func (r *MessageService) NewStreaming(ctx context.Context, body MessageNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[MessageStreamEventUnion]) {
78 var (
79 raw *http.Response
80 err error
81 )
82 opts = append(r.Options[:], opts...)
83 opts = append([]option.RequestOption{option.WithJSONSet("stream", true)}, opts...)
84 path := "v1/messages"
85 err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &raw, opts...)
86 return ssestream.NewStream[MessageStreamEventUnion](ssestream.NewDecoder(raw), err)
87}
88
89// Count the number of tokens in a Message.
90//
91// The Token Count API can be used to count the number of tokens in a Message,
92// including tools, images, and documents, without creating it.
93//
94// Learn more about token counting in our
95// [user guide](/en/docs/build-with-claude/token-counting)
96func (r *MessageService) CountTokens(ctx context.Context, body MessageCountTokensParams, opts ...option.RequestOption) (res *MessageTokensCount, err error) {
97 opts = append(r.Options[:], opts...)
98 path := "v1/messages/count_tokens"
99 err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
100 return
101}
102
103// The properties Data, MediaType, Type are required.
104type Base64ImageSourceParam struct {
105 Data string `json:"data,required" format:"byte"`
106 // Any of "image/jpeg", "image/png", "image/gif", "image/webp".
107 MediaType Base64ImageSourceMediaType `json:"media_type,omitzero,required"`
108 // This field can be elided, and will marshal its zero value as "base64".
109 Type constant.Base64 `json:"type,required"`
110 paramObj
111}
112
113func (r Base64ImageSourceParam) MarshalJSON() (data []byte, err error) {
114 type shadow Base64ImageSourceParam
115 return param.MarshalObject(r, (*shadow)(&r))
116}
117func (r *Base64ImageSourceParam) UnmarshalJSON(data []byte) error {
118 return apijson.UnmarshalRoot(data, r)
119}
120
121type Base64ImageSourceMediaType string
122
123const (
124 Base64ImageSourceMediaTypeImageJPEG Base64ImageSourceMediaType = "image/jpeg"
125 Base64ImageSourceMediaTypeImagePNG Base64ImageSourceMediaType = "image/png"
126 Base64ImageSourceMediaTypeImageGIF Base64ImageSourceMediaType = "image/gif"
127 Base64ImageSourceMediaTypeImageWebP Base64ImageSourceMediaType = "image/webp"
128)
129
130// The properties Data, MediaType, Type are required.
131type Base64PDFSourceParam struct {
132 Data string `json:"data,required" format:"byte"`
133 // This field can be elided, and will marshal its zero value as "application/pdf".
134 MediaType constant.ApplicationPDF `json:"media_type,required"`
135 // This field can be elided, and will marshal its zero value as "base64".
136 Type constant.Base64 `json:"type,required"`
137 paramObj
138}
139
140func (r Base64PDFSourceParam) MarshalJSON() (data []byte, err error) {
141 type shadow Base64PDFSourceParam
142 return param.MarshalObject(r, (*shadow)(&r))
143}
144func (r *Base64PDFSourceParam) UnmarshalJSON(data []byte) error {
145 return apijson.UnmarshalRoot(data, r)
146}
147
148func NewCacheControlEphemeralParam() CacheControlEphemeralParam {
149 return CacheControlEphemeralParam{
150 Type: "ephemeral",
151 }
152}
153
154// This struct has a constant value, construct it with
155// [NewCacheControlEphemeralParam].
156type CacheControlEphemeralParam struct {
157 Type constant.Ephemeral `json:"type,required"`
158 paramObj
159}
160
161func (r CacheControlEphemeralParam) MarshalJSON() (data []byte, err error) {
162 type shadow CacheControlEphemeralParam
163 return param.MarshalObject(r, (*shadow)(&r))
164}
165func (r *CacheControlEphemeralParam) UnmarshalJSON(data []byte) error {
166 return apijson.UnmarshalRoot(data, r)
167}
168
169type CitationCharLocation struct {
170 CitedText string `json:"cited_text,required"`
171 DocumentIndex int64 `json:"document_index,required"`
172 DocumentTitle string `json:"document_title,required"`
173 EndCharIndex int64 `json:"end_char_index,required"`
174 StartCharIndex int64 `json:"start_char_index,required"`
175 Type constant.CharLocation `json:"type,required"`
176 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
177 JSON struct {
178 CitedText respjson.Field
179 DocumentIndex respjson.Field
180 DocumentTitle respjson.Field
181 EndCharIndex respjson.Field
182 StartCharIndex respjson.Field
183 Type respjson.Field
184 ExtraFields map[string]respjson.Field
185 raw string
186 } `json:"-"`
187}
188
189// Returns the unmodified JSON received from the API
190func (r CitationCharLocation) RawJSON() string { return r.JSON.raw }
191func (r *CitationCharLocation) UnmarshalJSON(data []byte) error {
192 return apijson.UnmarshalRoot(data, r)
193}
194
195// The properties CitedText, DocumentIndex, DocumentTitle, EndCharIndex,
196// StartCharIndex, Type are required.
197type CitationCharLocationParam struct {
198 DocumentTitle param.Opt[string] `json:"document_title,omitzero,required"`
199 CitedText string `json:"cited_text,required"`
200 DocumentIndex int64 `json:"document_index,required"`
201 EndCharIndex int64 `json:"end_char_index,required"`
202 StartCharIndex int64 `json:"start_char_index,required"`
203 // This field can be elided, and will marshal its zero value as "char_location".
204 Type constant.CharLocation `json:"type,required"`
205 paramObj
206}
207
208func (r CitationCharLocationParam) MarshalJSON() (data []byte, err error) {
209 type shadow CitationCharLocationParam
210 return param.MarshalObject(r, (*shadow)(&r))
211}
212func (r *CitationCharLocationParam) UnmarshalJSON(data []byte) error {
213 return apijson.UnmarshalRoot(data, r)
214}
215
216type CitationContentBlockLocation struct {
217 CitedText string `json:"cited_text,required"`
218 DocumentIndex int64 `json:"document_index,required"`
219 DocumentTitle string `json:"document_title,required"`
220 EndBlockIndex int64 `json:"end_block_index,required"`
221 StartBlockIndex int64 `json:"start_block_index,required"`
222 Type constant.ContentBlockLocation `json:"type,required"`
223 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
224 JSON struct {
225 CitedText respjson.Field
226 DocumentIndex respjson.Field
227 DocumentTitle respjson.Field
228 EndBlockIndex respjson.Field
229 StartBlockIndex respjson.Field
230 Type respjson.Field
231 ExtraFields map[string]respjson.Field
232 raw string
233 } `json:"-"`
234}
235
236// Returns the unmodified JSON received from the API
237func (r CitationContentBlockLocation) RawJSON() string { return r.JSON.raw }
238func (r *CitationContentBlockLocation) UnmarshalJSON(data []byte) error {
239 return apijson.UnmarshalRoot(data, r)
240}
241
242// The properties CitedText, DocumentIndex, DocumentTitle, EndBlockIndex,
243// StartBlockIndex, Type are required.
244type CitationContentBlockLocationParam struct {
245 DocumentTitle param.Opt[string] `json:"document_title,omitzero,required"`
246 CitedText string `json:"cited_text,required"`
247 DocumentIndex int64 `json:"document_index,required"`
248 EndBlockIndex int64 `json:"end_block_index,required"`
249 StartBlockIndex int64 `json:"start_block_index,required"`
250 // This field can be elided, and will marshal its zero value as
251 // "content_block_location".
252 Type constant.ContentBlockLocation `json:"type,required"`
253 paramObj
254}
255
256func (r CitationContentBlockLocationParam) MarshalJSON() (data []byte, err error) {
257 type shadow CitationContentBlockLocationParam
258 return param.MarshalObject(r, (*shadow)(&r))
259}
260func (r *CitationContentBlockLocationParam) UnmarshalJSON(data []byte) error {
261 return apijson.UnmarshalRoot(data, r)
262}
263
264type CitationPageLocation struct {
265 CitedText string `json:"cited_text,required"`
266 DocumentIndex int64 `json:"document_index,required"`
267 DocumentTitle string `json:"document_title,required"`
268 EndPageNumber int64 `json:"end_page_number,required"`
269 StartPageNumber int64 `json:"start_page_number,required"`
270 Type constant.PageLocation `json:"type,required"`
271 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
272 JSON struct {
273 CitedText respjson.Field
274 DocumentIndex respjson.Field
275 DocumentTitle respjson.Field
276 EndPageNumber respjson.Field
277 StartPageNumber respjson.Field
278 Type respjson.Field
279 ExtraFields map[string]respjson.Field
280 raw string
281 } `json:"-"`
282}
283
284// Returns the unmodified JSON received from the API
285func (r CitationPageLocation) RawJSON() string { return r.JSON.raw }
286func (r *CitationPageLocation) UnmarshalJSON(data []byte) error {
287 return apijson.UnmarshalRoot(data, r)
288}
289
290// The properties CitedText, DocumentIndex, DocumentTitle, EndPageNumber,
291// StartPageNumber, Type are required.
292type CitationPageLocationParam struct {
293 DocumentTitle param.Opt[string] `json:"document_title,omitzero,required"`
294 CitedText string `json:"cited_text,required"`
295 DocumentIndex int64 `json:"document_index,required"`
296 EndPageNumber int64 `json:"end_page_number,required"`
297 StartPageNumber int64 `json:"start_page_number,required"`
298 // This field can be elided, and will marshal its zero value as "page_location".
299 Type constant.PageLocation `json:"type,required"`
300 paramObj
301}
302
303func (r CitationPageLocationParam) MarshalJSON() (data []byte, err error) {
304 type shadow CitationPageLocationParam
305 return param.MarshalObject(r, (*shadow)(&r))
306}
307func (r *CitationPageLocationParam) UnmarshalJSON(data []byte) error {
308 return apijson.UnmarshalRoot(data, r)
309}
310
311// The properties CitedText, EncryptedIndex, Title, Type, URL are required.
312type CitationWebSearchResultLocationParam struct {
313 Title param.Opt[string] `json:"title,omitzero,required"`
314 CitedText string `json:"cited_text,required"`
315 EncryptedIndex string `json:"encrypted_index,required"`
316 URL string `json:"url,required"`
317 // This field can be elided, and will marshal its zero value as
318 // "web_search_result_location".
319 Type constant.WebSearchResultLocation `json:"type,required"`
320 paramObj
321}
322
323func (r CitationWebSearchResultLocationParam) MarshalJSON() (data []byte, err error) {
324 type shadow CitationWebSearchResultLocationParam
325 return param.MarshalObject(r, (*shadow)(&r))
326}
327func (r *CitationWebSearchResultLocationParam) UnmarshalJSON(data []byte) error {
328 return apijson.UnmarshalRoot(data, r)
329}
330
331type CitationsConfigParam struct {
332 Enabled param.Opt[bool] `json:"enabled,omitzero"`
333 paramObj
334}
335
336func (r CitationsConfigParam) MarshalJSON() (data []byte, err error) {
337 type shadow CitationsConfigParam
338 return param.MarshalObject(r, (*shadow)(&r))
339}
340func (r *CitationsConfigParam) UnmarshalJSON(data []byte) error {
341 return apijson.UnmarshalRoot(data, r)
342}
343
344type CitationsDelta struct {
345 Citation CitationsDeltaCitationUnion `json:"citation,required"`
346 Type constant.CitationsDelta `json:"type,required"`
347 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
348 JSON struct {
349 Citation respjson.Field
350 Type respjson.Field
351 ExtraFields map[string]respjson.Field
352 raw string
353 } `json:"-"`
354}
355
356// Returns the unmodified JSON received from the API
357func (r CitationsDelta) RawJSON() string { return r.JSON.raw }
358func (r *CitationsDelta) UnmarshalJSON(data []byte) error {
359 return apijson.UnmarshalRoot(data, r)
360}
361
362// CitationsDeltaCitationUnion contains all possible properties and values from
363// [CitationCharLocation], [CitationPageLocation], [CitationContentBlockLocation],
364// [CitationsWebSearchResultLocation].
365//
366// Use the [CitationsDeltaCitationUnion.AsAny] method to switch on the variant.
367//
368// Use the methods beginning with 'As' to cast the union to one of its variants.
369type CitationsDeltaCitationUnion struct {
370 CitedText string `json:"cited_text"`
371 DocumentIndex int64 `json:"document_index"`
372 DocumentTitle string `json:"document_title"`
373 // This field is from variant [CitationCharLocation].
374 EndCharIndex int64 `json:"end_char_index"`
375 // This field is from variant [CitationCharLocation].
376 StartCharIndex int64 `json:"start_char_index"`
377 // Any of "char_location", "page_location", "content_block_location",
378 // "web_search_result_location".
379 Type string `json:"type"`
380 // This field is from variant [CitationPageLocation].
381 EndPageNumber int64 `json:"end_page_number"`
382 // This field is from variant [CitationPageLocation].
383 StartPageNumber int64 `json:"start_page_number"`
384 // This field is from variant [CitationContentBlockLocation].
385 EndBlockIndex int64 `json:"end_block_index"`
386 // This field is from variant [CitationContentBlockLocation].
387 StartBlockIndex int64 `json:"start_block_index"`
388 // This field is from variant [CitationsWebSearchResultLocation].
389 EncryptedIndex string `json:"encrypted_index"`
390 // This field is from variant [CitationsWebSearchResultLocation].
391 Title string `json:"title"`
392 // This field is from variant [CitationsWebSearchResultLocation].
393 URL string `json:"url"`
394 JSON struct {
395 CitedText respjson.Field
396 DocumentIndex respjson.Field
397 DocumentTitle respjson.Field
398 EndCharIndex respjson.Field
399 StartCharIndex respjson.Field
400 Type respjson.Field
401 EndPageNumber respjson.Field
402 StartPageNumber respjson.Field
403 EndBlockIndex respjson.Field
404 StartBlockIndex respjson.Field
405 EncryptedIndex respjson.Field
406 Title respjson.Field
407 URL respjson.Field
408 raw string
409 } `json:"-"`
410}
411
412// anyCitationsDeltaCitation is implemented by each variant of
413// [CitationsDeltaCitationUnion] to add type safety for the return type of
414// [CitationsDeltaCitationUnion.AsAny]
415type anyCitationsDeltaCitation interface {
416 implCitationsDeltaCitationUnion()
417}
418
419func (CitationCharLocation) implCitationsDeltaCitationUnion() {}
420func (CitationPageLocation) implCitationsDeltaCitationUnion() {}
421func (CitationContentBlockLocation) implCitationsDeltaCitationUnion() {}
422func (CitationsWebSearchResultLocation) implCitationsDeltaCitationUnion() {}
423
424// Use the following switch statement to find the correct variant
425//
426// switch variant := CitationsDeltaCitationUnion.AsAny().(type) {
427// case anthropic.CitationCharLocation:
428// case anthropic.CitationPageLocation:
429// case anthropic.CitationContentBlockLocation:
430// case anthropic.CitationsWebSearchResultLocation:
431// default:
432// fmt.Errorf("no variant present")
433// }
434func (u CitationsDeltaCitationUnion) AsAny() anyCitationsDeltaCitation {
435 switch u.Type {
436 case "char_location":
437 return u.AsCharLocation()
438 case "page_location":
439 return u.AsPageLocation()
440 case "content_block_location":
441 return u.AsContentBlockLocation()
442 case "web_search_result_location":
443 return u.AsWebSearchResultLocation()
444 }
445 return nil
446}
447
448func (u CitationsDeltaCitationUnion) AsCharLocation() (v CitationCharLocation) {
449 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
450 return
451}
452
453func (u CitationsDeltaCitationUnion) AsPageLocation() (v CitationPageLocation) {
454 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
455 return
456}
457
458func (u CitationsDeltaCitationUnion) AsContentBlockLocation() (v CitationContentBlockLocation) {
459 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
460 return
461}
462
463func (u CitationsDeltaCitationUnion) AsWebSearchResultLocation() (v CitationsWebSearchResultLocation) {
464 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
465 return
466}
467
468// Returns the unmodified JSON received from the API
469func (u CitationsDeltaCitationUnion) RawJSON() string { return u.JSON.raw }
470
471func (r *CitationsDeltaCitationUnion) UnmarshalJSON(data []byte) error {
472 return apijson.UnmarshalRoot(data, r)
473}
474
475type CitationsWebSearchResultLocation struct {
476 CitedText string `json:"cited_text,required"`
477 EncryptedIndex string `json:"encrypted_index,required"`
478 Title string `json:"title,required"`
479 Type constant.WebSearchResultLocation `json:"type,required"`
480 URL string `json:"url,required"`
481 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
482 JSON struct {
483 CitedText respjson.Field
484 EncryptedIndex respjson.Field
485 Title respjson.Field
486 Type respjson.Field
487 URL respjson.Field
488 ExtraFields map[string]respjson.Field
489 raw string
490 } `json:"-"`
491}
492
493// Returns the unmodified JSON received from the API
494func (r CitationsWebSearchResultLocation) RawJSON() string { return r.JSON.raw }
495func (r *CitationsWebSearchResultLocation) UnmarshalJSON(data []byte) error {
496 return apijson.UnmarshalRoot(data, r)
497}
498
499// ContentBlockUnion contains all possible properties and values from [TextBlock],
500// [ToolUseBlock], [ServerToolUseBlock], [WebSearchToolResultBlock],
501// [ThinkingBlock], [RedactedThinkingBlock].
502//
503// Use the [ContentBlockUnion.AsAny] method to switch on the variant.
504//
505// Use the methods beginning with 'As' to cast the union to one of its variants.
506type ContentBlockUnion struct {
507 // This field is from variant [TextBlock].
508 Citations []TextCitationUnion `json:"citations"`
509 // This field is from variant [TextBlock].
510 Text string `json:"text"`
511 // Any of "text", "tool_use", "server_tool_use", "web_search_tool_result",
512 // "thinking", "redacted_thinking".
513 Type string `json:"type"`
514 ID string `json:"id"`
515 Input json.RawMessage `json:"input"`
516 Name string `json:"name"`
517 // This field is from variant [WebSearchToolResultBlock].
518 Content WebSearchToolResultBlockContentUnion `json:"content"`
519 // This field is from variant [WebSearchToolResultBlock].
520 ToolUseID string `json:"tool_use_id"`
521 // This field is from variant [ThinkingBlock].
522 Signature string `json:"signature"`
523 // This field is from variant [ThinkingBlock].
524 Thinking string `json:"thinking"`
525 // This field is from variant [RedactedThinkingBlock].
526 Data string `json:"data"`
527 JSON struct {
528 Citations respjson.Field
529 Text respjson.Field
530 Type respjson.Field
531 ID respjson.Field
532 Input respjson.Field
533 Name respjson.Field
534 Content respjson.Field
535 ToolUseID respjson.Field
536 Signature respjson.Field
537 Thinking respjson.Field
538 Data respjson.Field
539 raw string
540 } `json:"-"`
541}
542
543func (r ContentBlockUnion) ToParam() ContentBlockParamUnion {
544 switch variant := r.AsAny().(type) {
545 case TextBlock:
546 p := variant.ToParam()
547 return ContentBlockParamUnion{OfText: &p}
548 case ToolUseBlock:
549 p := variant.ToParam()
550 return ContentBlockParamUnion{OfToolUse: &p}
551 case ThinkingBlock:
552 p := variant.ToParam()
553 return ContentBlockParamUnion{OfThinking: &p}
554 case RedactedThinkingBlock:
555 p := variant.ToParam()
556 return ContentBlockParamUnion{OfRedactedThinking: &p}
557 }
558 return ContentBlockParamUnion{}
559}
560
561// anyContentBlock is implemented by each variant of [ContentBlockUnion] to add
562// type safety for the return type of [ContentBlockUnion.AsAny]
563type anyContentBlock interface {
564 implContentBlockUnion()
565}
566
567func (TextBlock) implContentBlockUnion() {}
568func (ToolUseBlock) implContentBlockUnion() {}
569func (ServerToolUseBlock) implContentBlockUnion() {}
570func (WebSearchToolResultBlock) implContentBlockUnion() {}
571func (ThinkingBlock) implContentBlockUnion() {}
572func (RedactedThinkingBlock) implContentBlockUnion() {}
573
574// Use the following switch statement to find the correct variant
575//
576// switch variant := ContentBlockUnion.AsAny().(type) {
577// case anthropic.TextBlock:
578// case anthropic.ToolUseBlock:
579// case anthropic.ServerToolUseBlock:
580// case anthropic.WebSearchToolResultBlock:
581// case anthropic.ThinkingBlock:
582// case anthropic.RedactedThinkingBlock:
583// default:
584// fmt.Errorf("no variant present")
585// }
586func (u ContentBlockUnion) AsAny() anyContentBlock {
587 switch u.Type {
588 case "text":
589 return u.AsText()
590 case "tool_use":
591 return u.AsToolUse()
592 case "server_tool_use":
593 return u.AsServerToolUse()
594 case "web_search_tool_result":
595 return u.AsWebSearchToolResult()
596 case "thinking":
597 return u.AsThinking()
598 case "redacted_thinking":
599 return u.AsRedactedThinking()
600 }
601 return nil
602}
603
604func (u ContentBlockUnion) AsText() (v TextBlock) {
605 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
606 return
607}
608
609func (u ContentBlockUnion) AsToolUse() (v ToolUseBlock) {
610 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
611 return
612}
613
614func (u ContentBlockUnion) AsServerToolUse() (v ServerToolUseBlock) {
615 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
616 return
617}
618
619func (u ContentBlockUnion) AsWebSearchToolResult() (v WebSearchToolResultBlock) {
620 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
621 return
622}
623
624func (u ContentBlockUnion) AsThinking() (v ThinkingBlock) {
625 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
626 return
627}
628
629func (u ContentBlockUnion) AsRedactedThinking() (v RedactedThinkingBlock) {
630 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
631 return
632}
633
634// Returns the unmodified JSON received from the API
635func (u ContentBlockUnion) RawJSON() string { return u.JSON.raw }
636
637func (r *ContentBlockUnion) UnmarshalJSON(data []byte) error {
638 return apijson.UnmarshalRoot(data, r)
639}
640
641func NewServerToolUseBlock(id string, input any) ContentBlockParamUnion {
642 var serverToolUse ServerToolUseBlockParam
643 serverToolUse.ID = id
644 serverToolUse.Input = input
645 return ContentBlockParamUnion{OfServerToolUse: &serverToolUse}
646}
647
648func NewWebSearchToolResultBlock[
649 T []WebSearchResultBlockParam | WebSearchToolRequestErrorParam,
650](content T, toolUseID string) ContentBlockParamUnion {
651 var webSearchToolResult WebSearchToolResultBlockParam
652 switch v := any(content).(type) {
653 case []WebSearchResultBlockParam:
654 webSearchToolResult.Content.OfWebSearchToolResultBlockItem = v
655 case WebSearchToolRequestErrorParam:
656 webSearchToolResult.Content.OfRequestWebSearchToolResultError = &v
657 }
658 webSearchToolResult.ToolUseID = toolUseID
659 return ContentBlockParamUnion{OfWebSearchToolResult: &webSearchToolResult}
660}
661
662func NewTextBlock(text string) ContentBlockParamUnion {
663 var variant TextBlockParam
664 variant.Text = text
665 return ContentBlockParamUnion{OfText: &variant}
666}
667
668func NewImageBlock[T Base64ImageSourceParam | URLImageSourceParam](source T) ContentBlockParamUnion {
669 var image ImageBlockParam
670 switch v := any(source).(type) {
671 case Base64ImageSourceParam:
672 image.Source.OfBase64 = &v
673 case URLImageSourceParam:
674 image.Source.OfURL = &v
675 }
676 return ContentBlockParamUnion{OfImage: &image}
677}
678
679func NewImageBlockBase64(mediaType string, encodedData string) ContentBlockParamUnion {
680 return ContentBlockParamUnion{
681 OfImage: &ImageBlockParam{
682 Source: ImageBlockParamSourceUnion{
683 OfBase64: &Base64ImageSourceParam{
684 Data: encodedData,
685 MediaType: Base64ImageSourceMediaType(mediaType),
686 },
687 },
688 },
689 }
690}
691
692func NewToolUseBlock(id string, input any, name string) ContentBlockParamUnion {
693 var toolUse ToolUseBlockParam
694 toolUse.ID = id
695 toolUse.Input = input
696 toolUse.Name = name
697 return ContentBlockParamUnion{OfToolUse: &toolUse}
698}
699
700func NewToolResultBlock(toolUseID string, content string, isError bool) ContentBlockParamUnion {
701 toolBlock := ToolResultBlockParam{
702 ToolUseID: toolUseID,
703 Content: []ToolResultBlockParamContentUnion{
704 {OfText: &TextBlockParam{Text: content}},
705 },
706 IsError: Bool(isError),
707 }
708 return ContentBlockParamUnion{OfToolResult: &toolBlock}
709}
710
711func NewDocumentBlock[
712 T Base64PDFSourceParam | PlainTextSourceParam | ContentBlockSourceParam | URLPDFSourceParam,
713](source T) ContentBlockParamUnion {
714 var document DocumentBlockParam
715 switch v := any(source).(type) {
716 case Base64PDFSourceParam:
717 document.Source.OfBase64 = &v
718 case PlainTextSourceParam:
719 document.Source.OfText = &v
720 case ContentBlockSourceParam:
721 document.Source.OfContent = &v
722 case URLPDFSourceParam:
723 document.Source.OfURL = &v
724 }
725 return ContentBlockParamUnion{OfDocument: &document}
726}
727
728func NewThinkingBlock(signature string, thinking string) ContentBlockParamUnion {
729 var variant ThinkingBlockParam
730 variant.Signature = signature
731 variant.Thinking = thinking
732 return ContentBlockParamUnion{OfThinking: &variant}
733}
734
735func NewRedactedThinkingBlock(data string) ContentBlockParamUnion {
736 var redactedThinking RedactedThinkingBlockParam
737 redactedThinking.Data = data
738 return ContentBlockParamUnion{OfRedactedThinking: &redactedThinking}
739}
740
741// Only one field can be non-zero.
742//
743// Use [param.IsOmitted] to confirm if a field is set.
744type ContentBlockParamUnion struct {
745 OfServerToolUse *ServerToolUseBlockParam `json:",omitzero,inline"`
746 OfWebSearchToolResult *WebSearchToolResultBlockParam `json:",omitzero,inline"`
747 OfText *TextBlockParam `json:",omitzero,inline"`
748 OfImage *ImageBlockParam `json:",omitzero,inline"`
749 OfToolUse *ToolUseBlockParam `json:",omitzero,inline"`
750 OfToolResult *ToolResultBlockParam `json:",omitzero,inline"`
751 OfDocument *DocumentBlockParam `json:",omitzero,inline"`
752 OfThinking *ThinkingBlockParam `json:",omitzero,inline"`
753 OfRedactedThinking *RedactedThinkingBlockParam `json:",omitzero,inline"`
754 paramUnion
755}
756
757func (u ContentBlockParamUnion) MarshalJSON() ([]byte, error) {
758 return param.MarshalUnion(u, u.OfServerToolUse,
759 u.OfWebSearchToolResult,
760 u.OfText,
761 u.OfImage,
762 u.OfToolUse,
763 u.OfToolResult,
764 u.OfDocument,
765 u.OfThinking,
766 u.OfRedactedThinking)
767}
768func (u *ContentBlockParamUnion) UnmarshalJSON(data []byte) error {
769 return apijson.UnmarshalRoot(data, u)
770}
771
772func (u *ContentBlockParamUnion) asAny() any {
773 if !param.IsOmitted(u.OfServerToolUse) {
774 return u.OfServerToolUse
775 } else if !param.IsOmitted(u.OfWebSearchToolResult) {
776 return u.OfWebSearchToolResult
777 } else if !param.IsOmitted(u.OfText) {
778 return u.OfText
779 } else if !param.IsOmitted(u.OfImage) {
780 return u.OfImage
781 } else if !param.IsOmitted(u.OfToolUse) {
782 return u.OfToolUse
783 } else if !param.IsOmitted(u.OfToolResult) {
784 return u.OfToolResult
785 } else if !param.IsOmitted(u.OfDocument) {
786 return u.OfDocument
787 } else if !param.IsOmitted(u.OfThinking) {
788 return u.OfThinking
789 } else if !param.IsOmitted(u.OfRedactedThinking) {
790 return u.OfRedactedThinking
791 }
792 return nil
793}
794
795// Returns a pointer to the underlying variant's property, if present.
796func (u ContentBlockParamUnion) GetText() *string {
797 if vt := u.OfText; vt != nil {
798 return &vt.Text
799 }
800 return nil
801}
802
803// Returns a pointer to the underlying variant's property, if present.
804func (u ContentBlockParamUnion) GetIsError() *bool {
805 if vt := u.OfToolResult; vt != nil && vt.IsError.Valid() {
806 return &vt.IsError.Value
807 }
808 return nil
809}
810
811// Returns a pointer to the underlying variant's property, if present.
812func (u ContentBlockParamUnion) GetContext() *string {
813 if vt := u.OfDocument; vt != nil && vt.Context.Valid() {
814 return &vt.Context.Value
815 }
816 return nil
817}
818
819// Returns a pointer to the underlying variant's property, if present.
820func (u ContentBlockParamUnion) GetTitle() *string {
821 if vt := u.OfDocument; vt != nil && vt.Title.Valid() {
822 return &vt.Title.Value
823 }
824 return nil
825}
826
827// Returns a pointer to the underlying variant's property, if present.
828func (u ContentBlockParamUnion) GetSignature() *string {
829 if vt := u.OfThinking; vt != nil {
830 return &vt.Signature
831 }
832 return nil
833}
834
835// Returns a pointer to the underlying variant's property, if present.
836func (u ContentBlockParamUnion) GetThinking() *string {
837 if vt := u.OfThinking; vt != nil {
838 return &vt.Thinking
839 }
840 return nil
841}
842
843// Returns a pointer to the underlying variant's property, if present.
844func (u ContentBlockParamUnion) GetData() *string {
845 if vt := u.OfRedactedThinking; vt != nil {
846 return &vt.Data
847 }
848 return nil
849}
850
851// Returns a pointer to the underlying variant's property, if present.
852func (u ContentBlockParamUnion) GetID() *string {
853 if vt := u.OfServerToolUse; vt != nil {
854 return (*string)(&vt.ID)
855 } else if vt := u.OfToolUse; vt != nil {
856 return (*string)(&vt.ID)
857 }
858 return nil
859}
860
861// Returns a pointer to the underlying variant's property, if present.
862func (u ContentBlockParamUnion) GetName() *string {
863 if vt := u.OfServerToolUse; vt != nil {
864 return (*string)(&vt.Name)
865 } else if vt := u.OfToolUse; vt != nil {
866 return (*string)(&vt.Name)
867 }
868 return nil
869}
870
871// Returns a pointer to the underlying variant's property, if present.
872func (u ContentBlockParamUnion) GetType() *string {
873 if vt := u.OfServerToolUse; vt != nil {
874 return (*string)(&vt.Type)
875 } else if vt := u.OfWebSearchToolResult; vt != nil {
876 return (*string)(&vt.Type)
877 } else if vt := u.OfText; vt != nil {
878 return (*string)(&vt.Type)
879 } else if vt := u.OfImage; vt != nil {
880 return (*string)(&vt.Type)
881 } else if vt := u.OfToolUse; vt != nil {
882 return (*string)(&vt.Type)
883 } else if vt := u.OfToolResult; vt != nil {
884 return (*string)(&vt.Type)
885 } else if vt := u.OfDocument; vt != nil {
886 return (*string)(&vt.Type)
887 } else if vt := u.OfThinking; vt != nil {
888 return (*string)(&vt.Type)
889 } else if vt := u.OfRedactedThinking; vt != nil {
890 return (*string)(&vt.Type)
891 }
892 return nil
893}
894
895// Returns a pointer to the underlying variant's property, if present.
896func (u ContentBlockParamUnion) GetToolUseID() *string {
897 if vt := u.OfWebSearchToolResult; vt != nil {
898 return (*string)(&vt.ToolUseID)
899 } else if vt := u.OfToolResult; vt != nil {
900 return (*string)(&vt.ToolUseID)
901 }
902 return nil
903}
904
905// Returns a pointer to the underlying variant's Input property, if present.
906func (u ContentBlockParamUnion) GetInput() *any {
907 if vt := u.OfServerToolUse; vt != nil {
908 return &vt.Input
909 } else if vt := u.OfToolUse; vt != nil {
910 return &vt.Input
911 }
912 return nil
913}
914
915// Returns a pointer to the underlying variant's CacheControl property, if present.
916func (u ContentBlockParamUnion) GetCacheControl() *CacheControlEphemeralParam {
917 if vt := u.OfServerToolUse; vt != nil {
918 return &vt.CacheControl
919 } else if vt := u.OfWebSearchToolResult; vt != nil {
920 return &vt.CacheControl
921 } else if vt := u.OfText; vt != nil {
922 return &vt.CacheControl
923 } else if vt := u.OfImage; vt != nil {
924 return &vt.CacheControl
925 } else if vt := u.OfToolUse; vt != nil {
926 return &vt.CacheControl
927 } else if vt := u.OfToolResult; vt != nil {
928 return &vt.CacheControl
929 } else if vt := u.OfDocument; vt != nil {
930 return &vt.CacheControl
931 }
932 return nil
933}
934
935// Returns a subunion which exports methods to access subproperties
936//
937// Or use AsAny() to get the underlying value
938func (u ContentBlockParamUnion) GetContent() (res contentBlockParamUnionContent) {
939 if vt := u.OfWebSearchToolResult; vt != nil {
940 res.any = vt.Content.asAny()
941 } else if vt := u.OfToolResult; vt != nil {
942 res.any = &vt.Content
943 }
944 return
945}
946
947// Can have the runtime types [_[]WebSearchResultBlockParam],
948// [_[]ToolResultBlockParamContentUnion]
949type contentBlockParamUnionContent struct{ any }
950
951// Use the following switch statement to get the type of the union:
952//
953// switch u.AsAny().(type) {
954// case *[]anthropic.WebSearchResultBlockParam:
955// case *[]anthropic.ToolResultBlockParamContentUnion:
956// default:
957// fmt.Errorf("not present")
958// }
959func (u contentBlockParamUnionContent) AsAny() any { return u.any }
960
961// Returns a subunion which exports methods to access subproperties
962//
963// Or use AsAny() to get the underlying value
964func (u ContentBlockParamUnion) GetCitations() (res contentBlockParamUnionCitations) {
965 if vt := u.OfText; vt != nil {
966 res.any = &vt.Citations
967 } else if vt := u.OfDocument; vt != nil {
968 res.any = &vt.Citations
969 }
970 return
971}
972
973// Can have the runtime types [*[]TextCitationParamUnion], [*CitationsConfigParam]
974type contentBlockParamUnionCitations struct{ any }
975
976// Use the following switch statement to get the type of the union:
977//
978// switch u.AsAny().(type) {
979// case *[]anthropic.TextCitationParamUnion:
980// case *anthropic.CitationsConfigParam:
981// default:
982// fmt.Errorf("not present")
983// }
984func (u contentBlockParamUnionCitations) AsAny() any { return u.any }
985
986// Returns a subunion which exports methods to access subproperties
987//
988// Or use AsAny() to get the underlying value
989func (u ContentBlockParamUnion) GetSource() (res contentBlockParamUnionSource) {
990 if vt := u.OfImage; vt != nil {
991 res.any = vt.Source.asAny()
992 } else if vt := u.OfDocument; vt != nil {
993 res.any = vt.Source.asAny()
994 }
995 return
996}
997
998// Can have the runtime types [*Base64ImageSourceParam], [*URLImageSourceParam],
999// [*Base64PDFSourceParam], [*PlainTextSourceParam], [*ContentBlockSourceParam],
1000// [*URLPDFSourceParam]
1001type contentBlockParamUnionSource struct{ any }
1002
1003// Use the following switch statement to get the type of the union:
1004//
1005// switch u.AsAny().(type) {
1006// case *anthropic.Base64ImageSourceParam:
1007// case *anthropic.URLImageSourceParam:
1008// case *anthropic.Base64PDFSourceParam:
1009// case *anthropic.PlainTextSourceParam:
1010// case *anthropic.ContentBlockSourceParam:
1011// case *anthropic.URLPDFSourceParam:
1012// default:
1013// fmt.Errorf("not present")
1014// }
1015func (u contentBlockParamUnionSource) AsAny() any { return u.any }
1016
1017// Returns a pointer to the underlying variant's property, if present.
1018func (u contentBlockParamUnionSource) GetContent() *ContentBlockSourceContentUnionParam {
1019 switch vt := u.any.(type) {
1020 case *DocumentBlockParamSourceUnion:
1021 return vt.GetContent()
1022 }
1023 return nil
1024}
1025
1026// Returns a pointer to the underlying variant's property, if present.
1027func (u contentBlockParamUnionSource) GetData() *string {
1028 switch vt := u.any.(type) {
1029 case *ImageBlockParamSourceUnion:
1030 return vt.GetData()
1031 case *DocumentBlockParamSourceUnion:
1032 return vt.GetData()
1033 }
1034 return nil
1035}
1036
1037// Returns a pointer to the underlying variant's property, if present.
1038func (u contentBlockParamUnionSource) GetMediaType() *string {
1039 switch vt := u.any.(type) {
1040 case *ImageBlockParamSourceUnion:
1041 return vt.GetMediaType()
1042 case *DocumentBlockParamSourceUnion:
1043 return vt.GetMediaType()
1044 }
1045 return nil
1046}
1047
1048// Returns a pointer to the underlying variant's property, if present.
1049func (u contentBlockParamUnionSource) GetType() *string {
1050 switch vt := u.any.(type) {
1051 case *ImageBlockParamSourceUnion:
1052 return vt.GetType()
1053 case *DocumentBlockParamSourceUnion:
1054 return vt.GetType()
1055 }
1056 return nil
1057}
1058
1059// Returns a pointer to the underlying variant's property, if present.
1060func (u contentBlockParamUnionSource) GetURL() *string {
1061 switch vt := u.any.(type) {
1062 case *ImageBlockParamSourceUnion:
1063 return vt.GetURL()
1064 case *DocumentBlockParamSourceUnion:
1065 return vt.GetURL()
1066 }
1067 return nil
1068}
1069
1070func init() {
1071 apijson.RegisterUnion[ContentBlockParamUnion](
1072 "type",
1073 apijson.Discriminator[ServerToolUseBlockParam]("server_tool_use"),
1074 apijson.Discriminator[WebSearchToolResultBlockParam]("web_search_tool_result"),
1075 apijson.Discriminator[TextBlockParam]("text"),
1076 apijson.Discriminator[ImageBlockParam]("image"),
1077 apijson.Discriminator[ToolUseBlockParam]("tool_use"),
1078 apijson.Discriminator[ToolResultBlockParam]("tool_result"),
1079 apijson.Discriminator[DocumentBlockParam]("document"),
1080 apijson.Discriminator[ThinkingBlockParam]("thinking"),
1081 apijson.Discriminator[RedactedThinkingBlockParam]("redacted_thinking"),
1082 )
1083}
1084
1085func init() {
1086 apijson.RegisterUnion[DocumentBlockParamSourceUnion](
1087 "type",
1088 apijson.Discriminator[Base64PDFSourceParam]("base64"),
1089 apijson.Discriminator[PlainTextSourceParam]("text"),
1090 apijson.Discriminator[ContentBlockSourceParam]("content"),
1091 apijson.Discriminator[URLPDFSourceParam]("url"),
1092 )
1093}
1094
1095func init() {
1096 apijson.RegisterUnion[ImageBlockParamSourceUnion](
1097 "type",
1098 apijson.Discriminator[Base64ImageSourceParam]("base64"),
1099 apijson.Discriminator[URLImageSourceParam]("url"),
1100 )
1101}
1102
1103func init() {
1104 apijson.RegisterUnion[TextCitationParamUnion](
1105 "type",
1106 apijson.Discriminator[CitationCharLocationParam]("char_location"),
1107 apijson.Discriminator[CitationPageLocationParam]("page_location"),
1108 apijson.Discriminator[CitationContentBlockLocationParam]("content_block_location"),
1109 apijson.Discriminator[CitationWebSearchResultLocationParam]("web_search_result_location"),
1110 )
1111}
1112
1113func init() {
1114 apijson.RegisterUnion[ThinkingConfigParamUnion](
1115 "type",
1116 apijson.Discriminator[ThinkingConfigEnabledParam]("enabled"),
1117 apijson.Discriminator[ThinkingConfigDisabledParam]("disabled"),
1118 )
1119}
1120
1121func init() {
1122 apijson.RegisterUnion[ToolChoiceUnionParam](
1123 "type",
1124 apijson.Discriminator[ToolChoiceAutoParam]("auto"),
1125 apijson.Discriminator[ToolChoiceAnyParam]("any"),
1126 apijson.Discriminator[ToolChoiceToolParam]("tool"),
1127 apijson.Discriminator[ToolChoiceNoneParam]("none"),
1128 )
1129}
1130
1131func init() {
1132 apijson.RegisterUnion[ToolResultBlockParamContentUnion](
1133 "type",
1134 apijson.Discriminator[TextBlockParam]("text"),
1135 apijson.Discriminator[ImageBlockParam]("image"),
1136 )
1137}
1138
1139// The properties Content, Type are required.
1140type ContentBlockSourceParam struct {
1141 Content ContentBlockSourceContentUnionParam `json:"content,omitzero,required"`
1142 // This field can be elided, and will marshal its zero value as "content".
1143 Type constant.Content `json:"type,required"`
1144 paramObj
1145}
1146
1147func (r ContentBlockSourceParam) MarshalJSON() (data []byte, err error) {
1148 type shadow ContentBlockSourceParam
1149 return param.MarshalObject(r, (*shadow)(&r))
1150}
1151func (r *ContentBlockSourceParam) UnmarshalJSON(data []byte) error {
1152 return apijson.UnmarshalRoot(data, r)
1153}
1154
1155// Only one field can be non-zero.
1156//
1157// Use [param.IsOmitted] to confirm if a field is set.
1158type ContentBlockSourceContentUnionParam struct {
1159 OfString param.Opt[string] `json:",omitzero,inline"`
1160 OfContentBlockSourceContent []ContentBlockSourceContentUnionParam `json:",omitzero,inline"`
1161 paramUnion
1162}
1163
1164func (u ContentBlockSourceContentUnionParam) MarshalJSON() ([]byte, error) {
1165 return param.MarshalUnion(u, u.OfString, u.OfContentBlockSourceContent)
1166}
1167func (u *ContentBlockSourceContentUnionParam) UnmarshalJSON(data []byte) error {
1168 return apijson.UnmarshalRoot(data, u)
1169}
1170
1171func (u *ContentBlockSourceContentUnionParam) asAny() any {
1172 if !param.IsOmitted(u.OfString) {
1173 return &u.OfString.Value
1174 } else if !param.IsOmitted(u.OfContentBlockSourceContent) {
1175 return &u.OfContentBlockSourceContent
1176 }
1177 return nil
1178}
1179
1180// The properties Source, Type are required.
1181type DocumentBlockParam struct {
1182 Source DocumentBlockParamSourceUnion `json:"source,omitzero,required"`
1183 Context param.Opt[string] `json:"context,omitzero"`
1184 Title param.Opt[string] `json:"title,omitzero"`
1185 // Create a cache control breakpoint at this content block.
1186 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
1187 Citations CitationsConfigParam `json:"citations,omitzero"`
1188 // This field can be elided, and will marshal its zero value as "document".
1189 Type constant.Document `json:"type,required"`
1190 paramObj
1191}
1192
1193func (r DocumentBlockParam) MarshalJSON() (data []byte, err error) {
1194 type shadow DocumentBlockParam
1195 return param.MarshalObject(r, (*shadow)(&r))
1196}
1197func (r *DocumentBlockParam) UnmarshalJSON(data []byte) error {
1198 return apijson.UnmarshalRoot(data, r)
1199}
1200
1201// Only one field can be non-zero.
1202//
1203// Use [param.IsOmitted] to confirm if a field is set.
1204type DocumentBlockParamSourceUnion struct {
1205 OfBase64 *Base64PDFSourceParam `json:",omitzero,inline"`
1206 OfText *PlainTextSourceParam `json:",omitzero,inline"`
1207 OfContent *ContentBlockSourceParam `json:",omitzero,inline"`
1208 OfURL *URLPDFSourceParam `json:",omitzero,inline"`
1209 paramUnion
1210}
1211
1212func (u DocumentBlockParamSourceUnion) MarshalJSON() ([]byte, error) {
1213 return param.MarshalUnion(u, u.OfBase64, u.OfText, u.OfContent, u.OfURL)
1214}
1215func (u *DocumentBlockParamSourceUnion) UnmarshalJSON(data []byte) error {
1216 return apijson.UnmarshalRoot(data, u)
1217}
1218
1219func (u *DocumentBlockParamSourceUnion) asAny() any {
1220 if !param.IsOmitted(u.OfBase64) {
1221 return u.OfBase64
1222 } else if !param.IsOmitted(u.OfText) {
1223 return u.OfText
1224 } else if !param.IsOmitted(u.OfContent) {
1225 return u.OfContent
1226 } else if !param.IsOmitted(u.OfURL) {
1227 return u.OfURL
1228 }
1229 return nil
1230}
1231
1232// Returns a pointer to the underlying variant's property, if present.
1233func (u DocumentBlockParamSourceUnion) GetContent() *ContentBlockSourceContentUnionParam {
1234 if vt := u.OfContent; vt != nil {
1235 return &vt.Content
1236 }
1237 return nil
1238}
1239
1240// Returns a pointer to the underlying variant's property, if present.
1241func (u DocumentBlockParamSourceUnion) GetURL() *string {
1242 if vt := u.OfURL; vt != nil {
1243 return &vt.URL
1244 }
1245 return nil
1246}
1247
1248// Returns a pointer to the underlying variant's property, if present.
1249func (u DocumentBlockParamSourceUnion) GetData() *string {
1250 if vt := u.OfBase64; vt != nil {
1251 return (*string)(&vt.Data)
1252 } else if vt := u.OfText; vt != nil {
1253 return (*string)(&vt.Data)
1254 }
1255 return nil
1256}
1257
1258// Returns a pointer to the underlying variant's property, if present.
1259func (u DocumentBlockParamSourceUnion) GetMediaType() *string {
1260 if vt := u.OfBase64; vt != nil {
1261 return (*string)(&vt.MediaType)
1262 } else if vt := u.OfText; vt != nil {
1263 return (*string)(&vt.MediaType)
1264 }
1265 return nil
1266}
1267
1268// Returns a pointer to the underlying variant's property, if present.
1269func (u DocumentBlockParamSourceUnion) GetType() *string {
1270 if vt := u.OfBase64; vt != nil {
1271 return (*string)(&vt.Type)
1272 } else if vt := u.OfText; vt != nil {
1273 return (*string)(&vt.Type)
1274 } else if vt := u.OfContent; vt != nil {
1275 return (*string)(&vt.Type)
1276 } else if vt := u.OfURL; vt != nil {
1277 return (*string)(&vt.Type)
1278 }
1279 return nil
1280}
1281
1282// The properties Source, Type are required.
1283type ImageBlockParam struct {
1284 Source ImageBlockParamSourceUnion `json:"source,omitzero,required"`
1285 // Create a cache control breakpoint at this content block.
1286 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
1287 // This field can be elided, and will marshal its zero value as "image".
1288 Type constant.Image `json:"type,required"`
1289 paramObj
1290}
1291
1292func (r ImageBlockParam) MarshalJSON() (data []byte, err error) {
1293 type shadow ImageBlockParam
1294 return param.MarshalObject(r, (*shadow)(&r))
1295}
1296func (r *ImageBlockParam) UnmarshalJSON(data []byte) error {
1297 return apijson.UnmarshalRoot(data, r)
1298}
1299
1300// Only one field can be non-zero.
1301//
1302// Use [param.IsOmitted] to confirm if a field is set.
1303type ImageBlockParamSourceUnion struct {
1304 OfBase64 *Base64ImageSourceParam `json:",omitzero,inline"`
1305 OfURL *URLImageSourceParam `json:",omitzero,inline"`
1306 paramUnion
1307}
1308
1309func (u ImageBlockParamSourceUnion) MarshalJSON() ([]byte, error) {
1310 return param.MarshalUnion(u, u.OfBase64, u.OfURL)
1311}
1312func (u *ImageBlockParamSourceUnion) UnmarshalJSON(data []byte) error {
1313 return apijson.UnmarshalRoot(data, u)
1314}
1315
1316func (u *ImageBlockParamSourceUnion) asAny() any {
1317 if !param.IsOmitted(u.OfBase64) {
1318 return u.OfBase64
1319 } else if !param.IsOmitted(u.OfURL) {
1320 return u.OfURL
1321 }
1322 return nil
1323}
1324
1325// Returns a pointer to the underlying variant's property, if present.
1326func (u ImageBlockParamSourceUnion) GetData() *string {
1327 if vt := u.OfBase64; vt != nil {
1328 return &vt.Data
1329 }
1330 return nil
1331}
1332
1333// Returns a pointer to the underlying variant's property, if present.
1334func (u ImageBlockParamSourceUnion) GetMediaType() *string {
1335 if vt := u.OfBase64; vt != nil {
1336 return (*string)(&vt.MediaType)
1337 }
1338 return nil
1339}
1340
1341// Returns a pointer to the underlying variant's property, if present.
1342func (u ImageBlockParamSourceUnion) GetURL() *string {
1343 if vt := u.OfURL; vt != nil {
1344 return &vt.URL
1345 }
1346 return nil
1347}
1348
1349// Returns a pointer to the underlying variant's property, if present.
1350func (u ImageBlockParamSourceUnion) GetType() *string {
1351 if vt := u.OfBase64; vt != nil {
1352 return (*string)(&vt.Type)
1353 } else if vt := u.OfURL; vt != nil {
1354 return (*string)(&vt.Type)
1355 }
1356 return nil
1357}
1358
1359type InputJSONDelta struct {
1360 PartialJSON string `json:"partial_json,required"`
1361 Type constant.InputJSONDelta `json:"type,required"`
1362 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
1363 JSON struct {
1364 PartialJSON respjson.Field
1365 Type respjson.Field
1366 ExtraFields map[string]respjson.Field
1367 raw string
1368 } `json:"-"`
1369}
1370
1371// Returns the unmodified JSON received from the API
1372func (r InputJSONDelta) RawJSON() string { return r.JSON.raw }
1373func (r *InputJSONDelta) UnmarshalJSON(data []byte) error {
1374 return apijson.UnmarshalRoot(data, r)
1375}
1376
1377type Message struct {
1378 // Unique object identifier.
1379 //
1380 // The format and length of IDs may change over time.
1381 ID string `json:"id,required"`
1382 // Content generated by the model.
1383 //
1384 // This is an array of content blocks, each of which has a `type` that determines
1385 // its shape.
1386 //
1387 // Example:
1388 //
1389 // ```json
1390 // [{ "type": "text", "text": "Hi, I'm Claude." }]
1391 // ```
1392 //
1393 // If the request input `messages` ended with an `assistant` turn, then the
1394 // response `content` will continue directly from that last turn. You can use this
1395 // to constrain the model's output.
1396 //
1397 // For example, if the input `messages` were:
1398 //
1399 // ```json
1400 // [
1401 //
1402 // {
1403 // "role": "user",
1404 // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
1405 // },
1406 // { "role": "assistant", "content": "The best answer is (" }
1407 //
1408 // ]
1409 // ```
1410 //
1411 // Then the response `content` might be:
1412 //
1413 // ```json
1414 // [{ "type": "text", "text": "B)" }]
1415 // ```
1416 Content []ContentBlockUnion `json:"content,required"`
1417 // The model that will complete your prompt.\n\nSee
1418 // [models](https://docs.anthropic.com/en/docs/models-overview) for additional
1419 // details and options.
1420 Model Model `json:"model,required"`
1421 // Conversational role of the generated message.
1422 //
1423 // This will always be `"assistant"`.
1424 Role constant.Assistant `json:"role,required"`
1425 // The reason that we stopped.
1426 //
1427 // This may be one the following values:
1428 //
1429 // - `"end_turn"`: the model reached a natural stopping point
1430 // - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum
1431 // - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated
1432 // - `"tool_use"`: the model invoked one or more tools
1433 //
1434 // In non-streaming mode this value is always non-null. In streaming mode, it is
1435 // null in the `message_start` event and non-null otherwise.
1436 //
1437 // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn",
1438 // "refusal".
1439 StopReason StopReason `json:"stop_reason,required"`
1440 // Which custom stop sequence was generated, if any.
1441 //
1442 // This value will be a non-null string if one of your custom stop sequences was
1443 // generated.
1444 StopSequence string `json:"stop_sequence,required"`
1445 // Object type.
1446 //
1447 // For Messages, this is always `"message"`.
1448 Type constant.Message `json:"type,required"`
1449 // Billing and rate-limit usage.
1450 //
1451 // Anthropic's API bills and rate-limits by token counts, as tokens represent the
1452 // underlying cost to our systems.
1453 //
1454 // Under the hood, the API transforms requests into a format suitable for the
1455 // model. The model's output then goes through a parsing stage before becoming an
1456 // API response. As a result, the token counts in `usage` will not match one-to-one
1457 // with the exact visible content of an API request or response.
1458 //
1459 // For example, `output_tokens` will be non-zero, even for an empty string response
1460 // from Claude.
1461 //
1462 // Total input tokens in a request is the summation of `input_tokens`,
1463 // `cache_creation_input_tokens`, and `cache_read_input_tokens`.
1464 Usage Usage `json:"usage,required"`
1465 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
1466 JSON struct {
1467 ID respjson.Field
1468 Content respjson.Field
1469 Model respjson.Field
1470 Role respjson.Field
1471 StopReason respjson.Field
1472 StopSequence respjson.Field
1473 Type respjson.Field
1474 Usage respjson.Field
1475 ExtraFields map[string]respjson.Field
1476 raw string
1477 } `json:"-"`
1478}
1479
1480// Returns the unmodified JSON received from the API
1481func (r Message) RawJSON() string { return r.JSON.raw }
1482func (r *Message) UnmarshalJSON(data []byte) error {
1483 return apijson.UnmarshalRoot(data, r)
1484}
1485
1486func (r Message) ToParam() MessageParam {
1487 var p MessageParam
1488 p.Role = MessageParamRole(r.Role)
1489 p.Content = make([]ContentBlockParamUnion, len(r.Content))
1490 for i, c := range r.Content {
1491 p.Content[i] = c.ToParam()
1492 }
1493 return p
1494}
1495
1496// The reason that we stopped.
1497//
1498// This may be one the following values:
1499//
1500// - `"end_turn"`: the model reached a natural stopping point
1501// - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum
1502// - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated
1503// - `"tool_use"`: the model invoked one or more tools
1504//
1505// In non-streaming mode this value is always non-null. In streaming mode, it is
1506// null in the `message_start` event and non-null otherwise.
1507type MessageStopReason string
1508
1509const (
1510 MessageStopReasonEndTurn MessageStopReason = "end_turn"
1511 MessageStopReasonMaxTokens MessageStopReason = "max_tokens"
1512 MessageStopReasonStopSequence MessageStopReason = "stop_sequence"
1513 MessageStopReasonToolUse MessageStopReason = "tool_use"
1514)
1515
1516func MessageCountTokensToolParamOfTool(inputSchema ToolInputSchemaParam, name string) MessageCountTokensToolUnionParam {
1517 var variant ToolParam
1518 variant.InputSchema = inputSchema
1519 variant.Name = name
1520 return MessageCountTokensToolUnionParam{OfTool: &variant}
1521}
1522
1523// Only one field can be non-zero.
1524//
1525// Use [param.IsOmitted] to confirm if a field is set.
1526type MessageCountTokensToolUnionParam struct {
1527 OfTool *ToolParam `json:",omitzero,inline"`
1528 OfBashTool20250124 *ToolBash20250124Param `json:",omitzero,inline"`
1529 OfTextEditor20250124 *ToolTextEditor20250124Param `json:",omitzero,inline"`
1530 OfTextEditor20250429 *MessageCountTokensToolTextEditor20250429Param `json:",omitzero,inline"`
1531 OfWebSearchTool20250305 *WebSearchTool20250305Param `json:",omitzero,inline"`
1532 paramUnion
1533}
1534
1535func (u MessageCountTokensToolUnionParam) MarshalJSON() ([]byte, error) {
1536 return param.MarshalUnion(u, u.OfTool,
1537 u.OfBashTool20250124,
1538 u.OfTextEditor20250124,
1539 u.OfTextEditor20250429,
1540 u.OfWebSearchTool20250305)
1541}
1542func (u *MessageCountTokensToolUnionParam) UnmarshalJSON(data []byte) error {
1543 return apijson.UnmarshalRoot(data, u)
1544}
1545
1546func (u *MessageCountTokensToolUnionParam) asAny() any {
1547 if !param.IsOmitted(u.OfTool) {
1548 return u.OfTool
1549 } else if !param.IsOmitted(u.OfBashTool20250124) {
1550 return u.OfBashTool20250124
1551 } else if !param.IsOmitted(u.OfTextEditor20250124) {
1552 return u.OfTextEditor20250124
1553 } else if !param.IsOmitted(u.OfTextEditor20250429) {
1554 return u.OfTextEditor20250429
1555 } else if !param.IsOmitted(u.OfWebSearchTool20250305) {
1556 return u.OfWebSearchTool20250305
1557 }
1558 return nil
1559}
1560
1561// Returns a pointer to the underlying variant's property, if present.
1562func (u MessageCountTokensToolUnionParam) GetInputSchema() *ToolInputSchemaParam {
1563 if vt := u.OfTool; vt != nil {
1564 return &vt.InputSchema
1565 }
1566 return nil
1567}
1568
1569// Returns a pointer to the underlying variant's property, if present.
1570func (u MessageCountTokensToolUnionParam) GetDescription() *string {
1571 if vt := u.OfTool; vt != nil && vt.Description.Valid() {
1572 return &vt.Description.Value
1573 }
1574 return nil
1575}
1576
1577// Returns a pointer to the underlying variant's property, if present.
1578func (u MessageCountTokensToolUnionParam) GetAllowedDomains() []string {
1579 if vt := u.OfWebSearchTool20250305; vt != nil {
1580 return vt.AllowedDomains
1581 }
1582 return nil
1583}
1584
1585// Returns a pointer to the underlying variant's property, if present.
1586func (u MessageCountTokensToolUnionParam) GetBlockedDomains() []string {
1587 if vt := u.OfWebSearchTool20250305; vt != nil {
1588 return vt.BlockedDomains
1589 }
1590 return nil
1591}
1592
1593// Returns a pointer to the underlying variant's property, if present.
1594func (u MessageCountTokensToolUnionParam) GetMaxUses() *int64 {
1595 if vt := u.OfWebSearchTool20250305; vt != nil && vt.MaxUses.Valid() {
1596 return &vt.MaxUses.Value
1597 }
1598 return nil
1599}
1600
1601// Returns a pointer to the underlying variant's property, if present.
1602func (u MessageCountTokensToolUnionParam) GetUserLocation() *WebSearchTool20250305UserLocationParam {
1603 if vt := u.OfWebSearchTool20250305; vt != nil {
1604 return &vt.UserLocation
1605 }
1606 return nil
1607}
1608
1609// Returns a pointer to the underlying variant's property, if present.
1610func (u MessageCountTokensToolUnionParam) GetName() *string {
1611 if vt := u.OfTool; vt != nil {
1612 return (*string)(&vt.Name)
1613 } else if vt := u.OfBashTool20250124; vt != nil {
1614 return (*string)(&vt.Name)
1615 } else if vt := u.OfTextEditor20250124; vt != nil {
1616 return (*string)(&vt.Name)
1617 } else if vt := u.OfTextEditor20250429; vt != nil {
1618 return (*string)(&vt.Name)
1619 } else if vt := u.OfWebSearchTool20250305; vt != nil {
1620 return (*string)(&vt.Name)
1621 }
1622 return nil
1623}
1624
1625// Returns a pointer to the underlying variant's property, if present.
1626func (u MessageCountTokensToolUnionParam) GetType() *string {
1627 if vt := u.OfTool; vt != nil {
1628 return (*string)(&vt.Type)
1629 } else if vt := u.OfBashTool20250124; vt != nil {
1630 return (*string)(&vt.Type)
1631 } else if vt := u.OfTextEditor20250124; vt != nil {
1632 return (*string)(&vt.Type)
1633 } else if vt := u.OfTextEditor20250429; vt != nil {
1634 return (*string)(&vt.Type)
1635 } else if vt := u.OfWebSearchTool20250305; vt != nil {
1636 return (*string)(&vt.Type)
1637 }
1638 return nil
1639}
1640
1641// Returns a pointer to the underlying variant's CacheControl property, if present.
1642func (u MessageCountTokensToolUnionParam) GetCacheControl() *CacheControlEphemeralParam {
1643 if vt := u.OfTool; vt != nil {
1644 return &vt.CacheControl
1645 } else if vt := u.OfBashTool20250124; vt != nil {
1646 return &vt.CacheControl
1647 } else if vt := u.OfTextEditor20250124; vt != nil {
1648 return &vt.CacheControl
1649 } else if vt := u.OfTextEditor20250429; vt != nil {
1650 return &vt.CacheControl
1651 } else if vt := u.OfWebSearchTool20250305; vt != nil {
1652 return &vt.CacheControl
1653 }
1654 return nil
1655}
1656
1657// The properties Name, Type are required.
1658type MessageCountTokensToolTextEditor20250429Param struct {
1659 // Create a cache control breakpoint at this content block.
1660 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
1661 // Name of the tool.
1662 //
1663 // This is how the tool will be called by the model and in `tool_use` blocks.
1664 //
1665 // This field can be elided, and will marshal its zero value as
1666 // "str_replace_based_edit_tool".
1667 Name constant.StrReplaceBasedEditTool `json:"name,required"`
1668 // This field can be elided, and will marshal its zero value as
1669 // "text_editor_20250429".
1670 Type constant.TextEditor20250429 `json:"type,required"`
1671 paramObj
1672}
1673
1674func (r MessageCountTokensToolTextEditor20250429Param) MarshalJSON() (data []byte, err error) {
1675 type shadow MessageCountTokensToolTextEditor20250429Param
1676 return param.MarshalObject(r, (*shadow)(&r))
1677}
1678func (r *MessageCountTokensToolTextEditor20250429Param) UnmarshalJSON(data []byte) error {
1679 return apijson.UnmarshalRoot(data, r)
1680}
1681
1682type MessageDeltaUsage struct {
1683 // The cumulative number of input tokens used to create the cache entry.
1684 CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,required"`
1685 // The cumulative number of input tokens read from the cache.
1686 CacheReadInputTokens int64 `json:"cache_read_input_tokens,required"`
1687 // The cumulative number of input tokens which were used.
1688 InputTokens int64 `json:"input_tokens,required"`
1689 // The cumulative number of output tokens which were used.
1690 OutputTokens int64 `json:"output_tokens,required"`
1691 // The number of server tool requests.
1692 ServerToolUse ServerToolUsage `json:"server_tool_use,required"`
1693 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
1694 JSON struct {
1695 CacheCreationInputTokens respjson.Field
1696 CacheReadInputTokens respjson.Field
1697 InputTokens respjson.Field
1698 OutputTokens respjson.Field
1699 ServerToolUse respjson.Field
1700 ExtraFields map[string]respjson.Field
1701 raw string
1702 } `json:"-"`
1703}
1704
1705// Returns the unmodified JSON received from the API
1706func (r MessageDeltaUsage) RawJSON() string { return r.JSON.raw }
1707func (r *MessageDeltaUsage) UnmarshalJSON(data []byte) error {
1708 return apijson.UnmarshalRoot(data, r)
1709}
1710
1711// The properties Content, Role are required.
1712type MessageParam struct {
1713 Content []ContentBlockParamUnion `json:"content,omitzero,required"`
1714 // Any of "user", "assistant".
1715 Role MessageParamRole `json:"role,omitzero,required"`
1716 paramObj
1717}
1718
1719func NewUserMessage(blocks ...ContentBlockParamUnion) MessageParam {
1720 return MessageParam{
1721 Role: MessageParamRoleUser,
1722 Content: blocks,
1723 }
1724}
1725
1726func NewAssistantMessage(blocks ...ContentBlockParamUnion) MessageParam {
1727 return MessageParam{
1728 Role: MessageParamRoleAssistant,
1729 Content: blocks,
1730 }
1731}
1732
1733func (r MessageParam) MarshalJSON() (data []byte, err error) {
1734 type shadow MessageParam
1735 return param.MarshalObject(r, (*shadow)(&r))
1736}
1737func (r *MessageParam) UnmarshalJSON(data []byte) error {
1738 return apijson.UnmarshalRoot(data, r)
1739}
1740
1741type MessageParamRole string
1742
1743const (
1744 MessageParamRoleUser MessageParamRole = "user"
1745 MessageParamRoleAssistant MessageParamRole = "assistant"
1746)
1747
1748type MessageTokensCount struct {
1749 // The total number of tokens across the provided list of messages, system prompt,
1750 // and tools.
1751 InputTokens int64 `json:"input_tokens,required"`
1752 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
1753 JSON struct {
1754 InputTokens respjson.Field
1755 ExtraFields map[string]respjson.Field
1756 raw string
1757 } `json:"-"`
1758}
1759
1760// Returns the unmodified JSON received from the API
1761func (r MessageTokensCount) RawJSON() string { return r.JSON.raw }
1762func (r *MessageTokensCount) UnmarshalJSON(data []byte) error {
1763 return apijson.UnmarshalRoot(data, r)
1764}
1765
1766type MetadataParam struct {
1767 // An external identifier for the user who is associated with the request.
1768 //
1769 // This should be a uuid, hash value, or other opaque identifier. Anthropic may use
1770 // this id to help detect abuse. Do not include any identifying information such as
1771 // name, email address, or phone number.
1772 UserID param.Opt[string] `json:"user_id,omitzero"`
1773 paramObj
1774}
1775
1776func (r MetadataParam) MarshalJSON() (data []byte, err error) {
1777 type shadow MetadataParam
1778 return param.MarshalObject(r, (*shadow)(&r))
1779}
1780func (r *MetadataParam) UnmarshalJSON(data []byte) error {
1781 return apijson.UnmarshalRoot(data, r)
1782}
1783
1784// The model that will complete your prompt.\n\nSee
1785// [models](https://docs.anthropic.com/en/docs/models-overview) for additional
1786// details and options.
1787type Model string
1788
1789const (
1790 ModelClaude3_7SonnetLatest Model = "claude-3-7-sonnet-latest"
1791 ModelClaude3_7Sonnet20250219 Model = "claude-3-7-sonnet-20250219"
1792 ModelClaude3_5HaikuLatest Model = "claude-3-5-haiku-latest"
1793 ModelClaude3_5Haiku20241022 Model = "claude-3-5-haiku-20241022"
1794 ModelClaudeSonnet4_20250514 Model = "claude-sonnet-4-20250514"
1795 ModelClaudeSonnet4_0 Model = "claude-sonnet-4-0"
1796 ModelClaude4Sonnet20250514 Model = "claude-4-sonnet-20250514"
1797 ModelClaude3_5SonnetLatest Model = "claude-3-5-sonnet-latest"
1798 ModelClaude3_5Sonnet20241022 Model = "claude-3-5-sonnet-20241022"
1799 ModelClaude_3_5_Sonnet_20240620 Model = "claude-3-5-sonnet-20240620"
1800 ModelClaudeOpus4_0 Model = "claude-opus-4-0"
1801 ModelClaudeOpus4_20250514 Model = "claude-opus-4-20250514"
1802 ModelClaude4Opus20250514 Model = "claude-4-opus-20250514"
1803 ModelClaude3OpusLatest Model = "claude-3-opus-latest"
1804 ModelClaude_3_Opus_20240229 Model = "claude-3-opus-20240229"
1805 // Deprecated: Will reach end-of-life on July 21st, 2025. Please migrate to a newer
1806 // model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for
1807 // more information.
1808 ModelClaude_3_Sonnet_20240229 Model = "claude-3-sonnet-20240229"
1809 ModelClaude_3_Haiku_20240307 Model = "claude-3-haiku-20240307"
1810 // Deprecated: Will reach end-of-life on July 21st, 2025. Please migrate to a newer
1811 // model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for
1812 // more information.
1813 ModelClaude_2_1 Model = "claude-2.1"
1814 // Deprecated: Will reach end-of-life on July 21st, 2025. Please migrate to a newer
1815 // model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for
1816 // more information.
1817 ModelClaude_2_0 Model = "claude-2.0"
1818)
1819
1820// The properties Data, MediaType, Type are required.
1821type PlainTextSourceParam struct {
1822 Data string `json:"data,required"`
1823 // This field can be elided, and will marshal its zero value as "text/plain".
1824 MediaType constant.TextPlain `json:"media_type,required"`
1825 // This field can be elided, and will marshal its zero value as "text".
1826 Type constant.Text `json:"type,required"`
1827 paramObj
1828}
1829
1830func (r PlainTextSourceParam) MarshalJSON() (data []byte, err error) {
1831 type shadow PlainTextSourceParam
1832 return param.MarshalObject(r, (*shadow)(&r))
1833}
1834func (r *PlainTextSourceParam) UnmarshalJSON(data []byte) error {
1835 return apijson.UnmarshalRoot(data, r)
1836}
1837
1838// RawContentBlockDeltaUnion contains all possible properties and values from
1839// [TextDelta], [InputJSONDelta], [CitationsDelta], [ThinkingDelta],
1840// [SignatureDelta].
1841//
1842// Use the [RawContentBlockDeltaUnion.AsAny] method to switch on the variant.
1843//
1844// Use the methods beginning with 'As' to cast the union to one of its variants.
1845type RawContentBlockDeltaUnion struct {
1846 // This field is from variant [TextDelta].
1847 Text string `json:"text"`
1848 // Any of "text_delta", "input_json_delta", "citations_delta", "thinking_delta",
1849 // "signature_delta".
1850 Type string `json:"type"`
1851 // This field is from variant [InputJSONDelta].
1852 PartialJSON string `json:"partial_json"`
1853 // This field is from variant [CitationsDelta].
1854 Citation CitationsDeltaCitationUnion `json:"citation"`
1855 // This field is from variant [ThinkingDelta].
1856 Thinking string `json:"thinking"`
1857 // This field is from variant [SignatureDelta].
1858 Signature string `json:"signature"`
1859 JSON struct {
1860 Text respjson.Field
1861 Type respjson.Field
1862 PartialJSON respjson.Field
1863 Citation respjson.Field
1864 Thinking respjson.Field
1865 Signature respjson.Field
1866 raw string
1867 } `json:"-"`
1868}
1869
1870// anyRawContentBlockDelta is implemented by each variant of
1871// [RawContentBlockDeltaUnion] to add type safety for the return type of
1872// [RawContentBlockDeltaUnion.AsAny]
1873type anyRawContentBlockDelta interface {
1874 implRawContentBlockDeltaUnion()
1875}
1876
1877func (TextDelta) implRawContentBlockDeltaUnion() {}
1878func (InputJSONDelta) implRawContentBlockDeltaUnion() {}
1879func (CitationsDelta) implRawContentBlockDeltaUnion() {}
1880func (ThinkingDelta) implRawContentBlockDeltaUnion() {}
1881func (SignatureDelta) implRawContentBlockDeltaUnion() {}
1882
1883// Use the following switch statement to find the correct variant
1884//
1885// switch variant := RawContentBlockDeltaUnion.AsAny().(type) {
1886// case anthropic.TextDelta:
1887// case anthropic.InputJSONDelta:
1888// case anthropic.CitationsDelta:
1889// case anthropic.ThinkingDelta:
1890// case anthropic.SignatureDelta:
1891// default:
1892// fmt.Errorf("no variant present")
1893// }
1894func (u RawContentBlockDeltaUnion) AsAny() anyRawContentBlockDelta {
1895 switch u.Type {
1896 case "text_delta":
1897 return u.AsTextDelta()
1898 case "input_json_delta":
1899 return u.AsInputJSONDelta()
1900 case "citations_delta":
1901 return u.AsCitationsDelta()
1902 case "thinking_delta":
1903 return u.AsThinkingDelta()
1904 case "signature_delta":
1905 return u.AsSignatureDelta()
1906 }
1907 return nil
1908}
1909
1910func (u RawContentBlockDeltaUnion) AsTextDelta() (v TextDelta) {
1911 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
1912 return
1913}
1914
1915func (u RawContentBlockDeltaUnion) AsInputJSONDelta() (v InputJSONDelta) {
1916 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
1917 return
1918}
1919
1920func (u RawContentBlockDeltaUnion) AsCitationsDelta() (v CitationsDelta) {
1921 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
1922 return
1923}
1924
1925func (u RawContentBlockDeltaUnion) AsThinkingDelta() (v ThinkingDelta) {
1926 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
1927 return
1928}
1929
1930func (u RawContentBlockDeltaUnion) AsSignatureDelta() (v SignatureDelta) {
1931 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
1932 return
1933}
1934
1935// Returns the unmodified JSON received from the API
1936func (u RawContentBlockDeltaUnion) RawJSON() string { return u.JSON.raw }
1937
1938func (r *RawContentBlockDeltaUnion) UnmarshalJSON(data []byte) error {
1939 return apijson.UnmarshalRoot(data, r)
1940}
1941
1942type ContentBlockDeltaEvent struct {
1943 Delta RawContentBlockDeltaUnion `json:"delta,required"`
1944 Index int64 `json:"index,required"`
1945 Type constant.ContentBlockDelta `json:"type,required"`
1946 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
1947 JSON struct {
1948 Delta respjson.Field
1949 Index respjson.Field
1950 Type respjson.Field
1951 ExtraFields map[string]respjson.Field
1952 raw string
1953 } `json:"-"`
1954}
1955
1956// Returns the unmodified JSON received from the API
1957func (r ContentBlockDeltaEvent) RawJSON() string { return r.JSON.raw }
1958func (r *ContentBlockDeltaEvent) UnmarshalJSON(data []byte) error {
1959 return apijson.UnmarshalRoot(data, r)
1960}
1961
1962type ContentBlockStartEvent struct {
1963 ContentBlock ContentBlockStartEventContentBlockUnion `json:"content_block,required"`
1964 Index int64 `json:"index,required"`
1965 Type constant.ContentBlockStart `json:"type,required"`
1966 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
1967 JSON struct {
1968 ContentBlock respjson.Field
1969 Index respjson.Field
1970 Type respjson.Field
1971 ExtraFields map[string]respjson.Field
1972 raw string
1973 } `json:"-"`
1974}
1975
1976// Returns the unmodified JSON received from the API
1977func (r ContentBlockStartEvent) RawJSON() string { return r.JSON.raw }
1978func (r *ContentBlockStartEvent) UnmarshalJSON(data []byte) error {
1979 return apijson.UnmarshalRoot(data, r)
1980}
1981
1982// ContentBlockStartEventContentBlockUnion contains all possible properties and
1983// values from [TextBlock], [ToolUseBlock], [ServerToolUseBlock],
1984// [WebSearchToolResultBlock], [ThinkingBlock], [RedactedThinkingBlock].
1985//
1986// Use the [ContentBlockStartEventContentBlockUnion.AsAny] method to switch on the
1987// variant.
1988//
1989// Use the methods beginning with 'As' to cast the union to one of its variants.
1990type ContentBlockStartEventContentBlockUnion struct {
1991 // This field is from variant [TextBlock].
1992 Citations []TextCitationUnion `json:"citations"`
1993 // This field is from variant [TextBlock].
1994 Text string `json:"text"`
1995 // Any of "text", "tool_use", "server_tool_use", "web_search_tool_result",
1996 // "thinking", "redacted_thinking".
1997 Type string `json:"type"`
1998 ID string `json:"id"`
1999 Input any `json:"input"`
2000 Name string `json:"name"`
2001 // This field is from variant [WebSearchToolResultBlock].
2002 Content WebSearchToolResultBlockContentUnion `json:"content"`
2003 // This field is from variant [WebSearchToolResultBlock].
2004 ToolUseID string `json:"tool_use_id"`
2005 // This field is from variant [ThinkingBlock].
2006 Signature string `json:"signature"`
2007 // This field is from variant [ThinkingBlock].
2008 Thinking string `json:"thinking"`
2009 // This field is from variant [RedactedThinkingBlock].
2010 Data string `json:"data"`
2011 JSON struct {
2012 Citations respjson.Field
2013 Text respjson.Field
2014 Type respjson.Field
2015 ID respjson.Field
2016 Input respjson.Field
2017 Name respjson.Field
2018 Content respjson.Field
2019 ToolUseID respjson.Field
2020 Signature respjson.Field
2021 Thinking respjson.Field
2022 Data respjson.Field
2023 raw string
2024 } `json:"-"`
2025}
2026
2027// anyContentBlockStartEventContentBlock is implemented by each variant of
2028// [ContentBlockStartEventContentBlockUnion] to add type safety for the return type
2029// of [ContentBlockStartEventContentBlockUnion.AsAny]
2030type anyContentBlockStartEventContentBlock interface {
2031 implContentBlockStartEventContentBlockUnion()
2032}
2033
2034func (TextBlock) implContentBlockStartEventContentBlockUnion() {}
2035func (ToolUseBlock) implContentBlockStartEventContentBlockUnion() {}
2036func (ServerToolUseBlock) implContentBlockStartEventContentBlockUnion() {}
2037func (WebSearchToolResultBlock) implContentBlockStartEventContentBlockUnion() {}
2038func (ThinkingBlock) implContentBlockStartEventContentBlockUnion() {}
2039func (RedactedThinkingBlock) implContentBlockStartEventContentBlockUnion() {}
2040
2041// Use the following switch statement to find the correct variant
2042//
2043// switch variant := ContentBlockStartEventContentBlockUnion.AsAny().(type) {
2044// case anthropic.TextBlock:
2045// case anthropic.ToolUseBlock:
2046// case anthropic.ServerToolUseBlock:
2047// case anthropic.WebSearchToolResultBlock:
2048// case anthropic.ThinkingBlock:
2049// case anthropic.RedactedThinkingBlock:
2050// default:
2051// fmt.Errorf("no variant present")
2052// }
2053func (u ContentBlockStartEventContentBlockUnion) AsAny() anyContentBlockStartEventContentBlock {
2054 switch u.Type {
2055 case "text":
2056 return u.AsText()
2057 case "tool_use":
2058 return u.AsToolUse()
2059 case "server_tool_use":
2060 return u.AsServerToolUse()
2061 case "web_search_tool_result":
2062 return u.AsWebSearchToolResult()
2063 case "thinking":
2064 return u.AsThinking()
2065 case "redacted_thinking":
2066 return u.AsRedactedThinking()
2067 }
2068 return nil
2069}
2070
2071func (u ContentBlockStartEventContentBlockUnion) AsText() (v TextBlock) {
2072 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2073 return
2074}
2075
2076func (u ContentBlockStartEventContentBlockUnion) AsToolUse() (v ToolUseBlock) {
2077 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2078 return
2079}
2080
2081func (u ContentBlockStartEventContentBlockUnion) AsServerToolUse() (v ServerToolUseBlock) {
2082 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2083 return
2084}
2085
2086func (u ContentBlockStartEventContentBlockUnion) AsWebSearchToolResult() (v WebSearchToolResultBlock) {
2087 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2088 return
2089}
2090
2091func (u ContentBlockStartEventContentBlockUnion) AsThinking() (v ThinkingBlock) {
2092 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2093 return
2094}
2095
2096func (u ContentBlockStartEventContentBlockUnion) AsRedactedThinking() (v RedactedThinkingBlock) {
2097 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2098 return
2099}
2100
2101// Returns the unmodified JSON received from the API
2102func (u ContentBlockStartEventContentBlockUnion) RawJSON() string { return u.JSON.raw }
2103
2104func (r *ContentBlockStartEventContentBlockUnion) UnmarshalJSON(data []byte) error {
2105 return apijson.UnmarshalRoot(data, r)
2106}
2107
2108type ContentBlockStopEvent struct {
2109 Index int64 `json:"index,required"`
2110 Type constant.ContentBlockStop `json:"type,required"`
2111 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2112 JSON struct {
2113 Index respjson.Field
2114 Type respjson.Field
2115 ExtraFields map[string]respjson.Field
2116 raw string
2117 } `json:"-"`
2118}
2119
2120// Returns the unmodified JSON received from the API
2121func (r ContentBlockStopEvent) RawJSON() string { return r.JSON.raw }
2122func (r *ContentBlockStopEvent) UnmarshalJSON(data []byte) error {
2123 return apijson.UnmarshalRoot(data, r)
2124}
2125
2126type MessageDeltaEvent struct {
2127 Delta MessageDeltaEventDelta `json:"delta,required"`
2128 Type constant.MessageDelta `json:"type,required"`
2129 // Billing and rate-limit usage.
2130 //
2131 // Anthropic's API bills and rate-limits by token counts, as tokens represent the
2132 // underlying cost to our systems.
2133 //
2134 // Under the hood, the API transforms requests into a format suitable for the
2135 // model. The model's output then goes through a parsing stage before becoming an
2136 // API response. As a result, the token counts in `usage` will not match one-to-one
2137 // with the exact visible content of an API request or response.
2138 //
2139 // For example, `output_tokens` will be non-zero, even for an empty string response
2140 // from Claude.
2141 //
2142 // Total input tokens in a request is the summation of `input_tokens`,
2143 // `cache_creation_input_tokens`, and `cache_read_input_tokens`.
2144 Usage MessageDeltaUsage `json:"usage,required"`
2145 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2146 JSON struct {
2147 Delta respjson.Field
2148 Type respjson.Field
2149 Usage respjson.Field
2150 ExtraFields map[string]respjson.Field
2151 raw string
2152 } `json:"-"`
2153}
2154
2155// Returns the unmodified JSON received from the API
2156func (r MessageDeltaEvent) RawJSON() string { return r.JSON.raw }
2157func (r *MessageDeltaEvent) UnmarshalJSON(data []byte) error {
2158 return apijson.UnmarshalRoot(data, r)
2159}
2160
2161type MessageDeltaEventDelta struct {
2162 // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn",
2163 // "refusal".
2164 StopReason StopReason `json:"stop_reason,required"`
2165 StopSequence string `json:"stop_sequence,required"`
2166 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2167 JSON struct {
2168 StopReason respjson.Field
2169 StopSequence respjson.Field
2170 ExtraFields map[string]respjson.Field
2171 raw string
2172 } `json:"-"`
2173}
2174
2175// Returns the unmodified JSON received from the API
2176func (r MessageDeltaEventDelta) RawJSON() string { return r.JSON.raw }
2177func (r *MessageDeltaEventDelta) UnmarshalJSON(data []byte) error {
2178 return apijson.UnmarshalRoot(data, r)
2179}
2180
2181type MessageStartEvent struct {
2182 Message Message `json:"message,required"`
2183 Type constant.MessageStart `json:"type,required"`
2184 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2185 JSON struct {
2186 Message respjson.Field
2187 Type respjson.Field
2188 ExtraFields map[string]respjson.Field
2189 raw string
2190 } `json:"-"`
2191}
2192
2193// Returns the unmodified JSON received from the API
2194func (r MessageStartEvent) RawJSON() string { return r.JSON.raw }
2195func (r *MessageStartEvent) UnmarshalJSON(data []byte) error {
2196 return apijson.UnmarshalRoot(data, r)
2197}
2198
2199type MessageStopEvent struct {
2200 Type constant.MessageStop `json:"type,required"`
2201 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2202 JSON struct {
2203 Type respjson.Field
2204 ExtraFields map[string]respjson.Field
2205 raw string
2206 } `json:"-"`
2207}
2208
2209// Returns the unmodified JSON received from the API
2210func (r MessageStopEvent) RawJSON() string { return r.JSON.raw }
2211func (r *MessageStopEvent) UnmarshalJSON(data []byte) error {
2212 return apijson.UnmarshalRoot(data, r)
2213}
2214
2215// MessageStreamEventUnion contains all possible properties and values from
2216// [MessageStartEvent], [MessageDeltaEvent], [MessageStopEvent],
2217// [ContentBlockStartEvent], [ContentBlockDeltaEvent], [ContentBlockStopEvent].
2218//
2219// Use the [MessageStreamEventUnion.AsAny] method to switch on the variant.
2220//
2221// Use the methods beginning with 'As' to cast the union to one of its variants.
2222type MessageStreamEventUnion struct {
2223 // This field is from variant [MessageStartEvent].
2224 Message Message `json:"message"`
2225 // Any of "message_start", "message_delta", "message_stop", "content_block_start",
2226 // "content_block_delta", "content_block_stop".
2227 Type string `json:"type"`
2228 // This field is a union of [MessageDeltaEventDelta], [RawContentBlockDeltaUnion]
2229 Delta MessageStreamEventUnionDelta `json:"delta"`
2230 // This field is from variant [MessageDeltaEvent].
2231 Usage MessageDeltaUsage `json:"usage"`
2232 // This field is from variant [ContentBlockStartEvent].
2233 ContentBlock ContentBlockStartEventContentBlockUnion `json:"content_block"`
2234 Index int64 `json:"index"`
2235 JSON struct {
2236 Message respjson.Field
2237 Type respjson.Field
2238 Delta respjson.Field
2239 Usage respjson.Field
2240 ContentBlock respjson.Field
2241 Index respjson.Field
2242 raw string
2243 } `json:"-"`
2244}
2245
2246// anyMessageStreamEvent is implemented by each variant of
2247// [MessageStreamEventUnion] to add type safety for the return type of
2248// [MessageStreamEventUnion.AsAny]
2249type anyMessageStreamEvent interface {
2250 implMessageStreamEventUnion()
2251}
2252
2253func (MessageStartEvent) implMessageStreamEventUnion() {}
2254func (MessageDeltaEvent) implMessageStreamEventUnion() {}
2255func (MessageStopEvent) implMessageStreamEventUnion() {}
2256func (ContentBlockStartEvent) implMessageStreamEventUnion() {}
2257func (ContentBlockDeltaEvent) implMessageStreamEventUnion() {}
2258func (ContentBlockStopEvent) implMessageStreamEventUnion() {}
2259
2260// Use the following switch statement to find the correct variant
2261//
2262// switch variant := MessageStreamEventUnion.AsAny().(type) {
2263// case anthropic.MessageStartEvent:
2264// case anthropic.MessageDeltaEvent:
2265// case anthropic.MessageStopEvent:
2266// case anthropic.ContentBlockStartEvent:
2267// case anthropic.ContentBlockDeltaEvent:
2268// case anthropic.ContentBlockStopEvent:
2269// default:
2270// fmt.Errorf("no variant present")
2271// }
2272func (u MessageStreamEventUnion) AsAny() anyMessageStreamEvent {
2273 switch u.Type {
2274 case "message_start":
2275 return u.AsMessageStart()
2276 case "message_delta":
2277 return u.AsMessageDelta()
2278 case "message_stop":
2279 return u.AsMessageStop()
2280 case "content_block_start":
2281 return u.AsContentBlockStart()
2282 case "content_block_delta":
2283 return u.AsContentBlockDelta()
2284 case "content_block_stop":
2285 return u.AsContentBlockStop()
2286 }
2287 return nil
2288}
2289
2290func (u MessageStreamEventUnion) AsMessageStart() (v MessageStartEvent) {
2291 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2292 return
2293}
2294
2295func (u MessageStreamEventUnion) AsMessageDelta() (v MessageDeltaEvent) {
2296 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2297 return
2298}
2299
2300func (u MessageStreamEventUnion) AsMessageStop() (v MessageStopEvent) {
2301 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2302 return
2303}
2304
2305func (u MessageStreamEventUnion) AsContentBlockStart() (v ContentBlockStartEvent) {
2306 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2307 return
2308}
2309
2310func (u MessageStreamEventUnion) AsContentBlockDelta() (v ContentBlockDeltaEvent) {
2311 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2312 return
2313}
2314
2315func (u MessageStreamEventUnion) AsContentBlockStop() (v ContentBlockStopEvent) {
2316 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2317 return
2318}
2319
2320// Returns the unmodified JSON received from the API
2321func (u MessageStreamEventUnion) RawJSON() string { return u.JSON.raw }
2322
2323func (r *MessageStreamEventUnion) UnmarshalJSON(data []byte) error {
2324 return apijson.UnmarshalRoot(data, r)
2325}
2326
2327// MessageStreamEventUnionDelta is an implicit subunion of
2328// [MessageStreamEventUnion]. MessageStreamEventUnionDelta provides convenient
2329// access to the sub-properties of the union.
2330//
2331// For type safety it is recommended to directly use a variant of the
2332// [MessageStreamEventUnion].
2333type MessageStreamEventUnionDelta struct {
2334 // This field is from variant [MessageDeltaEventDelta].
2335 StopReason StopReason `json:"stop_reason"`
2336 // This field is from variant [MessageDeltaEventDelta].
2337 StopSequence string `json:"stop_sequence"`
2338 // This field is from variant [RawContentBlockDeltaUnion].
2339 Text string `json:"text"`
2340 Type string `json:"type"`
2341 // This field is from variant [RawContentBlockDeltaUnion].
2342 PartialJSON string `json:"partial_json"`
2343 // This field is from variant [RawContentBlockDeltaUnion].
2344 Citation CitationsDeltaCitationUnion `json:"citation"`
2345 // This field is from variant [RawContentBlockDeltaUnion].
2346 Thinking string `json:"thinking"`
2347 // This field is from variant [RawContentBlockDeltaUnion].
2348 Signature string `json:"signature"`
2349 JSON struct {
2350 StopReason respjson.Field
2351 StopSequence respjson.Field
2352 Text respjson.Field
2353 Type respjson.Field
2354 PartialJSON respjson.Field
2355 Citation respjson.Field
2356 Thinking respjson.Field
2357 Signature respjson.Field
2358 raw string
2359 } `json:"-"`
2360}
2361
2362func (r *MessageStreamEventUnionDelta) UnmarshalJSON(data []byte) error {
2363 return apijson.UnmarshalRoot(data, r)
2364}
2365
2366// Accumulate builds up the Message incrementally from a MessageStreamEvent. The Message then can be used as
2367// any other Message, except with the caveat that the Message.JSON field which normally can be used to inspect
2368// the JSON sent over the network may not be populated fully.
2369//
2370// message := anthropic.Message{}
2371// for stream.Next() {
2372// event := stream.Current()
2373// message.Accumulate(event)
2374// }
2375func (acc *Message) Accumulate(event MessageStreamEventUnion) error {
2376 if acc == nil {
2377 return fmt.Errorf("accumulate: cannot accumlate into nil Message")
2378 }
2379
2380 switch event := event.AsAny().(type) {
2381 case MessageStartEvent:
2382 *acc = event.Message
2383 case MessageDeltaEvent:
2384 acc.StopReason = event.Delta.StopReason
2385 acc.StopSequence = event.Delta.StopSequence
2386 acc.Usage.OutputTokens = event.Usage.OutputTokens
2387 case MessageStopEvent:
2388 accJson, err := json.Marshal(acc)
2389 if err != nil {
2390 return fmt.Errorf("error converting content block to JSON: %w", err)
2391 }
2392 acc.JSON.raw = string(accJson)
2393 case ContentBlockStartEvent:
2394 acc.Content = append(acc.Content, ContentBlockUnion{})
2395 err := acc.Content[len(acc.Content)-1].UnmarshalJSON([]byte(event.ContentBlock.RawJSON()))
2396 if err != nil {
2397 return err
2398 }
2399 case ContentBlockDeltaEvent:
2400 if len(acc.Content) == 0 {
2401 return fmt.Errorf("received event of type %s but there was no content block", event.Type)
2402 }
2403 cb := &acc.Content[len(acc.Content)-1]
2404 switch delta := event.Delta.AsAny().(type) {
2405 case TextDelta:
2406 cb.Text += delta.Text
2407 case InputJSONDelta:
2408 if len(delta.PartialJSON) != 0 {
2409 if string(cb.Input) == "{}" {
2410 cb.Input = []byte(delta.PartialJSON)
2411 } else {
2412 cb.Input = append(cb.Input, []byte(delta.PartialJSON)...)
2413 }
2414 }
2415 case ThinkingDelta:
2416 cb.Thinking += delta.Thinking
2417 case SignatureDelta:
2418 cb.Signature += delta.Signature
2419 case CitationsDelta:
2420 citation := TextCitationUnion{}
2421 err := citation.UnmarshalJSON([]byte(delta.Citation.RawJSON()))
2422 if err != nil {
2423 return fmt.Errorf("could not unmarshal citation delta into citation type: %w", err)
2424 }
2425 cb.Citations = append(cb.Citations, citation)
2426 }
2427 case ContentBlockStopEvent:
2428 if len(acc.Content) == 0 {
2429 return fmt.Errorf("received event of type %s but there was no content block", event.Type)
2430 }
2431 contentBlock := &acc.Content[len(acc.Content)-1]
2432 cbJson, err := json.Marshal(contentBlock)
2433 if err != nil {
2434 return fmt.Errorf("error converting content block to JSON: %w", err)
2435 }
2436 contentBlock.JSON.raw = string(cbJson)
2437 }
2438
2439 return nil
2440}
2441
2442type RedactedThinkingBlock struct {
2443 Data string `json:"data,required"`
2444 Type constant.RedactedThinking `json:"type,required"`
2445 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2446 JSON struct {
2447 Data respjson.Field
2448 Type respjson.Field
2449 ExtraFields map[string]respjson.Field
2450 raw string
2451 } `json:"-"`
2452}
2453
2454// Returns the unmodified JSON received from the API
2455func (r RedactedThinkingBlock) RawJSON() string { return r.JSON.raw }
2456func (r *RedactedThinkingBlock) UnmarshalJSON(data []byte) error {
2457 return apijson.UnmarshalRoot(data, r)
2458}
2459
2460func (r RedactedThinkingBlock) ToParam() RedactedThinkingBlockParam {
2461 var p RedactedThinkingBlockParam
2462 p.Type = r.Type
2463 p.Data = r.Data
2464 return p
2465}
2466
2467// The properties Data, Type are required.
2468type RedactedThinkingBlockParam struct {
2469 Data string `json:"data,required"`
2470 // This field can be elided, and will marshal its zero value as
2471 // "redacted_thinking".
2472 Type constant.RedactedThinking `json:"type,required"`
2473 paramObj
2474}
2475
2476func (r RedactedThinkingBlockParam) MarshalJSON() (data []byte, err error) {
2477 type shadow RedactedThinkingBlockParam
2478 return param.MarshalObject(r, (*shadow)(&r))
2479}
2480func (r *RedactedThinkingBlockParam) UnmarshalJSON(data []byte) error {
2481 return apijson.UnmarshalRoot(data, r)
2482}
2483
2484type ServerToolUsage struct {
2485 // The number of web search tool requests.
2486 WebSearchRequests int64 `json:"web_search_requests,required"`
2487 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2488 JSON struct {
2489 WebSearchRequests respjson.Field
2490 ExtraFields map[string]respjson.Field
2491 raw string
2492 } `json:"-"`
2493}
2494
2495// Returns the unmodified JSON received from the API
2496func (r ServerToolUsage) RawJSON() string { return r.JSON.raw }
2497func (r *ServerToolUsage) UnmarshalJSON(data []byte) error {
2498 return apijson.UnmarshalRoot(data, r)
2499}
2500
2501type ServerToolUseBlock struct {
2502 ID string `json:"id,required"`
2503 Input any `json:"input,required"`
2504 Name constant.WebSearch `json:"name,required"`
2505 Type constant.ServerToolUse `json:"type,required"`
2506 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2507 JSON struct {
2508 ID respjson.Field
2509 Input respjson.Field
2510 Name respjson.Field
2511 Type respjson.Field
2512 ExtraFields map[string]respjson.Field
2513 raw string
2514 } `json:"-"`
2515}
2516
2517// Returns the unmodified JSON received from the API
2518func (r ServerToolUseBlock) RawJSON() string { return r.JSON.raw }
2519func (r *ServerToolUseBlock) UnmarshalJSON(data []byte) error {
2520 return apijson.UnmarshalRoot(data, r)
2521}
2522
2523// The properties ID, Input, Name, Type are required.
2524type ServerToolUseBlockParam struct {
2525 ID string `json:"id,required"`
2526 Input any `json:"input,omitzero,required"`
2527 // Create a cache control breakpoint at this content block.
2528 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
2529 // This field can be elided, and will marshal its zero value as "web_search".
2530 Name constant.WebSearch `json:"name,required"`
2531 // This field can be elided, and will marshal its zero value as "server_tool_use".
2532 Type constant.ServerToolUse `json:"type,required"`
2533 paramObj
2534}
2535
2536func (r ServerToolUseBlockParam) MarshalJSON() (data []byte, err error) {
2537 type shadow ServerToolUseBlockParam
2538 return param.MarshalObject(r, (*shadow)(&r))
2539}
2540func (r *ServerToolUseBlockParam) UnmarshalJSON(data []byte) error {
2541 return apijson.UnmarshalRoot(data, r)
2542}
2543
2544type SignatureDelta struct {
2545 Signature string `json:"signature,required"`
2546 Type constant.SignatureDelta `json:"type,required"`
2547 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2548 JSON struct {
2549 Signature respjson.Field
2550 Type respjson.Field
2551 ExtraFields map[string]respjson.Field
2552 raw string
2553 } `json:"-"`
2554}
2555
2556// Returns the unmodified JSON received from the API
2557func (r SignatureDelta) RawJSON() string { return r.JSON.raw }
2558func (r *SignatureDelta) UnmarshalJSON(data []byte) error {
2559 return apijson.UnmarshalRoot(data, r)
2560}
2561
2562type StopReason string
2563
2564const (
2565 StopReasonEndTurn StopReason = "end_turn"
2566 StopReasonMaxTokens StopReason = "max_tokens"
2567 StopReasonStopSequence StopReason = "stop_sequence"
2568 StopReasonToolUse StopReason = "tool_use"
2569 StopReasonPauseTurn StopReason = "pause_turn"
2570 StopReasonRefusal StopReason = "refusal"
2571)
2572
2573type TextBlock struct {
2574 // Citations supporting the text block.
2575 //
2576 // The type of citation returned will depend on the type of document being cited.
2577 // Citing a PDF results in `page_location`, plain text results in `char_location`,
2578 // and content document results in `content_block_location`.
2579 Citations []TextCitationUnion `json:"citations,required"`
2580 Text string `json:"text,required"`
2581 Type constant.Text `json:"type,required"`
2582 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2583 JSON struct {
2584 Citations respjson.Field
2585 Text respjson.Field
2586 Type respjson.Field
2587 ExtraFields map[string]respjson.Field
2588 raw string
2589 } `json:"-"`
2590}
2591
2592// Returns the unmodified JSON received from the API
2593func (r TextBlock) RawJSON() string { return r.JSON.raw }
2594func (r *TextBlock) UnmarshalJSON(data []byte) error {
2595 return apijson.UnmarshalRoot(data, r)
2596}
2597
2598func (r TextBlock) ToParam() TextBlockParam {
2599 var p TextBlockParam
2600 p.Type = r.Type
2601 p.Text = r.Text
2602
2603 // Distinguish between a nil and zero length slice, since some compatible
2604 // APIs may not require citations.
2605 if r.Citations != nil {
2606 p.Citations = make([]TextCitationParamUnion, len(r.Citations))
2607 }
2608
2609 for i, citation := range r.Citations {
2610 switch citationVariant := citation.AsAny().(type) {
2611 case CitationCharLocation:
2612 var citationParam CitationCharLocationParam
2613 citationParam.Type = citationVariant.Type
2614 citationParam.DocumentTitle = paramutil.ToOpt(citationVariant.DocumentTitle, citationVariant.JSON.DocumentTitle)
2615 citationParam.CitedText = citationVariant.CitedText
2616 citationParam.DocumentIndex = citationVariant.DocumentIndex
2617 citationParam.EndCharIndex = citationVariant.EndCharIndex
2618 citationParam.StartCharIndex = citationVariant.StartCharIndex
2619 p.Citations[i] = TextCitationParamUnion{OfCharLocation: &citationParam}
2620 case CitationPageLocation:
2621 var citationParam CitationPageLocationParam
2622 citationParam.Type = citationVariant.Type
2623 citationParam.DocumentTitle = paramutil.ToOpt(citationVariant.DocumentTitle, citationVariant.JSON.DocumentTitle)
2624 citationParam.DocumentIndex = citationVariant.DocumentIndex
2625 citationParam.EndPageNumber = citationVariant.EndPageNumber
2626 citationParam.StartPageNumber = citationVariant.StartPageNumber
2627 p.Citations[i] = TextCitationParamUnion{OfPageLocation: &citationParam}
2628 case CitationContentBlockLocation:
2629 var citationParam CitationContentBlockLocationParam
2630 citationParam.Type = citationVariant.Type
2631 citationParam.DocumentTitle = paramutil.ToOpt(citationVariant.DocumentTitle, citationVariant.JSON.DocumentTitle)
2632 citationParam.CitedText = citationVariant.CitedText
2633 citationParam.DocumentIndex = citationVariant.DocumentIndex
2634 citationParam.EndBlockIndex = citationVariant.EndBlockIndex
2635 citationParam.StartBlockIndex = citationVariant.StartBlockIndex
2636 p.Citations[i] = TextCitationParamUnion{OfContentBlockLocation: &citationParam}
2637 }
2638 }
2639 return p
2640}
2641
2642// The properties Text, Type are required.
2643type TextBlockParam struct {
2644 Text string `json:"text,required"`
2645 Citations []TextCitationParamUnion `json:"citations,omitzero"`
2646 // Create a cache control breakpoint at this content block.
2647 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
2648 // This field can be elided, and will marshal its zero value as "text".
2649 Type constant.Text `json:"type,required"`
2650 paramObj
2651}
2652
2653func (r TextBlockParam) MarshalJSON() (data []byte, err error) {
2654 type shadow TextBlockParam
2655 return param.MarshalObject(r, (*shadow)(&r))
2656}
2657func (r *TextBlockParam) UnmarshalJSON(data []byte) error {
2658 return apijson.UnmarshalRoot(data, r)
2659}
2660
2661// TextCitationUnion contains all possible properties and values from
2662// [CitationCharLocation], [CitationPageLocation], [CitationContentBlockLocation],
2663// [CitationsWebSearchResultLocation].
2664//
2665// Use the [TextCitationUnion.AsAny] method to switch on the variant.
2666//
2667// Use the methods beginning with 'As' to cast the union to one of its variants.
2668type TextCitationUnion struct {
2669 CitedText string `json:"cited_text"`
2670 DocumentIndex int64 `json:"document_index"`
2671 DocumentTitle string `json:"document_title"`
2672 // This field is from variant [CitationCharLocation].
2673 EndCharIndex int64 `json:"end_char_index"`
2674 // This field is from variant [CitationCharLocation].
2675 StartCharIndex int64 `json:"start_char_index"`
2676 // Any of "char_location", "page_location", "content_block_location",
2677 // "web_search_result_location".
2678 Type string `json:"type"`
2679 // This field is from variant [CitationPageLocation].
2680 EndPageNumber int64 `json:"end_page_number"`
2681 // This field is from variant [CitationPageLocation].
2682 StartPageNumber int64 `json:"start_page_number"`
2683 // This field is from variant [CitationContentBlockLocation].
2684 EndBlockIndex int64 `json:"end_block_index"`
2685 // This field is from variant [CitationContentBlockLocation].
2686 StartBlockIndex int64 `json:"start_block_index"`
2687 // This field is from variant [CitationsWebSearchResultLocation].
2688 EncryptedIndex string `json:"encrypted_index"`
2689 // This field is from variant [CitationsWebSearchResultLocation].
2690 Title string `json:"title"`
2691 // This field is from variant [CitationsWebSearchResultLocation].
2692 URL string `json:"url"`
2693 JSON struct {
2694 CitedText respjson.Field
2695 DocumentIndex respjson.Field
2696 DocumentTitle respjson.Field
2697 EndCharIndex respjson.Field
2698 StartCharIndex respjson.Field
2699 Type respjson.Field
2700 EndPageNumber respjson.Field
2701 StartPageNumber respjson.Field
2702 EndBlockIndex respjson.Field
2703 StartBlockIndex respjson.Field
2704 EncryptedIndex respjson.Field
2705 Title respjson.Field
2706 URL respjson.Field
2707 raw string
2708 } `json:"-"`
2709}
2710
2711// anyTextCitation is implemented by each variant of [TextCitationUnion] to add
2712// type safety for the return type of [TextCitationUnion.AsAny]
2713type anyTextCitation interface {
2714 implTextCitationUnion()
2715}
2716
2717func (CitationCharLocation) implTextCitationUnion() {}
2718func (CitationPageLocation) implTextCitationUnion() {}
2719func (CitationContentBlockLocation) implTextCitationUnion() {}
2720func (CitationsWebSearchResultLocation) implTextCitationUnion() {}
2721
2722// Use the following switch statement to find the correct variant
2723//
2724// switch variant := TextCitationUnion.AsAny().(type) {
2725// case anthropic.CitationCharLocation:
2726// case anthropic.CitationPageLocation:
2727// case anthropic.CitationContentBlockLocation:
2728// case anthropic.CitationsWebSearchResultLocation:
2729// default:
2730// fmt.Errorf("no variant present")
2731// }
2732func (u TextCitationUnion) AsAny() anyTextCitation {
2733 switch u.Type {
2734 case "char_location":
2735 return u.AsCharLocation()
2736 case "page_location":
2737 return u.AsPageLocation()
2738 case "content_block_location":
2739 return u.AsContentBlockLocation()
2740 case "web_search_result_location":
2741 return u.AsWebSearchResultLocation()
2742 }
2743 return nil
2744}
2745
2746func (u TextCitationUnion) AsCharLocation() (v CitationCharLocation) {
2747 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2748 return
2749}
2750
2751func (u TextCitationUnion) AsPageLocation() (v CitationPageLocation) {
2752 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2753 return
2754}
2755
2756func (u TextCitationUnion) AsContentBlockLocation() (v CitationContentBlockLocation) {
2757 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2758 return
2759}
2760
2761func (u TextCitationUnion) AsWebSearchResultLocation() (v CitationsWebSearchResultLocation) {
2762 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
2763 return
2764}
2765
2766// Returns the unmodified JSON received from the API
2767func (u TextCitationUnion) RawJSON() string { return u.JSON.raw }
2768
2769func (r *TextCitationUnion) UnmarshalJSON(data []byte) error {
2770 return apijson.UnmarshalRoot(data, r)
2771}
2772
2773// Only one field can be non-zero.
2774//
2775// Use [param.IsOmitted] to confirm if a field is set.
2776type TextCitationParamUnion struct {
2777 OfCharLocation *CitationCharLocationParam `json:",omitzero,inline"`
2778 OfPageLocation *CitationPageLocationParam `json:",omitzero,inline"`
2779 OfContentBlockLocation *CitationContentBlockLocationParam `json:",omitzero,inline"`
2780 OfWebSearchResultLocation *CitationWebSearchResultLocationParam `json:",omitzero,inline"`
2781 paramUnion
2782}
2783
2784func (u TextCitationParamUnion) MarshalJSON() ([]byte, error) {
2785 return param.MarshalUnion(u, u.OfCharLocation, u.OfPageLocation, u.OfContentBlockLocation, u.OfWebSearchResultLocation)
2786}
2787func (u *TextCitationParamUnion) UnmarshalJSON(data []byte) error {
2788 return apijson.UnmarshalRoot(data, u)
2789}
2790
2791func (u *TextCitationParamUnion) asAny() any {
2792 if !param.IsOmitted(u.OfCharLocation) {
2793 return u.OfCharLocation
2794 } else if !param.IsOmitted(u.OfPageLocation) {
2795 return u.OfPageLocation
2796 } else if !param.IsOmitted(u.OfContentBlockLocation) {
2797 return u.OfContentBlockLocation
2798 } else if !param.IsOmitted(u.OfWebSearchResultLocation) {
2799 return u.OfWebSearchResultLocation
2800 }
2801 return nil
2802}
2803
2804// Returns a pointer to the underlying variant's property, if present.
2805func (u TextCitationParamUnion) GetEndCharIndex() *int64 {
2806 if vt := u.OfCharLocation; vt != nil {
2807 return &vt.EndCharIndex
2808 }
2809 return nil
2810}
2811
2812// Returns a pointer to the underlying variant's property, if present.
2813func (u TextCitationParamUnion) GetStartCharIndex() *int64 {
2814 if vt := u.OfCharLocation; vt != nil {
2815 return &vt.StartCharIndex
2816 }
2817 return nil
2818}
2819
2820// Returns a pointer to the underlying variant's property, if present.
2821func (u TextCitationParamUnion) GetEndPageNumber() *int64 {
2822 if vt := u.OfPageLocation; vt != nil {
2823 return &vt.EndPageNumber
2824 }
2825 return nil
2826}
2827
2828// Returns a pointer to the underlying variant's property, if present.
2829func (u TextCitationParamUnion) GetStartPageNumber() *int64 {
2830 if vt := u.OfPageLocation; vt != nil {
2831 return &vt.StartPageNumber
2832 }
2833 return nil
2834}
2835
2836// Returns a pointer to the underlying variant's property, if present.
2837func (u TextCitationParamUnion) GetEndBlockIndex() *int64 {
2838 if vt := u.OfContentBlockLocation; vt != nil {
2839 return &vt.EndBlockIndex
2840 }
2841 return nil
2842}
2843
2844// Returns a pointer to the underlying variant's property, if present.
2845func (u TextCitationParamUnion) GetStartBlockIndex() *int64 {
2846 if vt := u.OfContentBlockLocation; vt != nil {
2847 return &vt.StartBlockIndex
2848 }
2849 return nil
2850}
2851
2852// Returns a pointer to the underlying variant's property, if present.
2853func (u TextCitationParamUnion) GetEncryptedIndex() *string {
2854 if vt := u.OfWebSearchResultLocation; vt != nil {
2855 return &vt.EncryptedIndex
2856 }
2857 return nil
2858}
2859
2860// Returns a pointer to the underlying variant's property, if present.
2861func (u TextCitationParamUnion) GetTitle() *string {
2862 if vt := u.OfWebSearchResultLocation; vt != nil && vt.Title.Valid() {
2863 return &vt.Title.Value
2864 }
2865 return nil
2866}
2867
2868// Returns a pointer to the underlying variant's property, if present.
2869func (u TextCitationParamUnion) GetURL() *string {
2870 if vt := u.OfWebSearchResultLocation; vt != nil {
2871 return &vt.URL
2872 }
2873 return nil
2874}
2875
2876// Returns a pointer to the underlying variant's property, if present.
2877func (u TextCitationParamUnion) GetCitedText() *string {
2878 if vt := u.OfCharLocation; vt != nil {
2879 return (*string)(&vt.CitedText)
2880 } else if vt := u.OfPageLocation; vt != nil {
2881 return (*string)(&vt.CitedText)
2882 } else if vt := u.OfContentBlockLocation; vt != nil {
2883 return (*string)(&vt.CitedText)
2884 } else if vt := u.OfWebSearchResultLocation; vt != nil {
2885 return (*string)(&vt.CitedText)
2886 }
2887 return nil
2888}
2889
2890// Returns a pointer to the underlying variant's property, if present.
2891func (u TextCitationParamUnion) GetDocumentIndex() *int64 {
2892 if vt := u.OfCharLocation; vt != nil {
2893 return (*int64)(&vt.DocumentIndex)
2894 } else if vt := u.OfPageLocation; vt != nil {
2895 return (*int64)(&vt.DocumentIndex)
2896 } else if vt := u.OfContentBlockLocation; vt != nil {
2897 return (*int64)(&vt.DocumentIndex)
2898 }
2899 return nil
2900}
2901
2902// Returns a pointer to the underlying variant's property, if present.
2903func (u TextCitationParamUnion) GetDocumentTitle() *string {
2904 if vt := u.OfCharLocation; vt != nil && vt.DocumentTitle.Valid() {
2905 return &vt.DocumentTitle.Value
2906 } else if vt := u.OfPageLocation; vt != nil && vt.DocumentTitle.Valid() {
2907 return &vt.DocumentTitle.Value
2908 } else if vt := u.OfContentBlockLocation; vt != nil && vt.DocumentTitle.Valid() {
2909 return &vt.DocumentTitle.Value
2910 }
2911 return nil
2912}
2913
2914// Returns a pointer to the underlying variant's property, if present.
2915func (u TextCitationParamUnion) GetType() *string {
2916 if vt := u.OfCharLocation; vt != nil {
2917 return (*string)(&vt.Type)
2918 } else if vt := u.OfPageLocation; vt != nil {
2919 return (*string)(&vt.Type)
2920 } else if vt := u.OfContentBlockLocation; vt != nil {
2921 return (*string)(&vt.Type)
2922 } else if vt := u.OfWebSearchResultLocation; vt != nil {
2923 return (*string)(&vt.Type)
2924 }
2925 return nil
2926}
2927
2928type TextDelta struct {
2929 Text string `json:"text,required"`
2930 Type constant.TextDelta `json:"type,required"`
2931 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2932 JSON struct {
2933 Text respjson.Field
2934 Type respjson.Field
2935 ExtraFields map[string]respjson.Field
2936 raw string
2937 } `json:"-"`
2938}
2939
2940// Returns the unmodified JSON received from the API
2941func (r TextDelta) RawJSON() string { return r.JSON.raw }
2942func (r *TextDelta) UnmarshalJSON(data []byte) error {
2943 return apijson.UnmarshalRoot(data, r)
2944}
2945
2946type ThinkingBlock struct {
2947 Signature string `json:"signature,required"`
2948 Thinking string `json:"thinking,required"`
2949 Type constant.Thinking `json:"type,required"`
2950 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
2951 JSON struct {
2952 Signature respjson.Field
2953 Thinking respjson.Field
2954 Type respjson.Field
2955 ExtraFields map[string]respjson.Field
2956 raw string
2957 } `json:"-"`
2958}
2959
2960// Returns the unmodified JSON received from the API
2961func (r ThinkingBlock) RawJSON() string { return r.JSON.raw }
2962func (r *ThinkingBlock) UnmarshalJSON(data []byte) error {
2963 return apijson.UnmarshalRoot(data, r)
2964}
2965
2966func (r ThinkingBlock) ToParam() ThinkingBlockParam {
2967 var p ThinkingBlockParam
2968 p.Type = r.Type
2969 p.Signature = r.Signature
2970 p.Thinking = r.Thinking
2971 return p
2972}
2973
2974// The properties Signature, Thinking, Type are required.
2975type ThinkingBlockParam struct {
2976 Signature string `json:"signature,required"`
2977 Thinking string `json:"thinking,required"`
2978 // This field can be elided, and will marshal its zero value as "thinking".
2979 Type constant.Thinking `json:"type,required"`
2980 paramObj
2981}
2982
2983func (r ThinkingBlockParam) MarshalJSON() (data []byte, err error) {
2984 type shadow ThinkingBlockParam
2985 return param.MarshalObject(r, (*shadow)(&r))
2986}
2987func (r *ThinkingBlockParam) UnmarshalJSON(data []byte) error {
2988 return apijson.UnmarshalRoot(data, r)
2989}
2990
2991func NewThinkingConfigDisabledParam() ThinkingConfigDisabledParam {
2992 return ThinkingConfigDisabledParam{
2993 Type: "disabled",
2994 }
2995}
2996
2997// This struct has a constant value, construct it with
2998// [NewThinkingConfigDisabledParam].
2999type ThinkingConfigDisabledParam struct {
3000 Type constant.Disabled `json:"type,required"`
3001 paramObj
3002}
3003
3004func (r ThinkingConfigDisabledParam) MarshalJSON() (data []byte, err error) {
3005 type shadow ThinkingConfigDisabledParam
3006 return param.MarshalObject(r, (*shadow)(&r))
3007}
3008func (r *ThinkingConfigDisabledParam) UnmarshalJSON(data []byte) error {
3009 return apijson.UnmarshalRoot(data, r)
3010}
3011
3012// The properties BudgetTokens, Type are required.
3013type ThinkingConfigEnabledParam struct {
3014 // Determines how many tokens Claude can use for its internal reasoning process.
3015 // Larger budgets can enable more thorough analysis for complex problems, improving
3016 // response quality.
3017 //
3018 // Must be ≥1024 and less than `max_tokens`.
3019 //
3020 // See
3021 // [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)
3022 // for details.
3023 BudgetTokens int64 `json:"budget_tokens,required"`
3024 // This field can be elided, and will marshal its zero value as "enabled".
3025 Type constant.Enabled `json:"type,required"`
3026 paramObj
3027}
3028
3029func (r ThinkingConfigEnabledParam) MarshalJSON() (data []byte, err error) {
3030 type shadow ThinkingConfigEnabledParam
3031 return param.MarshalObject(r, (*shadow)(&r))
3032}
3033func (r *ThinkingConfigEnabledParam) UnmarshalJSON(data []byte) error {
3034 return apijson.UnmarshalRoot(data, r)
3035}
3036
3037func ThinkingConfigParamOfEnabled(budgetTokens int64) ThinkingConfigParamUnion {
3038 var enabled ThinkingConfigEnabledParam
3039 enabled.BudgetTokens = budgetTokens
3040 return ThinkingConfigParamUnion{OfEnabled: &enabled}
3041}
3042
3043// Only one field can be non-zero.
3044//
3045// Use [param.IsOmitted] to confirm if a field is set.
3046type ThinkingConfigParamUnion struct {
3047 OfEnabled *ThinkingConfigEnabledParam `json:",omitzero,inline"`
3048 OfDisabled *ThinkingConfigDisabledParam `json:",omitzero,inline"`
3049 paramUnion
3050}
3051
3052func (u ThinkingConfigParamUnion) MarshalJSON() ([]byte, error) {
3053 return param.MarshalUnion(u, u.OfEnabled, u.OfDisabled)
3054}
3055func (u *ThinkingConfigParamUnion) UnmarshalJSON(data []byte) error {
3056 return apijson.UnmarshalRoot(data, u)
3057}
3058
3059func (u *ThinkingConfigParamUnion) asAny() any {
3060 if !param.IsOmitted(u.OfEnabled) {
3061 return u.OfEnabled
3062 } else if !param.IsOmitted(u.OfDisabled) {
3063 return u.OfDisabled
3064 }
3065 return nil
3066}
3067
3068// Returns a pointer to the underlying variant's property, if present.
3069func (u ThinkingConfigParamUnion) GetBudgetTokens() *int64 {
3070 if vt := u.OfEnabled; vt != nil {
3071 return &vt.BudgetTokens
3072 }
3073 return nil
3074}
3075
3076// Returns a pointer to the underlying variant's property, if present.
3077func (u ThinkingConfigParamUnion) GetType() *string {
3078 if vt := u.OfEnabled; vt != nil {
3079 return (*string)(&vt.Type)
3080 } else if vt := u.OfDisabled; vt != nil {
3081 return (*string)(&vt.Type)
3082 }
3083 return nil
3084}
3085
3086type ThinkingDelta struct {
3087 Thinking string `json:"thinking,required"`
3088 Type constant.ThinkingDelta `json:"type,required"`
3089 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
3090 JSON struct {
3091 Thinking respjson.Field
3092 Type respjson.Field
3093 ExtraFields map[string]respjson.Field
3094 raw string
3095 } `json:"-"`
3096}
3097
3098// Returns the unmodified JSON received from the API
3099func (r ThinkingDelta) RawJSON() string { return r.JSON.raw }
3100func (r *ThinkingDelta) UnmarshalJSON(data []byte) error {
3101 return apijson.UnmarshalRoot(data, r)
3102}
3103
3104// The properties InputSchema, Name are required.
3105type ToolParam struct {
3106 // [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.
3107 //
3108 // This defines the shape of the `input` that your tool accepts and that the model
3109 // will produce.
3110 InputSchema ToolInputSchemaParam `json:"input_schema,omitzero,required"`
3111 // Name of the tool.
3112 //
3113 // This is how the tool will be called by the model and in `tool_use` blocks.
3114 Name string `json:"name,required"`
3115 // Description of what this tool does.
3116 //
3117 // Tool descriptions should be as detailed as possible. The more information that
3118 // the model has about what the tool is and how to use it, the better it will
3119 // perform. You can use natural language descriptions to reinforce important
3120 // aspects of the tool input JSON schema.
3121 Description param.Opt[string] `json:"description,omitzero"`
3122 // Any of "custom".
3123 Type ToolType `json:"type,omitzero"`
3124 // Create a cache control breakpoint at this content block.
3125 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
3126 paramObj
3127}
3128
3129func (r ToolParam) MarshalJSON() (data []byte, err error) {
3130 type shadow ToolParam
3131 return param.MarshalObject(r, (*shadow)(&r))
3132}
3133func (r *ToolParam) UnmarshalJSON(data []byte) error {
3134 return apijson.UnmarshalRoot(data, r)
3135}
3136
3137// [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.
3138//
3139// This defines the shape of the `input` that your tool accepts and that the model
3140// will produce.
3141//
3142// The property Type is required.
3143type ToolInputSchemaParam struct {
3144 Properties any `json:"properties,omitzero"`
3145 Required []string `json:"required,omitzero"`
3146 // This field can be elided, and will marshal its zero value as "object".
3147 Type constant.Object `json:"type,required"`
3148 ExtraFields map[string]any `json:"-"`
3149 paramObj
3150}
3151
3152func (r ToolInputSchemaParam) MarshalJSON() (data []byte, err error) {
3153 type shadow ToolInputSchemaParam
3154 return param.MarshalWithExtras(r, (*shadow)(&r), r.ExtraFields)
3155}
3156func (r *ToolInputSchemaParam) UnmarshalJSON(data []byte) error {
3157 return apijson.UnmarshalRoot(data, r)
3158}
3159
3160type ToolType string
3161
3162const (
3163 ToolTypeCustom ToolType = "custom"
3164)
3165
3166// The properties Name, Type are required.
3167type ToolBash20250124Param struct {
3168 // Create a cache control breakpoint at this content block.
3169 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
3170 // Name of the tool.
3171 //
3172 // This is how the tool will be called by the model and in `tool_use` blocks.
3173 //
3174 // This field can be elided, and will marshal its zero value as "bash".
3175 Name constant.Bash `json:"name,required"`
3176 // This field can be elided, and will marshal its zero value as "bash_20250124".
3177 Type constant.Bash20250124 `json:"type,required"`
3178 paramObj
3179}
3180
3181func (r ToolBash20250124Param) MarshalJSON() (data []byte, err error) {
3182 type shadow ToolBash20250124Param
3183 return param.MarshalObject(r, (*shadow)(&r))
3184}
3185func (r *ToolBash20250124Param) UnmarshalJSON(data []byte) error {
3186 return apijson.UnmarshalRoot(data, r)
3187}
3188
3189func ToolChoiceParamOfTool(name string) ToolChoiceUnionParam {
3190 var tool ToolChoiceToolParam
3191 tool.Name = name
3192 return ToolChoiceUnionParam{OfTool: &tool}
3193}
3194
3195// Only one field can be non-zero.
3196//
3197// Use [param.IsOmitted] to confirm if a field is set.
3198type ToolChoiceUnionParam struct {
3199 OfAuto *ToolChoiceAutoParam `json:",omitzero,inline"`
3200 OfAny *ToolChoiceAnyParam `json:",omitzero,inline"`
3201 OfTool *ToolChoiceToolParam `json:",omitzero,inline"`
3202 OfNone *ToolChoiceNoneParam `json:",omitzero,inline"`
3203 paramUnion
3204}
3205
3206func (u ToolChoiceUnionParam) MarshalJSON() ([]byte, error) {
3207 return param.MarshalUnion(u, u.OfAuto, u.OfAny, u.OfTool, u.OfNone)
3208}
3209func (u *ToolChoiceUnionParam) UnmarshalJSON(data []byte) error {
3210 return apijson.UnmarshalRoot(data, u)
3211}
3212
3213func (u *ToolChoiceUnionParam) asAny() any {
3214 if !param.IsOmitted(u.OfAuto) {
3215 return u.OfAuto
3216 } else if !param.IsOmitted(u.OfAny) {
3217 return u.OfAny
3218 } else if !param.IsOmitted(u.OfTool) {
3219 return u.OfTool
3220 } else if !param.IsOmitted(u.OfNone) {
3221 return u.OfNone
3222 }
3223 return nil
3224}
3225
3226// Returns a pointer to the underlying variant's property, if present.
3227func (u ToolChoiceUnionParam) GetName() *string {
3228 if vt := u.OfTool; vt != nil {
3229 return &vt.Name
3230 }
3231 return nil
3232}
3233
3234// Returns a pointer to the underlying variant's property, if present.
3235func (u ToolChoiceUnionParam) GetType() *string {
3236 if vt := u.OfAuto; vt != nil {
3237 return (*string)(&vt.Type)
3238 } else if vt := u.OfAny; vt != nil {
3239 return (*string)(&vt.Type)
3240 } else if vt := u.OfTool; vt != nil {
3241 return (*string)(&vt.Type)
3242 } else if vt := u.OfNone; vt != nil {
3243 return (*string)(&vt.Type)
3244 }
3245 return nil
3246}
3247
3248// Returns a pointer to the underlying variant's property, if present.
3249func (u ToolChoiceUnionParam) GetDisableParallelToolUse() *bool {
3250 if vt := u.OfAuto; vt != nil && vt.DisableParallelToolUse.Valid() {
3251 return &vt.DisableParallelToolUse.Value
3252 } else if vt := u.OfAny; vt != nil && vt.DisableParallelToolUse.Valid() {
3253 return &vt.DisableParallelToolUse.Value
3254 } else if vt := u.OfTool; vt != nil && vt.DisableParallelToolUse.Valid() {
3255 return &vt.DisableParallelToolUse.Value
3256 }
3257 return nil
3258}
3259
3260// The model will use any available tools.
3261//
3262// The property Type is required.
3263type ToolChoiceAnyParam struct {
3264 // Whether to disable parallel tool use.
3265 //
3266 // Defaults to `false`. If set to `true`, the model will output exactly one tool
3267 // use.
3268 DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"`
3269 // This field can be elided, and will marshal its zero value as "any".
3270 Type constant.Any `json:"type,required"`
3271 paramObj
3272}
3273
3274func (r ToolChoiceAnyParam) MarshalJSON() (data []byte, err error) {
3275 type shadow ToolChoiceAnyParam
3276 return param.MarshalObject(r, (*shadow)(&r))
3277}
3278func (r *ToolChoiceAnyParam) UnmarshalJSON(data []byte) error {
3279 return apijson.UnmarshalRoot(data, r)
3280}
3281
3282// The model will automatically decide whether to use tools.
3283//
3284// The property Type is required.
3285type ToolChoiceAutoParam struct {
3286 // Whether to disable parallel tool use.
3287 //
3288 // Defaults to `false`. If set to `true`, the model will output at most one tool
3289 // use.
3290 DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"`
3291 // This field can be elided, and will marshal its zero value as "auto".
3292 Type constant.Auto `json:"type,required"`
3293 paramObj
3294}
3295
3296func (r ToolChoiceAutoParam) MarshalJSON() (data []byte, err error) {
3297 type shadow ToolChoiceAutoParam
3298 return param.MarshalObject(r, (*shadow)(&r))
3299}
3300func (r *ToolChoiceAutoParam) UnmarshalJSON(data []byte) error {
3301 return apijson.UnmarshalRoot(data, r)
3302}
3303
3304func NewToolChoiceNoneParam() ToolChoiceNoneParam {
3305 return ToolChoiceNoneParam{
3306 Type: "none",
3307 }
3308}
3309
3310// The model will not be allowed to use tools.
3311//
3312// This struct has a constant value, construct it with [NewToolChoiceNoneParam].
3313type ToolChoiceNoneParam struct {
3314 Type constant.None `json:"type,required"`
3315 paramObj
3316}
3317
3318func (r ToolChoiceNoneParam) MarshalJSON() (data []byte, err error) {
3319 type shadow ToolChoiceNoneParam
3320 return param.MarshalObject(r, (*shadow)(&r))
3321}
3322func (r *ToolChoiceNoneParam) UnmarshalJSON(data []byte) error {
3323 return apijson.UnmarshalRoot(data, r)
3324}
3325
3326// The model will use the specified tool with `tool_choice.name`.
3327//
3328// The properties Name, Type are required.
3329type ToolChoiceToolParam struct {
3330 // The name of the tool to use.
3331 Name string `json:"name,required"`
3332 // Whether to disable parallel tool use.
3333 //
3334 // Defaults to `false`. If set to `true`, the model will output exactly one tool
3335 // use.
3336 DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"`
3337 // This field can be elided, and will marshal its zero value as "tool".
3338 Type constant.Tool `json:"type,required"`
3339 paramObj
3340}
3341
3342func (r ToolChoiceToolParam) MarshalJSON() (data []byte, err error) {
3343 type shadow ToolChoiceToolParam
3344 return param.MarshalObject(r, (*shadow)(&r))
3345}
3346func (r *ToolChoiceToolParam) UnmarshalJSON(data []byte) error {
3347 return apijson.UnmarshalRoot(data, r)
3348}
3349
3350// The properties ToolUseID, Type are required.
3351type ToolResultBlockParam struct {
3352 ToolUseID string `json:"tool_use_id,required"`
3353 IsError param.Opt[bool] `json:"is_error,omitzero"`
3354 // Create a cache control breakpoint at this content block.
3355 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
3356 Content []ToolResultBlockParamContentUnion `json:"content,omitzero"`
3357 // This field can be elided, and will marshal its zero value as "tool_result".
3358 Type constant.ToolResult `json:"type,required"`
3359 paramObj
3360}
3361
3362func (r ToolResultBlockParam) MarshalJSON() (data []byte, err error) {
3363 type shadow ToolResultBlockParam
3364 return param.MarshalObject(r, (*shadow)(&r))
3365}
3366func (r *ToolResultBlockParam) UnmarshalJSON(data []byte) error {
3367 return apijson.UnmarshalRoot(data, r)
3368}
3369
3370// Only one field can be non-zero.
3371//
3372// Use [param.IsOmitted] to confirm if a field is set.
3373type ToolResultBlockParamContentUnion struct {
3374 OfText *TextBlockParam `json:",omitzero,inline"`
3375 OfImage *ImageBlockParam `json:",omitzero,inline"`
3376 paramUnion
3377}
3378
3379func (u ToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) {
3380 return param.MarshalUnion(u, u.OfText, u.OfImage)
3381}
3382func (u *ToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error {
3383 return apijson.UnmarshalRoot(data, u)
3384}
3385
3386func (u *ToolResultBlockParamContentUnion) asAny() any {
3387 if !param.IsOmitted(u.OfText) {
3388 return u.OfText
3389 } else if !param.IsOmitted(u.OfImage) {
3390 return u.OfImage
3391 }
3392 return nil
3393}
3394
3395// Returns a pointer to the underlying variant's property, if present.
3396func (u ToolResultBlockParamContentUnion) GetText() *string {
3397 if vt := u.OfText; vt != nil {
3398 return &vt.Text
3399 }
3400 return nil
3401}
3402
3403// Returns a pointer to the underlying variant's property, if present.
3404func (u ToolResultBlockParamContentUnion) GetCitations() []TextCitationParamUnion {
3405 if vt := u.OfText; vt != nil {
3406 return vt.Citations
3407 }
3408 return nil
3409}
3410
3411// Returns a pointer to the underlying variant's property, if present.
3412func (u ToolResultBlockParamContentUnion) GetSource() *ImageBlockParamSourceUnion {
3413 if vt := u.OfImage; vt != nil {
3414 return &vt.Source
3415 }
3416 return nil
3417}
3418
3419// Returns a pointer to the underlying variant's property, if present.
3420func (u ToolResultBlockParamContentUnion) GetType() *string {
3421 if vt := u.OfText; vt != nil {
3422 return (*string)(&vt.Type)
3423 } else if vt := u.OfImage; vt != nil {
3424 return (*string)(&vt.Type)
3425 }
3426 return nil
3427}
3428
3429// Returns a pointer to the underlying variant's CacheControl property, if present.
3430func (u ToolResultBlockParamContentUnion) GetCacheControl() *CacheControlEphemeralParam {
3431 if vt := u.OfText; vt != nil {
3432 return &vt.CacheControl
3433 } else if vt := u.OfImage; vt != nil {
3434 return &vt.CacheControl
3435 }
3436 return nil
3437}
3438
3439// The properties Name, Type are required.
3440type ToolTextEditor20250124Param struct {
3441 // Create a cache control breakpoint at this content block.
3442 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
3443 // Name of the tool.
3444 //
3445 // This is how the tool will be called by the model and in `tool_use` blocks.
3446 //
3447 // This field can be elided, and will marshal its zero value as
3448 // "str_replace_editor".
3449 Name constant.StrReplaceEditor `json:"name,required"`
3450 // This field can be elided, and will marshal its zero value as
3451 // "text_editor_20250124".
3452 Type constant.TextEditor20250124 `json:"type,required"`
3453 paramObj
3454}
3455
3456func (r ToolTextEditor20250124Param) MarshalJSON() (data []byte, err error) {
3457 type shadow ToolTextEditor20250124Param
3458 return param.MarshalObject(r, (*shadow)(&r))
3459}
3460func (r *ToolTextEditor20250124Param) UnmarshalJSON(data []byte) error {
3461 return apijson.UnmarshalRoot(data, r)
3462}
3463
3464func ToolUnionParamOfTool(inputSchema ToolInputSchemaParam, name string) ToolUnionParam {
3465 var variant ToolParam
3466 variant.InputSchema = inputSchema
3467 variant.Name = name
3468 return ToolUnionParam{OfTool: &variant}
3469}
3470
3471// Only one field can be non-zero.
3472//
3473// Use [param.IsOmitted] to confirm if a field is set.
3474type ToolUnionParam struct {
3475 OfTool *ToolParam `json:",omitzero,inline"`
3476 OfBashTool20250124 *ToolBash20250124Param `json:",omitzero,inline"`
3477 OfTextEditor20250124 *ToolTextEditor20250124Param `json:",omitzero,inline"`
3478 OfTextEditor20250429 *ToolUnionTextEditor20250429Param `json:",omitzero,inline"`
3479 OfWebSearchTool20250305 *WebSearchTool20250305Param `json:",omitzero,inline"`
3480 paramUnion
3481}
3482
3483func (u ToolUnionParam) MarshalJSON() ([]byte, error) {
3484 return param.MarshalUnion(u, u.OfTool,
3485 u.OfBashTool20250124,
3486 u.OfTextEditor20250124,
3487 u.OfTextEditor20250429,
3488 u.OfWebSearchTool20250305)
3489}
3490func (u *ToolUnionParam) UnmarshalJSON(data []byte) error {
3491 return apijson.UnmarshalRoot(data, u)
3492}
3493
3494func (u *ToolUnionParam) asAny() any {
3495 if !param.IsOmitted(u.OfTool) {
3496 return u.OfTool
3497 } else if !param.IsOmitted(u.OfBashTool20250124) {
3498 return u.OfBashTool20250124
3499 } else if !param.IsOmitted(u.OfTextEditor20250124) {
3500 return u.OfTextEditor20250124
3501 } else if !param.IsOmitted(u.OfTextEditor20250429) {
3502 return u.OfTextEditor20250429
3503 } else if !param.IsOmitted(u.OfWebSearchTool20250305) {
3504 return u.OfWebSearchTool20250305
3505 }
3506 return nil
3507}
3508
3509// Returns a pointer to the underlying variant's property, if present.
3510func (u ToolUnionParam) GetInputSchema() *ToolInputSchemaParam {
3511 if vt := u.OfTool; vt != nil {
3512 return &vt.InputSchema
3513 }
3514 return nil
3515}
3516
3517// Returns a pointer to the underlying variant's property, if present.
3518func (u ToolUnionParam) GetDescription() *string {
3519 if vt := u.OfTool; vt != nil && vt.Description.Valid() {
3520 return &vt.Description.Value
3521 }
3522 return nil
3523}
3524
3525// Returns a pointer to the underlying variant's property, if present.
3526func (u ToolUnionParam) GetAllowedDomains() []string {
3527 if vt := u.OfWebSearchTool20250305; vt != nil {
3528 return vt.AllowedDomains
3529 }
3530 return nil
3531}
3532
3533// Returns a pointer to the underlying variant's property, if present.
3534func (u ToolUnionParam) GetBlockedDomains() []string {
3535 if vt := u.OfWebSearchTool20250305; vt != nil {
3536 return vt.BlockedDomains
3537 }
3538 return nil
3539}
3540
3541// Returns a pointer to the underlying variant's property, if present.
3542func (u ToolUnionParam) GetMaxUses() *int64 {
3543 if vt := u.OfWebSearchTool20250305; vt != nil && vt.MaxUses.Valid() {
3544 return &vt.MaxUses.Value
3545 }
3546 return nil
3547}
3548
3549// Returns a pointer to the underlying variant's property, if present.
3550func (u ToolUnionParam) GetUserLocation() *WebSearchTool20250305UserLocationParam {
3551 if vt := u.OfWebSearchTool20250305; vt != nil {
3552 return &vt.UserLocation
3553 }
3554 return nil
3555}
3556
3557// Returns a pointer to the underlying variant's property, if present.
3558func (u ToolUnionParam) GetName() *string {
3559 if vt := u.OfTool; vt != nil {
3560 return (*string)(&vt.Name)
3561 } else if vt := u.OfBashTool20250124; vt != nil {
3562 return (*string)(&vt.Name)
3563 } else if vt := u.OfTextEditor20250124; vt != nil {
3564 return (*string)(&vt.Name)
3565 } else if vt := u.OfTextEditor20250429; vt != nil {
3566 return (*string)(&vt.Name)
3567 } else if vt := u.OfWebSearchTool20250305; vt != nil {
3568 return (*string)(&vt.Name)
3569 }
3570 return nil
3571}
3572
3573// Returns a pointer to the underlying variant's property, if present.
3574func (u ToolUnionParam) GetType() *string {
3575 if vt := u.OfTool; vt != nil {
3576 return (*string)(&vt.Type)
3577 } else if vt := u.OfBashTool20250124; vt != nil {
3578 return (*string)(&vt.Type)
3579 } else if vt := u.OfTextEditor20250124; vt != nil {
3580 return (*string)(&vt.Type)
3581 } else if vt := u.OfTextEditor20250429; vt != nil {
3582 return (*string)(&vt.Type)
3583 } else if vt := u.OfWebSearchTool20250305; vt != nil {
3584 return (*string)(&vt.Type)
3585 }
3586 return nil
3587}
3588
3589// Returns a pointer to the underlying variant's CacheControl property, if present.
3590func (u ToolUnionParam) GetCacheControl() *CacheControlEphemeralParam {
3591 if vt := u.OfTool; vt != nil {
3592 return &vt.CacheControl
3593 } else if vt := u.OfBashTool20250124; vt != nil {
3594 return &vt.CacheControl
3595 } else if vt := u.OfTextEditor20250124; vt != nil {
3596 return &vt.CacheControl
3597 } else if vt := u.OfTextEditor20250429; vt != nil {
3598 return &vt.CacheControl
3599 } else if vt := u.OfWebSearchTool20250305; vt != nil {
3600 return &vt.CacheControl
3601 }
3602 return nil
3603}
3604
3605// The properties Name, Type are required.
3606type ToolUnionTextEditor20250429Param struct {
3607 // Create a cache control breakpoint at this content block.
3608 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
3609 // Name of the tool.
3610 //
3611 // This is how the tool will be called by the model and in `tool_use` blocks.
3612 //
3613 // This field can be elided, and will marshal its zero value as
3614 // "str_replace_based_edit_tool".
3615 Name constant.StrReplaceBasedEditTool `json:"name,required"`
3616 // This field can be elided, and will marshal its zero value as
3617 // "text_editor_20250429".
3618 Type constant.TextEditor20250429 `json:"type,required"`
3619 paramObj
3620}
3621
3622func (r ToolUnionTextEditor20250429Param) MarshalJSON() (data []byte, err error) {
3623 type shadow ToolUnionTextEditor20250429Param
3624 return param.MarshalObject(r, (*shadow)(&r))
3625}
3626func (r *ToolUnionTextEditor20250429Param) UnmarshalJSON(data []byte) error {
3627 return apijson.UnmarshalRoot(data, r)
3628}
3629
3630type ToolUseBlock struct {
3631 ID string `json:"id,required"`
3632 Input json.RawMessage `json:"input,required"`
3633 Name string `json:"name,required"`
3634 Type constant.ToolUse `json:"type,required"`
3635 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
3636 JSON struct {
3637 ID respjson.Field
3638 Input respjson.Field
3639 Name respjson.Field
3640 Type respjson.Field
3641 ExtraFields map[string]respjson.Field
3642 raw string
3643 } `json:"-"`
3644}
3645
3646// Returns the unmodified JSON received from the API
3647func (r ToolUseBlock) RawJSON() string { return r.JSON.raw }
3648func (r *ToolUseBlock) UnmarshalJSON(data []byte) error {
3649 return apijson.UnmarshalRoot(data, r)
3650}
3651
3652func (r ToolUseBlock) ToParam() ToolUseBlockParam {
3653 var toolUse ToolUseBlockParam
3654 toolUse.Type = r.Type
3655 toolUse.ID = r.ID
3656 toolUse.Input = r.Input
3657 toolUse.Name = r.Name
3658 return toolUse
3659}
3660
3661// The properties ID, Input, Name, Type are required.
3662type ToolUseBlockParam struct {
3663 ID string `json:"id,required"`
3664 Input any `json:"input,omitzero,required"`
3665 Name string `json:"name,required"`
3666 // Create a cache control breakpoint at this content block.
3667 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
3668 // This field can be elided, and will marshal its zero value as "tool_use".
3669 Type constant.ToolUse `json:"type,required"`
3670 paramObj
3671}
3672
3673func (r ToolUseBlockParam) MarshalJSON() (data []byte, err error) {
3674 type shadow ToolUseBlockParam
3675 return param.MarshalObject(r, (*shadow)(&r))
3676}
3677func (r *ToolUseBlockParam) UnmarshalJSON(data []byte) error {
3678 return apijson.UnmarshalRoot(data, r)
3679}
3680
3681// The properties Type, URL are required.
3682type URLImageSourceParam struct {
3683 URL string `json:"url,required"`
3684 // This field can be elided, and will marshal its zero value as "url".
3685 Type constant.URL `json:"type,required"`
3686 paramObj
3687}
3688
3689func (r URLImageSourceParam) MarshalJSON() (data []byte, err error) {
3690 type shadow URLImageSourceParam
3691 return param.MarshalObject(r, (*shadow)(&r))
3692}
3693func (r *URLImageSourceParam) UnmarshalJSON(data []byte) error {
3694 return apijson.UnmarshalRoot(data, r)
3695}
3696
3697// The properties Type, URL are required.
3698type URLPDFSourceParam struct {
3699 URL string `json:"url,required"`
3700 // This field can be elided, and will marshal its zero value as "url".
3701 Type constant.URL `json:"type,required"`
3702 paramObj
3703}
3704
3705func (r URLPDFSourceParam) MarshalJSON() (data []byte, err error) {
3706 type shadow URLPDFSourceParam
3707 return param.MarshalObject(r, (*shadow)(&r))
3708}
3709func (r *URLPDFSourceParam) UnmarshalJSON(data []byte) error {
3710 return apijson.UnmarshalRoot(data, r)
3711}
3712
3713type Usage struct {
3714 // The number of input tokens used to create the cache entry.
3715 CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,required"`
3716 // The number of input tokens read from the cache.
3717 CacheReadInputTokens int64 `json:"cache_read_input_tokens,required"`
3718 // The number of input tokens which were used.
3719 InputTokens int64 `json:"input_tokens,required"`
3720 // The number of output tokens which were used.
3721 OutputTokens int64 `json:"output_tokens,required"`
3722 // The number of server tool requests.
3723 ServerToolUse ServerToolUsage `json:"server_tool_use,required"`
3724 // If the request used the priority, standard, or batch tier.
3725 //
3726 // Any of "standard", "priority", "batch".
3727 ServiceTier UsageServiceTier `json:"service_tier,required"`
3728 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
3729 JSON struct {
3730 CacheCreationInputTokens respjson.Field
3731 CacheReadInputTokens respjson.Field
3732 InputTokens respjson.Field
3733 OutputTokens respjson.Field
3734 ServerToolUse respjson.Field
3735 ServiceTier respjson.Field
3736 ExtraFields map[string]respjson.Field
3737 raw string
3738 } `json:"-"`
3739}
3740
3741// Returns the unmodified JSON received from the API
3742func (r Usage) RawJSON() string { return r.JSON.raw }
3743func (r *Usage) UnmarshalJSON(data []byte) error {
3744 return apijson.UnmarshalRoot(data, r)
3745}
3746
3747// If the request used the priority, standard, or batch tier.
3748type UsageServiceTier string
3749
3750const (
3751 UsageServiceTierStandard UsageServiceTier = "standard"
3752 UsageServiceTierPriority UsageServiceTier = "priority"
3753 UsageServiceTierBatch UsageServiceTier = "batch"
3754)
3755
3756type WebSearchResultBlock struct {
3757 EncryptedContent string `json:"encrypted_content,required"`
3758 PageAge string `json:"page_age,required"`
3759 Title string `json:"title,required"`
3760 Type constant.WebSearchResult `json:"type,required"`
3761 URL string `json:"url,required"`
3762 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
3763 JSON struct {
3764 EncryptedContent respjson.Field
3765 PageAge respjson.Field
3766 Title respjson.Field
3767 Type respjson.Field
3768 URL respjson.Field
3769 ExtraFields map[string]respjson.Field
3770 raw string
3771 } `json:"-"`
3772}
3773
3774// Returns the unmodified JSON received from the API
3775func (r WebSearchResultBlock) RawJSON() string { return r.JSON.raw }
3776func (r *WebSearchResultBlock) UnmarshalJSON(data []byte) error {
3777 return apijson.UnmarshalRoot(data, r)
3778}
3779
3780// The properties EncryptedContent, Title, Type, URL are required.
3781type WebSearchResultBlockParam struct {
3782 EncryptedContent string `json:"encrypted_content,required"`
3783 Title string `json:"title,required"`
3784 URL string `json:"url,required"`
3785 PageAge param.Opt[string] `json:"page_age,omitzero"`
3786 // This field can be elided, and will marshal its zero value as
3787 // "web_search_result".
3788 Type constant.WebSearchResult `json:"type,required"`
3789 paramObj
3790}
3791
3792func (r WebSearchResultBlockParam) MarshalJSON() (data []byte, err error) {
3793 type shadow WebSearchResultBlockParam
3794 return param.MarshalObject(r, (*shadow)(&r))
3795}
3796func (r *WebSearchResultBlockParam) UnmarshalJSON(data []byte) error {
3797 return apijson.UnmarshalRoot(data, r)
3798}
3799
3800// The properties Name, Type are required.
3801type WebSearchTool20250305Param struct {
3802 // Maximum number of times the tool can be used in the API request.
3803 MaxUses param.Opt[int64] `json:"max_uses,omitzero"`
3804 // If provided, only these domains will be included in results. Cannot be used
3805 // alongside `blocked_domains`.
3806 AllowedDomains []string `json:"allowed_domains,omitzero"`
3807 // If provided, these domains will never appear in results. Cannot be used
3808 // alongside `allowed_domains`.
3809 BlockedDomains []string `json:"blocked_domains,omitzero"`
3810 // Parameters for the user's location. Used to provide more relevant search
3811 // results.
3812 UserLocation WebSearchTool20250305UserLocationParam `json:"user_location,omitzero"`
3813 // Create a cache control breakpoint at this content block.
3814 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
3815 // Name of the tool.
3816 //
3817 // This is how the tool will be called by the model and in `tool_use` blocks.
3818 //
3819 // This field can be elided, and will marshal its zero value as "web_search".
3820 Name constant.WebSearch `json:"name,required"`
3821 // This field can be elided, and will marshal its zero value as
3822 // "web_search_20250305".
3823 Type constant.WebSearch20250305 `json:"type,required"`
3824 paramObj
3825}
3826
3827func (r WebSearchTool20250305Param) MarshalJSON() (data []byte, err error) {
3828 type shadow WebSearchTool20250305Param
3829 return param.MarshalObject(r, (*shadow)(&r))
3830}
3831func (r *WebSearchTool20250305Param) UnmarshalJSON(data []byte) error {
3832 return apijson.UnmarshalRoot(data, r)
3833}
3834
3835// Parameters for the user's location. Used to provide more relevant search
3836// results.
3837//
3838// The property Type is required.
3839type WebSearchTool20250305UserLocationParam struct {
3840 // The city of the user.
3841 City param.Opt[string] `json:"city,omitzero"`
3842 // The two letter
3843 // [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the
3844 // user.
3845 Country param.Opt[string] `json:"country,omitzero"`
3846 // The region of the user.
3847 Region param.Opt[string] `json:"region,omitzero"`
3848 // The [IANA timezone](https://nodatime.org/TimeZones) of the user.
3849 Timezone param.Opt[string] `json:"timezone,omitzero"`
3850 // This field can be elided, and will marshal its zero value as "approximate".
3851 Type constant.Approximate `json:"type,required"`
3852 paramObj
3853}
3854
3855func (r WebSearchTool20250305UserLocationParam) MarshalJSON() (data []byte, err error) {
3856 type shadow WebSearchTool20250305UserLocationParam
3857 return param.MarshalObject(r, (*shadow)(&r))
3858}
3859func (r *WebSearchTool20250305UserLocationParam) UnmarshalJSON(data []byte) error {
3860 return apijson.UnmarshalRoot(data, r)
3861}
3862
3863// The properties ErrorCode, Type are required.
3864type WebSearchToolRequestErrorParam struct {
3865 // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded",
3866 // "too_many_requests", "query_too_long".
3867 ErrorCode WebSearchToolRequestErrorErrorCode `json:"error_code,omitzero,required"`
3868 // This field can be elided, and will marshal its zero value as
3869 // "web_search_tool_result_error".
3870 Type constant.WebSearchToolResultError `json:"type,required"`
3871 paramObj
3872}
3873
3874func (r WebSearchToolRequestErrorParam) MarshalJSON() (data []byte, err error) {
3875 type shadow WebSearchToolRequestErrorParam
3876 return param.MarshalObject(r, (*shadow)(&r))
3877}
3878func (r *WebSearchToolRequestErrorParam) UnmarshalJSON(data []byte) error {
3879 return apijson.UnmarshalRoot(data, r)
3880}
3881
3882type WebSearchToolRequestErrorErrorCode string
3883
3884const (
3885 WebSearchToolRequestErrorErrorCodeInvalidToolInput WebSearchToolRequestErrorErrorCode = "invalid_tool_input"
3886 WebSearchToolRequestErrorErrorCodeUnavailable WebSearchToolRequestErrorErrorCode = "unavailable"
3887 WebSearchToolRequestErrorErrorCodeMaxUsesExceeded WebSearchToolRequestErrorErrorCode = "max_uses_exceeded"
3888 WebSearchToolRequestErrorErrorCodeTooManyRequests WebSearchToolRequestErrorErrorCode = "too_many_requests"
3889 WebSearchToolRequestErrorErrorCodeQueryTooLong WebSearchToolRequestErrorErrorCode = "query_too_long"
3890)
3891
3892type WebSearchToolResultBlock struct {
3893 Content WebSearchToolResultBlockContentUnion `json:"content,required"`
3894 ToolUseID string `json:"tool_use_id,required"`
3895 Type constant.WebSearchToolResult `json:"type,required"`
3896 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
3897 JSON struct {
3898 Content respjson.Field
3899 ToolUseID respjson.Field
3900 Type respjson.Field
3901 ExtraFields map[string]respjson.Field
3902 raw string
3903 } `json:"-"`
3904}
3905
3906// Returns the unmodified JSON received from the API
3907func (r WebSearchToolResultBlock) RawJSON() string { return r.JSON.raw }
3908func (r *WebSearchToolResultBlock) UnmarshalJSON(data []byte) error {
3909 return apijson.UnmarshalRoot(data, r)
3910}
3911
3912// WebSearchToolResultBlockContentUnion contains all possible properties and values
3913// from [WebSearchToolResultError], [[]WebSearchResultBlock].
3914//
3915// Use the methods beginning with 'As' to cast the union to one of its variants.
3916//
3917// If the underlying value is not a json object, one of the following properties
3918// will be valid: OfWebSearchResultBlockArray]
3919type WebSearchToolResultBlockContentUnion struct {
3920 // This field will be present if the value is a [[]WebSearchResultBlock] instead of
3921 // an object.
3922 OfWebSearchResultBlockArray []WebSearchResultBlock `json:",inline"`
3923 // This field is from variant [WebSearchToolResultError].
3924 ErrorCode WebSearchToolResultErrorErrorCode `json:"error_code"`
3925 // This field is from variant [WebSearchToolResultError].
3926 Type constant.WebSearchToolResultError `json:"type"`
3927 JSON struct {
3928 OfWebSearchResultBlockArray respjson.Field
3929 ErrorCode respjson.Field
3930 Type respjson.Field
3931 raw string
3932 } `json:"-"`
3933}
3934
3935func (u WebSearchToolResultBlockContentUnion) AsResponseWebSearchToolResultError() (v WebSearchToolResultError) {
3936 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
3937 return
3938}
3939
3940func (u WebSearchToolResultBlockContentUnion) AsWebSearchResultBlockArray() (v []WebSearchResultBlock) {
3941 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
3942 return
3943}
3944
3945// Returns the unmodified JSON received from the API
3946func (u WebSearchToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw }
3947
3948func (r *WebSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error {
3949 return apijson.UnmarshalRoot(data, r)
3950}
3951
3952// The properties Content, ToolUseID, Type are required.
3953type WebSearchToolResultBlockParam struct {
3954 Content WebSearchToolResultBlockParamContentUnion `json:"content,omitzero,required"`
3955 ToolUseID string `json:"tool_use_id,required"`
3956 // Create a cache control breakpoint at this content block.
3957 CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
3958 // This field can be elided, and will marshal its zero value as
3959 // "web_search_tool_result".
3960 Type constant.WebSearchToolResult `json:"type,required"`
3961 paramObj
3962}
3963
3964func (r WebSearchToolResultBlockParam) MarshalJSON() (data []byte, err error) {
3965 type shadow WebSearchToolResultBlockParam
3966 return param.MarshalObject(r, (*shadow)(&r))
3967}
3968func (r *WebSearchToolResultBlockParam) UnmarshalJSON(data []byte) error {
3969 return apijson.UnmarshalRoot(data, r)
3970}
3971
3972func NewWebSearchToolRequestError(errorCode WebSearchToolRequestErrorErrorCode) WebSearchToolResultBlockParamContentUnion {
3973 var variant WebSearchToolRequestErrorParam
3974 variant.ErrorCode = errorCode
3975 return WebSearchToolResultBlockParamContentUnion{OfRequestWebSearchToolResultError: &variant}
3976}
3977
3978// Only one field can be non-zero.
3979//
3980// Use [param.IsOmitted] to confirm if a field is set.
3981type WebSearchToolResultBlockParamContentUnion struct {
3982 OfWebSearchToolResultBlockItem []WebSearchResultBlockParam `json:",omitzero,inline"`
3983 OfRequestWebSearchToolResultError *WebSearchToolRequestErrorParam `json:",omitzero,inline"`
3984 paramUnion
3985}
3986
3987func (u WebSearchToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) {
3988 return param.MarshalUnion(u, u.OfWebSearchToolResultBlockItem, u.OfRequestWebSearchToolResultError)
3989}
3990func (u *WebSearchToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error {
3991 return apijson.UnmarshalRoot(data, u)
3992}
3993
3994func (u *WebSearchToolResultBlockParamContentUnion) asAny() any {
3995 if !param.IsOmitted(u.OfWebSearchToolResultBlockItem) {
3996 return &u.OfWebSearchToolResultBlockItem
3997 } else if !param.IsOmitted(u.OfRequestWebSearchToolResultError) {
3998 return u.OfRequestWebSearchToolResultError
3999 }
4000 return nil
4001}
4002
4003type WebSearchToolResultError struct {
4004 // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded",
4005 // "too_many_requests", "query_too_long".
4006 ErrorCode WebSearchToolResultErrorErrorCode `json:"error_code,required"`
4007 Type constant.WebSearchToolResultError `json:"type,required"`
4008 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
4009 JSON struct {
4010 ErrorCode respjson.Field
4011 Type respjson.Field
4012 ExtraFields map[string]respjson.Field
4013 raw string
4014 } `json:"-"`
4015}
4016
4017// Returns the unmodified JSON received from the API
4018func (r WebSearchToolResultError) RawJSON() string { return r.JSON.raw }
4019func (r *WebSearchToolResultError) UnmarshalJSON(data []byte) error {
4020 return apijson.UnmarshalRoot(data, r)
4021}
4022
4023type WebSearchToolResultErrorErrorCode string
4024
4025const (
4026 WebSearchToolResultErrorErrorCodeInvalidToolInput WebSearchToolResultErrorErrorCode = "invalid_tool_input"
4027 WebSearchToolResultErrorErrorCodeUnavailable WebSearchToolResultErrorErrorCode = "unavailable"
4028 WebSearchToolResultErrorErrorCodeMaxUsesExceeded WebSearchToolResultErrorErrorCode = "max_uses_exceeded"
4029 WebSearchToolResultErrorErrorCodeTooManyRequests WebSearchToolResultErrorErrorCode = "too_many_requests"
4030 WebSearchToolResultErrorErrorCodeQueryTooLong WebSearchToolResultErrorErrorCode = "query_too_long"
4031)
4032
4033type MessageNewParams struct {
4034 // The maximum number of tokens to generate before stopping.
4035 //
4036 // Note that our models may stop _before_ reaching this maximum. This parameter
4037 // only specifies the absolute maximum number of tokens to generate.
4038 //
4039 // Different models have different maximum values for this parameter. See
4040 // [models](https://docs.anthropic.com/en/docs/models-overview) for details.
4041 MaxTokens int64 `json:"max_tokens,required"`
4042 // Input messages.
4043 //
4044 // Our models are trained to operate on alternating `user` and `assistant`
4045 // conversational turns. When creating a new `Message`, you specify the prior
4046 // conversational turns with the `messages` parameter, and the model then generates
4047 // the next `Message` in the conversation. Consecutive `user` or `assistant` turns
4048 // in your request will be combined into a single turn.
4049 //
4050 // Each input message must be an object with a `role` and `content`. You can
4051 // specify a single `user`-role message, or you can include multiple `user` and
4052 // `assistant` messages.
4053 //
4054 // If the final message uses the `assistant` role, the response content will
4055 // continue immediately from the content in that message. This can be used to
4056 // constrain part of the model's response.
4057 //
4058 // Example with a single `user` message:
4059 //
4060 // ```json
4061 // [{ "role": "user", "content": "Hello, Claude" }]
4062 // ```
4063 //
4064 // Example with multiple conversational turns:
4065 //
4066 // ```json
4067 // [
4068 //
4069 // { "role": "user", "content": "Hello there." },
4070 // { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
4071 // { "role": "user", "content": "Can you explain LLMs in plain English?" }
4072 //
4073 // ]
4074 // ```
4075 //
4076 // Example with a partially-filled response from Claude:
4077 //
4078 // ```json
4079 // [
4080 //
4081 // {
4082 // "role": "user",
4083 // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
4084 // },
4085 // { "role": "assistant", "content": "The best answer is (" }
4086 //
4087 // ]
4088 // ```
4089 //
4090 // Each input message `content` may be either a single `string` or an array of
4091 // content blocks, where each block has a specific `type`. Using a `string` for
4092 // `content` is shorthand for an array of one content block of type `"text"`. The
4093 // following input messages are equivalent:
4094 //
4095 // ```json
4096 // { "role": "user", "content": "Hello, Claude" }
4097 // ```
4098 //
4099 // ```json
4100 // { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
4101 // ```
4102 //
4103 // Starting with Claude 3 models, you can also send image content blocks:
4104 //
4105 // ```json
4106 //
4107 // {
4108 // "role": "user",
4109 // "content": [
4110 // {
4111 // "type": "image",
4112 // "source": {
4113 // "type": "base64",
4114 // "media_type": "image/jpeg",
4115 // "data": "/9j/4AAQSkZJRg..."
4116 // }
4117 // },
4118 // { "type": "text", "text": "What is in this image?" }
4119 // ]
4120 // }
4121 //
4122 // ```
4123 //
4124 // We currently support the `base64` source type for images, and the `image/jpeg`,
4125 // `image/png`, `image/gif`, and `image/webp` media types.
4126 //
4127 // See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for
4128 // more input examples.
4129 //
4130 // Note that if you want to include a
4131 // [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
4132 // the top-level `system` parameter — there is no `"system"` role for input
4133 // messages in the Messages API.
4134 //
4135 // There is a limit of 100000 messages in a single request.
4136 Messages []MessageParam `json:"messages,omitzero,required"`
4137 // The model that will complete your prompt.\n\nSee
4138 // [models](https://docs.anthropic.com/en/docs/models-overview) for additional
4139 // details and options.
4140 Model Model `json:"model,omitzero,required"`
4141 // Amount of randomness injected into the response.
4142 //
4143 // Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
4144 // for analytical / multiple choice, and closer to `1.0` for creative and
4145 // generative tasks.
4146 //
4147 // Note that even with `temperature` of `0.0`, the results will not be fully
4148 // deterministic.
4149 Temperature param.Opt[float64] `json:"temperature,omitzero"`
4150 // Only sample from the top K options for each subsequent token.
4151 //
4152 // Used to remove "long tail" low probability responses.
4153 // [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
4154 //
4155 // Recommended for advanced use cases only. You usually only need to use
4156 // `temperature`.
4157 TopK param.Opt[int64] `json:"top_k,omitzero"`
4158 // Use nucleus sampling.
4159 //
4160 // In nucleus sampling, we compute the cumulative distribution over all the options
4161 // for each subsequent token in decreasing probability order and cut it off once it
4162 // reaches a particular probability specified by `top_p`. You should either alter
4163 // `temperature` or `top_p`, but not both.
4164 //
4165 // Recommended for advanced use cases only. You usually only need to use
4166 // `temperature`.
4167 TopP param.Opt[float64] `json:"top_p,omitzero"`
4168 // An object describing metadata about the request.
4169 Metadata MetadataParam `json:"metadata,omitzero"`
4170 // Determines whether to use priority capacity (if available) or standard capacity
4171 // for this request.
4172 //
4173 // Anthropic offers different levels of service for your API requests. See
4174 // [service-tiers](https://docs.anthropic.com/en/api/service-tiers) for details.
4175 //
4176 // Any of "auto", "standard_only".
4177 ServiceTier MessageNewParamsServiceTier `json:"service_tier,omitzero"`
4178 // Custom text sequences that will cause the model to stop generating.
4179 //
4180 // Our models will normally stop when they have naturally completed their turn,
4181 // which will result in a response `stop_reason` of `"end_turn"`.
4182 //
4183 // If you want the model to stop generating when it encounters custom strings of
4184 // text, you can use the `stop_sequences` parameter. If the model encounters one of
4185 // the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
4186 // and the response `stop_sequence` value will contain the matched stop sequence.
4187 StopSequences []string `json:"stop_sequences,omitzero"`
4188 // System prompt.
4189 //
4190 // A system prompt is a way of providing context and instructions to Claude, such
4191 // as specifying a particular goal or role. See our
4192 // [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).
4193 System []TextBlockParam `json:"system,omitzero"`
4194 // Configuration for enabling Claude's extended thinking.
4195 //
4196 // When enabled, responses include `thinking` content blocks showing Claude's
4197 // thinking process before the final answer. Requires a minimum budget of 1,024
4198 // tokens and counts towards your `max_tokens` limit.
4199 //
4200 // See
4201 // [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)
4202 // for details.
4203 Thinking ThinkingConfigParamUnion `json:"thinking,omitzero"`
4204 // How the model should use the provided tools. The model can use a specific tool,
4205 // any available tool, decide by itself, or not use tools at all.
4206 ToolChoice ToolChoiceUnionParam `json:"tool_choice,omitzero"`
4207 // Definitions of tools that the model may use.
4208 //
4209 // If you include `tools` in your API request, the model may return `tool_use`
4210 // content blocks that represent the model's use of those tools. You can then run
4211 // those tools using the tool input generated by the model and then optionally
4212 // return results back to the model using `tool_result` content blocks.
4213 //
4214 // Each tool definition includes:
4215 //
4216 // - `name`: Name of the tool.
4217 // - `description`: Optional, but strongly-recommended description of the tool.
4218 // - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
4219 // tool `input` shape that the model will produce in `tool_use` output content
4220 // blocks.
4221 //
4222 // For example, if you defined `tools` as:
4223 //
4224 // ```json
4225 // [
4226 //
4227 // {
4228 // "name": "get_stock_price",
4229 // "description": "Get the current stock price for a given ticker symbol.",
4230 // "input_schema": {
4231 // "type": "object",
4232 // "properties": {
4233 // "ticker": {
4234 // "type": "string",
4235 // "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
4236 // }
4237 // },
4238 // "required": ["ticker"]
4239 // }
4240 // }
4241 //
4242 // ]
4243 // ```
4244 //
4245 // And then asked the model "What's the S&P 500 at today?", the model might produce
4246 // `tool_use` content blocks in the response like this:
4247 //
4248 // ```json
4249 // [
4250 //
4251 // {
4252 // "type": "tool_use",
4253 // "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
4254 // "name": "get_stock_price",
4255 // "input": { "ticker": "^GSPC" }
4256 // }
4257 //
4258 // ]
4259 // ```
4260 //
4261 // You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
4262 // input, and return the following back to the model in a subsequent `user`
4263 // message:
4264 //
4265 // ```json
4266 // [
4267 //
4268 // {
4269 // "type": "tool_result",
4270 // "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
4271 // "content": "259.75 USD"
4272 // }
4273 //
4274 // ]
4275 // ```
4276 //
4277 // Tools can be used for workflows that include running client-side tools and
4278 // functions, or more generally whenever you want the model to produce a particular
4279 // JSON structure of output.
4280 //
4281 // See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.
4282 Tools []ToolUnionParam `json:"tools,omitzero"`
4283 paramObj
4284}
4285
4286func (r MessageNewParams) MarshalJSON() (data []byte, err error) {
4287 type shadow MessageNewParams
4288 return param.MarshalObject(r, (*shadow)(&r))
4289}
4290func (r *MessageNewParams) UnmarshalJSON(data []byte) error {
4291 return apijson.UnmarshalRoot(data, r)
4292}
4293
4294// Determines whether to use priority capacity (if available) or standard capacity
4295// for this request.
4296//
4297// Anthropic offers different levels of service for your API requests. See
4298// [service-tiers](https://docs.anthropic.com/en/api/service-tiers) for details.
4299type MessageNewParamsServiceTier string
4300
4301const (
4302 MessageNewParamsServiceTierAuto MessageNewParamsServiceTier = "auto"
4303 MessageNewParamsServiceTierStandardOnly MessageNewParamsServiceTier = "standard_only"
4304)
4305
4306type MessageCountTokensParams struct {
4307 // Input messages.
4308 //
4309 // Our models are trained to operate on alternating `user` and `assistant`
4310 // conversational turns. When creating a new `Message`, you specify the prior
4311 // conversational turns with the `messages` parameter, and the model then generates
4312 // the next `Message` in the conversation. Consecutive `user` or `assistant` turns
4313 // in your request will be combined into a single turn.
4314 //
4315 // Each input message must be an object with a `role` and `content`. You can
4316 // specify a single `user`-role message, or you can include multiple `user` and
4317 // `assistant` messages.
4318 //
4319 // If the final message uses the `assistant` role, the response content will
4320 // continue immediately from the content in that message. This can be used to
4321 // constrain part of the model's response.
4322 //
4323 // Example with a single `user` message:
4324 //
4325 // ```json
4326 // [{ "role": "user", "content": "Hello, Claude" }]
4327 // ```
4328 //
4329 // Example with multiple conversational turns:
4330 //
4331 // ```json
4332 // [
4333 //
4334 // { "role": "user", "content": "Hello there." },
4335 // { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
4336 // { "role": "user", "content": "Can you explain LLMs in plain English?" }
4337 //
4338 // ]
4339 // ```
4340 //
4341 // Example with a partially-filled response from Claude:
4342 //
4343 // ```json
4344 // [
4345 //
4346 // {
4347 // "role": "user",
4348 // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
4349 // },
4350 // { "role": "assistant", "content": "The best answer is (" }
4351 //
4352 // ]
4353 // ```
4354 //
4355 // Each input message `content` may be either a single `string` or an array of
4356 // content blocks, where each block has a specific `type`. Using a `string` for
4357 // `content` is shorthand for an array of one content block of type `"text"`. The
4358 // following input messages are equivalent:
4359 //
4360 // ```json
4361 // { "role": "user", "content": "Hello, Claude" }
4362 // ```
4363 //
4364 // ```json
4365 // { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
4366 // ```
4367 //
4368 // Starting with Claude 3 models, you can also send image content blocks:
4369 //
4370 // ```json
4371 //
4372 // {
4373 // "role": "user",
4374 // "content": [
4375 // {
4376 // "type": "image",
4377 // "source": {
4378 // "type": "base64",
4379 // "media_type": "image/jpeg",
4380 // "data": "/9j/4AAQSkZJRg..."
4381 // }
4382 // },
4383 // { "type": "text", "text": "What is in this image?" }
4384 // ]
4385 // }
4386 //
4387 // ```
4388 //
4389 // We currently support the `base64` source type for images, and the `image/jpeg`,
4390 // `image/png`, `image/gif`, and `image/webp` media types.
4391 //
4392 // See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for
4393 // more input examples.
4394 //
4395 // Note that if you want to include a
4396 // [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
4397 // the top-level `system` parameter — there is no `"system"` role for input
4398 // messages in the Messages API.
4399 //
4400 // There is a limit of 100000 messages in a single request.
4401 Messages []MessageParam `json:"messages,omitzero,required"`
4402 // The model that will complete your prompt.\n\nSee
4403 // [models](https://docs.anthropic.com/en/docs/models-overview) for additional
4404 // details and options.
4405 Model Model `json:"model,omitzero,required"`
4406 // System prompt.
4407 //
4408 // A system prompt is a way of providing context and instructions to Claude, such
4409 // as specifying a particular goal or role. See our
4410 // [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).
4411 System MessageCountTokensParamsSystemUnion `json:"system,omitzero"`
4412 // Configuration for enabling Claude's extended thinking.
4413 //
4414 // When enabled, responses include `thinking` content blocks showing Claude's
4415 // thinking process before the final answer. Requires a minimum budget of 1,024
4416 // tokens and counts towards your `max_tokens` limit.
4417 //
4418 // See
4419 // [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)
4420 // for details.
4421 Thinking ThinkingConfigParamUnion `json:"thinking,omitzero"`
4422 // How the model should use the provided tools. The model can use a specific tool,
4423 // any available tool, decide by itself, or not use tools at all.
4424 ToolChoice ToolChoiceUnionParam `json:"tool_choice,omitzero"`
4425 // Definitions of tools that the model may use.
4426 //
4427 // If you include `tools` in your API request, the model may return `tool_use`
4428 // content blocks that represent the model's use of those tools. You can then run
4429 // those tools using the tool input generated by the model and then optionally
4430 // return results back to the model using `tool_result` content blocks.
4431 //
4432 // Each tool definition includes:
4433 //
4434 // - `name`: Name of the tool.
4435 // - `description`: Optional, but strongly-recommended description of the tool.
4436 // - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
4437 // tool `input` shape that the model will produce in `tool_use` output content
4438 // blocks.
4439 //
4440 // For example, if you defined `tools` as:
4441 //
4442 // ```json
4443 // [
4444 //
4445 // {
4446 // "name": "get_stock_price",
4447 // "description": "Get the current stock price for a given ticker symbol.",
4448 // "input_schema": {
4449 // "type": "object",
4450 // "properties": {
4451 // "ticker": {
4452 // "type": "string",
4453 // "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
4454 // }
4455 // },
4456 // "required": ["ticker"]
4457 // }
4458 // }
4459 //
4460 // ]
4461 // ```
4462 //
4463 // And then asked the model "What's the S&P 500 at today?", the model might produce
4464 // `tool_use` content blocks in the response like this:
4465 //
4466 // ```json
4467 // [
4468 //
4469 // {
4470 // "type": "tool_use",
4471 // "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
4472 // "name": "get_stock_price",
4473 // "input": { "ticker": "^GSPC" }
4474 // }
4475 //
4476 // ]
4477 // ```
4478 //
4479 // You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
4480 // input, and return the following back to the model in a subsequent `user`
4481 // message:
4482 //
4483 // ```json
4484 // [
4485 //
4486 // {
4487 // "type": "tool_result",
4488 // "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
4489 // "content": "259.75 USD"
4490 // }
4491 //
4492 // ]
4493 // ```
4494 //
4495 // Tools can be used for workflows that include running client-side tools and
4496 // functions, or more generally whenever you want the model to produce a particular
4497 // JSON structure of output.
4498 //
4499 // See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.
4500 Tools []MessageCountTokensToolUnionParam `json:"tools,omitzero"`
4501 paramObj
4502}
4503
4504func (r MessageCountTokensParams) MarshalJSON() (data []byte, err error) {
4505 type shadow MessageCountTokensParams
4506 return param.MarshalObject(r, (*shadow)(&r))
4507}
4508func (r *MessageCountTokensParams) UnmarshalJSON(data []byte) error {
4509 return apijson.UnmarshalRoot(data, r)
4510}
4511
4512// Only one field can be non-zero.
4513//
4514// Use [param.IsOmitted] to confirm if a field is set.
4515type MessageCountTokensParamsSystemUnion struct {
4516 OfString param.Opt[string] `json:",omitzero,inline"`
4517 OfTextBlockArray []TextBlockParam `json:",omitzero,inline"`
4518 paramUnion
4519}
4520
4521func (u MessageCountTokensParamsSystemUnion) MarshalJSON() ([]byte, error) {
4522 return param.MarshalUnion(u, u.OfString, u.OfTextBlockArray)
4523}
4524func (u *MessageCountTokensParamsSystemUnion) UnmarshalJSON(data []byte) error {
4525 return apijson.UnmarshalRoot(data, u)
4526}
4527
4528func (u *MessageCountTokensParamsSystemUnion) asAny() any {
4529 if !param.IsOmitted(u.OfString) {
4530 return &u.OfString.Value
4531 } else if !param.IsOmitted(u.OfTextBlockArray) {
4532 return &u.OfTextBlockArray
4533 }
4534 return nil
4535}
4536
4537// CalculateNonStreamingTimeout calculates the appropriate timeout for a non-streaming request
4538// based on the maximum number of tokens and the model's non-streaming token limit
4539func CalculateNonStreamingTimeout(maxTokens int, model Model, opts []option.RequestOption) (time.Duration, error) {
4540 preCfg, err := requestconfig.PreRequestOptions(opts...)
4541 if err != nil {
4542 return 0, fmt.Errorf("error applying request options: %w", err)
4543 }
4544 // if the user has set a specific request timeout, use that
4545 if preCfg.RequestTimeout != 0 {
4546 return preCfg.RequestTimeout, nil
4547 }
4548
4549 maximumTime := 60 * 60 * time.Second
4550 defaultTime := 60 * 10 * time.Second
4551
4552 expectedTime := time.Duration(float64(maximumTime) * float64(maxTokens) / 128000.0)
4553
4554 // If the model has a non-streaming token limit and max_tokens exceeds it,
4555 // or if the expected time exceeds default time, recommend streaming
4556 maxNonStreamingTokens, hasLimit := constant.ModelNonStreamingTokens[string(model)]
4557 if expectedTime > defaultTime || (hasLimit && maxTokens > maxNonStreamingTokens) {
4558 return 0, fmt.Errorf("streaming is strongly recommended for operations that may take longer than 10 minutes")
4559 }
4560
4561 return expectedTime, nil
4562}