-
Notifications
You must be signed in to change notification settings - Fork 608
/
AnthropicApi.java
914 lines (752 loc) · 28.8 KB
/
AnthropicApi.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.anthropic.api;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.springframework.ai.anthropic.api.StreamHelper.ChatCompletionResponseBuilder;
import org.springframework.ai.model.ModelDescription;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.WebClient;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* @author Christian Tzolov
* @author Mariusz Bernacki
* @since 1.0.0
*/
public class AnthropicApi {
private static final String HEADER_X_API_KEY = "x-api-key";
private static final String HEADER_ANTHROPIC_VERSION = "anthropic-version";
private static final String HEADER_ANTHROPIC_BETA = "anthropic-beta";
public static final String DEFAULT_BASE_URL = "https://api.anthropic.com";
public static final String DEFAULT_ANTHROPIC_VERSION = "2023-06-01";
public static final String DEFAULT_ANTHROPIC_BETA_VERSION = "tools-2024-04-04";
private static final Predicate<String> SSE_DONE_PREDICATE = "[DONE]"::equals;
private final RestClient restClient;
private WebClient webClient;
/**
* Create a new client api with DEFAULT_BASE_URL
* @param anthropicApiKey Anthropic api Key.
*/
public AnthropicApi(String anthropicApiKey) {
this(DEFAULT_BASE_URL, anthropicApiKey);
}
/**
* Create a new client api.
* @param baseUrl api base URL.
* @param anthropicApiKey Anthropic api Key.
*/
public AnthropicApi(String baseUrl, String anthropicApiKey) {
this(baseUrl, anthropicApiKey, DEFAULT_ANTHROPIC_VERSION, RestClient.builder(),
RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER);
}
/**
* Create a new client api.
* @param baseUrl api base URL.
* @param anthropicApiKey Anthropic api Key.
* @param restClientBuilder RestClient builder.
* @param responseErrorHandler Response error handler.
*/
public AnthropicApi(String baseUrl, String anthropicApiKey, String anthropicVersion,
RestClient.Builder restClientBuilder, ResponseErrorHandler responseErrorHandler) {
Consumer<HttpHeaders> jsonContentHeaders = headers -> {
headers.add(HEADER_X_API_KEY, anthropicApiKey);
headers.add(HEADER_ANTHROPIC_VERSION, anthropicVersion);
headers.add(HEADER_ANTHROPIC_BETA, DEFAULT_ANTHROPIC_BETA_VERSION);
headers.setContentType(MediaType.APPLICATION_JSON);
};
this.restClient = restClientBuilder.baseUrl(baseUrl)
.defaultHeaders(jsonContentHeaders)
.defaultStatusHandler(responseErrorHandler)
.build();
this.webClient = WebClient.builder()
.baseUrl(baseUrl)
.defaultHeaders(jsonContentHeaders)
.defaultStatusHandler(HttpStatusCode::isError,
resp -> Mono.just(new RuntimeException("Response exception, Status: [" + resp.statusCode()
+ "], Body:[" + resp.bodyToMono(java.lang.String.class) + "]")))
.build();
}
/**
* Check the <a href="https://docs.anthropic.com/claude/docs/models-overview">Models
* overview</a> and <a href=
* "https://docs.anthropic.com/claude/docs/models-overview#model-comparison">model
* comparison</a> for additional details and options.
*/
public enum ChatModel implements ModelDescription {
// @formatter:off
CLAUDE_3_5_SONNET("claude-3-5-sonnet-20240620"),
CLAUDE_3_OPUS("claude-3-opus-20240229"),
CLAUDE_3_SONNET("claude-3-sonnet-20240229"),
CLAUDE_3_HAIKU("claude-3-haiku-20240307"),
// Legacy models
CLAUDE_2_1("claude-2.1"),
CLAUDE_2("claude-2.0"),
CLAUDE_INSTANT_1_2("claude-instant-1.2");
// @formatter:on
public final String value;
ChatModel(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
@Override
public String getModelName() {
return this.value;
}
}
/**
* The role of the author of this message.
*/
public enum Role {
// @formatter:off
@JsonProperty("user") USER,
@JsonProperty("assistant") ASSISTANT
// @formatter:on
}
/**
* @param model The model that will complete your prompt. See the list of
* <a href="https://docs.anthropic.com/claude/docs/models-overview">models</a> for
* additional details and options.
* @param messages Input messages.
* @param system System prompt. A system prompt is a way of providing context and
* instructions to Claude, such as specifying a particular goal or role. See our
* <a href="https://docs.anthropic.com/claude/docs/system-prompts">guide</a> to system
* prompts.
* @param maxTokens The maximum number of tokens to generate before stopping. Note
* that our models may stop before reaching this maximum. This parameter only
* specifies the absolute maximum number of tokens to generate. Different models have
* different maximum values for this parameter.
* @param metadata An object describing metadata about the request.
* @param stopSequences Custom text sequences that will cause the model to stop
* generating. Our models will normally stop when they have naturally completed their
* turn, which will result in a response stop_reason of "end_turn". If you want the
* model to stop generating when it encounters custom strings of text, you can use the
* stop_sequences parameter. If the model encounters one of the custom sequences, the
* response stop_reason value will be "stop_sequence" and the response stop_sequence
* value will contain the matched stop sequence.
* @param stream Whether to incrementally stream the response using server-sent
* events.
* @param temperature Amount of randomness injected into the response.Defaults to 1.0.
* Ranges from 0.0 to 1.0. Use temperature closer to 0.0 for analytical / multiple
* choice, and closer to 1.0 for creative and generative tasks. Note that even with
* temperature of 0.0, the results will not be fully deterministic.
* @param topP Use nucleus sampling. In nucleus sampling, we compute the cumulative
* distribution over all the options for each subsequent token in decreasing
* probability order and cut it off once it reaches a particular probability specified
* by top_p. You should either alter temperature or top_p, but not both. Recommended
* for advanced use cases only. You usually only need to use temperature.
* @param topK Only sample from the top K options for each subsequent token. Used to
* remove "long tail" low probability responses. Learn more technical details here.
* Recommended for advanced use cases only. You usually only need to use temperature.
* @param tools Definitions of tools that the model may use. If provided the model may
* return tool_use content blocks that represent the model's use of those tools. You
* can then run those tools using the tool input generated by the model and then
* optionally return results back to the model using tool_result content blocks.
*/
@JsonInclude(Include.NON_NULL)
public record ChatCompletionRequest( // @formatter:off
@JsonProperty("model") String model,
@JsonProperty("messages") List<AnthropicMessage> messages,
@JsonProperty("system") String system,
@JsonProperty("max_tokens") Integer maxTokens,
@JsonProperty("metadata") Metadata metadata,
@JsonProperty("stop_sequences") List<String> stopSequences,
@JsonProperty("stream") Boolean stream,
@JsonProperty("temperature") Float temperature,
@JsonProperty("top_p") Float topP,
@JsonProperty("top_k") Integer topK,
@JsonProperty("tools") List<Tool> tools) {
// @formatter:on
public ChatCompletionRequest(String model, List<AnthropicMessage> messages, String system, Integer maxTokens,
Float temperature, Boolean stream) {
this(model, messages, system, maxTokens, null, null, stream, temperature, null, null, null);
}
public ChatCompletionRequest(String model, List<AnthropicMessage> messages, String system, Integer maxTokens,
List<String> stopSequences, Float temperature, Boolean stream) {
this(model, messages, system, maxTokens, null, stopSequences, stream, temperature, null, null, null);
}
/**
* @param userId An external identifier for the user who is associated with the
* request. This should be a uuid, hash value, or other opaque identifier.
* Anthropic may use this id to help detect abuse. Do not include any identifying
* information such as name, email address, or phone number.
*/
@JsonInclude(Include.NON_NULL)
public record Metadata(@JsonProperty("user_id") String userId) {
}
public static ChatCompletionRequestBuilder builder() {
return new ChatCompletionRequestBuilder();
}
public static ChatCompletionRequestBuilder from(ChatCompletionRequest request) {
return new ChatCompletionRequestBuilder(request);
}
}
public static class ChatCompletionRequestBuilder {
private String model;
private List<AnthropicMessage> messages;
private String system;
private Integer maxTokens;
private ChatCompletionRequest.Metadata metadata;
private List<String> stopSequences;
private Boolean stream = false;
private Float temperature;
private Float topP;
private Integer topK;
private List<Tool> tools;
private ChatCompletionRequestBuilder() {
}
private ChatCompletionRequestBuilder(ChatCompletionRequest request) {
this.model = request.model;
this.messages = request.messages;
this.system = request.system;
this.maxTokens = request.maxTokens;
this.metadata = request.metadata;
this.stopSequences = request.stopSequences;
this.stream = request.stream;
this.temperature = request.temperature;
this.topP = request.topP;
this.topK = request.topK;
this.tools = request.tools;
}
public ChatCompletionRequestBuilder withModel(ChatModel model) {
this.model = model.getValue();
return this;
}
public ChatCompletionRequestBuilder withModel(String model) {
this.model = model;
return this;
}
public ChatCompletionRequestBuilder withMessages(List<AnthropicMessage> messages) {
this.messages = messages;
return this;
}
public ChatCompletionRequestBuilder withSystem(String system) {
this.system = system;
return this;
}
public ChatCompletionRequestBuilder withMaxTokens(Integer maxTokens) {
this.maxTokens = maxTokens;
return this;
}
public ChatCompletionRequestBuilder withMetadata(ChatCompletionRequest.Metadata metadata) {
this.metadata = metadata;
return this;
}
public ChatCompletionRequestBuilder withStopSequences(List<String> stopSequences) {
this.stopSequences = stopSequences;
return this;
}
public ChatCompletionRequestBuilder withStream(Boolean stream) {
this.stream = stream;
return this;
}
public ChatCompletionRequestBuilder withTemperature(Float temperature) {
this.temperature = temperature;
return this;
}
public ChatCompletionRequestBuilder withTopP(Float topP) {
this.topP = topP;
return this;
}
public ChatCompletionRequestBuilder withTopK(Integer topK) {
this.topK = topK;
return this;
}
public ChatCompletionRequestBuilder withTools(List<Tool> tools) {
this.tools = tools;
return this;
}
public ChatCompletionRequest build() {
return new ChatCompletionRequest(model, messages, system, maxTokens, metadata, stopSequences, stream,
temperature, topP, topK, tools);
}
}
/**
* Input messages.
*
* Our models are trained to operate on alternating user and assistant conversational
* turns. When creating a new Message, you specify the prior conversational turns with
* the messages parameter, and the model then generates the next Message in the
* conversation. Each input message must be an object with a role and content. You can
* specify a single user-role message, or you can include multiple user and assistant
* messages. The first message must always use the user role. If the final message
* uses the assistant role, the response content will continue immediately from the
* content in that message. This can be used to constrain part of the model's
* response.
*
* @param content The contents of the message. Can be of one of String or
* MultiModalContent.
* @param role The role of the messages author. Could be one of the {@link Role}
* types.
*/
@JsonInclude(Include.NON_NULL)
public record AnthropicMessage( // @formatter:off
@JsonProperty("content") List<ContentBlock> content,
@JsonProperty("role") Role role) {
// @formatter:on
}
/**
* @param type the content type can be "text", "image", "tool_use", "tool_result" or
* "text_delta".
* @param source The source of the media content. Applicable for "image" types only.
* @param text The text of the message. Applicable for "text" types only.
* @param index The index of the content block. Applicable only for streaming
* responses.
*/
@JsonInclude(Include.NON_NULL)
public record ContentBlock( // @formatter:off
@JsonProperty("type") ContentBlockType type,
@JsonProperty("source") Source source,
@JsonProperty("text") String text,
// applicable only for streaming responses.
@JsonProperty("index") Integer index,
// tool_use response only
@JsonProperty("id") String id,
@JsonProperty("name") String name,
@JsonProperty("input") Map<String, Object> input,
// tool_result response only
@JsonProperty("tool_use_id") String toolUseId,
@JsonProperty("content") String content
) {
// @formatter:on
public ContentBlock(String mediaType, String data) {
this(new Source(mediaType, data));
}
public ContentBlock(Source source) {
this(ContentBlockType.IMAGE, source, null, null, null, null, null, null, null);
}
public ContentBlock(String text) {
this(ContentBlockType.TEXT, null, text, null, null, null, null, null, null);
}
// Tool result
public ContentBlock(ContentBlockType type, String toolUseId, String content) {
this(type, null, null, null, null, null, null, toolUseId, content);
}
public ContentBlock(ContentBlockType type, Source source, String text, Integer index) {
this(type, source, text, index, null, null, null, null, null);
}
// Tool use input JSON delta streaming
public ContentBlock(ContentBlockType type, String id, String name, Map<String, Object> input) {
this(type, null, null, null, id, name, input, null, null);
}
/**
* The type of this message.
*/
public enum ContentBlockType {
/**
* Tool request
*/
@JsonProperty("tool_use")
TOOL_USE,
/**
* Send tool result back to LLM.
*/
@JsonProperty("tool_result")
TOOL_RESULT,
/**
* Text message.
*/
@JsonProperty("text")
TEXT,
/**
* Text delta message. Returned from the streaming response.
*/
@JsonProperty("text_delta")
TEXT_DELTA,
/**
* Tool use input partial JSON delta streaming.
*/
@JsonProperty("input_json_delta")
INPUT_JSON_DELTA,
/**
* Image message.
*/
@JsonProperty("image")
IMAGE;
}
/**
* The source of the media content. (Applicable for "image" types only)
*
* @param type The type of the media content. Only "base64" is supported at the
* moment.
* @param mediaType The media type of the content. For example, "image/png" or
* "image/jpeg".
* @param data The base64-encoded data of the content.
*/
@JsonInclude(Include.NON_NULL)
public record Source( // @formatter:off
@JsonProperty("type") String type,
@JsonProperty("media_type") String mediaType,
@JsonProperty("data") String data) {
// @formatter:on
public Source(String mediaType, String data) {
this("base64", mediaType, data);
}
}
}
@JsonInclude(Include.NON_NULL)
public record Tool(// @formatter:off
@JsonProperty("name") String name,
@JsonProperty("description") String description,
@JsonProperty("input_schema") Map<String, Object> inputSchema) {
// @formatter:on
}
/**
* @param id Unique object identifier. The format and length of IDs may change over
* time.
* @param type Object type. For Messages, this is always "message".
* @param role Conversational role of the generated message. This will always be
* "assistant".
* @param content Content generated by the model. This is an array of content blocks.
* @param model The model that handled the request.
* @param stopReason The reason the model stopped generating tokens. This will be one
* of "end_turn", "max_tokens", "stop_sequence", "tool_use", or "timeout".
* @param stopSequence Which custom stop sequence was generated, if any.
* @param usage Input and output token usage.
*/
@JsonInclude(Include.NON_NULL)
public record ChatCompletionResponse( // @formatter:off
@JsonProperty("id") String id,
@JsonProperty("type") String type,
@JsonProperty("role") Role role,
@JsonProperty("content") List<ContentBlock> content,
@JsonProperty("model") String model,
@JsonProperty("stop_reason") String stopReason,
@JsonProperty("stop_sequence") String stopSequence,
@JsonProperty("usage") Usage usage) {
// @formatter:on
}
/**
* Usage statistics.
*
* @param inputTokens The number of input tokens which were used.
* @param outputTokens The number of output tokens which were used. completion).
*/
@JsonInclude(Include.NON_NULL)
public record Usage( // @formatter:off
@JsonProperty("input_tokens") Integer inputTokens,
@JsonProperty("output_tokens") Integer outputTokens) {
// @formatter:off
}
///////////////////////////////////////
/// ERROR EVENT
///////////////////////////////////////
/**
* The evnt type of the streamed chunk.
*/
public enum EventType {
/**
* Message start event. Contains a Message object with empty content.
*/
@JsonProperty("message_start")
MESSAGE_START,
/**
* Message delta event, indicating top-level changes to the final Message object.
*/
@JsonProperty("message_delta")
MESSAGE_DELTA,
/**
* A final message stop event.
*/
@JsonProperty("message_stop")
MESSAGE_STOP,
/**
*
*/
@JsonProperty("content_block_start")
CONTENT_BLOCK_START,
/**
*
*/
@JsonProperty("content_block_delta")
CONTENT_BLOCK_DELTA,
/**
*
*/
@JsonProperty("content_block_stop")
CONTENT_BLOCK_STOP,
/**
*
*/
@JsonProperty("error")
ERROR,
/**
*
*/
@JsonProperty("ping")
PING,
/**
* Artifically created event to aggregate tool use events.
*/
TOOL_USE_AGGREATE;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type",
visible = true)
@JsonSubTypes({ @JsonSubTypes.Type(value = ContentBlockStartEvent.class, name = "content_block_start"),
@JsonSubTypes.Type(value = ContentBlockDeltaEvent.class, name = "content_block_delta"),
@JsonSubTypes.Type(value = ContentBlockStopEvent.class, name = "content_block_stop"),
@JsonSubTypes.Type(value = PingEvent.class, name = "ping"),
@JsonSubTypes.Type(value = ErrorEvent.class, name = "error"),
@JsonSubTypes.Type(value = MessageStartEvent.class, name = "message_start"),
@JsonSubTypes.Type(value = MessageDeltaEvent.class, name = "message_delta"),
@JsonSubTypes.Type(value = MessageStopEvent.class, name = "message_stop") })
public interface StreamEvent {
@JsonProperty("type")
EventType type();
}
///////////////////////////////////////
/// CONTENT_BLOCK EVENTS
///////////////////////////////////////
/**
* Special event used to aggregate multiple tool use events into a single event with
* list of aggregated ContentBlockToolUse.
*/
public static class ToolUseAggregationEvent implements StreamEvent {
private Integer index;
private String id;
private String name;
private String partialJson = "";
private List<ContentBlockStartEvent.ContentBlockToolUse> toolContentBlocks = new ArrayList<>();
@Override
public EventType type() {
return EventType.TOOL_USE_AGGREATE;
}
public List<ContentBlockStartEvent.ContentBlockToolUse> getToolContentBlocks() {
return this.toolContentBlocks;
}
public boolean isEmpty() {
return (this.index == null || this.id == null || this.name == null
|| !StringUtils.hasText(this.partialJson));
}
ToolUseAggregationEvent withIndex(Integer index) {
this.index = index;
return this;
}
ToolUseAggregationEvent withId(String id) {
this.id = id;
return this;
}
ToolUseAggregationEvent withName(String name) {
this.name = name;
return this;
}
ToolUseAggregationEvent appendPartialJson(String partialJson) {
this.partialJson = this.partialJson + partialJson;
return this;
}
void squashIntoContentBlock() {
Map<String, Object> map = (StringUtils.hasText(this.partialJson))
? ModelOptionsUtils.jsonToMap(this.partialJson) : Map.of();
this.toolContentBlocks.add(new ContentBlockStartEvent.ContentBlockToolUse("tool_use", this.id, this.name, map));
this.index = null;
this.id = null;
this.name = null;
this.partialJson = "";
}
@Override
public String toString() {
return "EventToolUseBuilder [index=" + index + ", id=" + id + ", name=" + name + ", partialJson="
+ partialJson + ", toolUseMap=" + toolContentBlocks + "]";
}
}
// CB START EVENT
@JsonInclude(Include.NON_NULL)
public record ContentBlockStartEvent(// @formatter:off
@JsonProperty("type") EventType type,
@JsonProperty("index") Integer index,
@JsonProperty("content_block") ContentBlockBody contentBlock) implements StreamEvent {
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type",
visible = true)
@JsonSubTypes({ @JsonSubTypes.Type(value = ContentBlockToolUse.class, name = "tool_use"),
@JsonSubTypes.Type(value = ContentBlockText.class, name = "text") })
public interface ContentBlockBody {
String type();
}
@JsonInclude(Include.NON_NULL)
public record ContentBlockToolUse(
@JsonProperty("type") String type,
@JsonProperty("id") String id,
@JsonProperty("name") String name,
@JsonProperty("input") Map<String, Object> input) implements ContentBlockBody {
}
@JsonInclude(Include.NON_NULL)
public record ContentBlockText(
@JsonProperty("type") String type,
@JsonProperty("text") String text) implements ContentBlockBody {
}
}// @formatter:on
// CB DELTA EVENT
@JsonInclude(Include.NON_NULL)
public record ContentBlockDeltaEvent(// @formatter:off
@JsonProperty("type") EventType type,
@JsonProperty("index") Integer index,
@JsonProperty("delta") ContentBlockDeltaBody delta) implements StreamEvent {
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type",
visible = true)
@JsonSubTypes({ @JsonSubTypes.Type(value = ContentBlockDeltaText.class, name = "text_delta"),
@JsonSubTypes.Type(value = ContentBlockDeltaJson.class, name = "input_json_delta") })
public interface ContentBlockDeltaBody {
String type();
}
@JsonInclude(Include.NON_NULL)
public record ContentBlockDeltaText(
@JsonProperty("type") String type,
@JsonProperty("text") String text) implements ContentBlockDeltaBody {
}
@JsonInclude(Include.NON_NULL)
public record ContentBlockDeltaJson(
@JsonProperty("type") String type,
@JsonProperty("partial_json") String partialJson) implements ContentBlockDeltaBody {
}
}// @formatter:on
/// ECB STOP
@JsonInclude(Include.NON_NULL)
public record ContentBlockStopEvent(// @formatter:off
@JsonProperty("type") EventType type,
@JsonProperty("index") Integer index) implements StreamEvent {
}// @formatter:on
///////////////////////////////////////
/// MESSAGE EVENTS
///////////////////////////////////////
// MESSAGE START EVENT
@JsonInclude(Include.NON_NULL)
public record MessageStartEvent(// @formatter:off
@JsonProperty("type") EventType type,
@JsonProperty("message") ChatCompletionResponse message) implements StreamEvent {
}// @formatter:on
// MESSAGE DELTA EVENT
@JsonInclude(Include.NON_NULL)
public record MessageDeltaEvent(// @formatter:off
@JsonProperty("type") EventType type,
@JsonProperty("delta") MessageDelta delta,
@JsonProperty("usage") MessageDeltaUsage usage) implements StreamEvent {
@JsonInclude(Include.NON_NULL)
public record MessageDelta(
@JsonProperty("stop_reason") String stopReason,
@JsonProperty("stop_sequence") String stopSequence) {
}
@JsonInclude(Include.NON_NULL)
public record MessageDeltaUsage(
@JsonProperty("output_tokens") Integer outputTokens) {
}
}// @formatter:on
// MESSAGE STOP EVENT
@JsonInclude(Include.NON_NULL)
public record MessageStopEvent(// @formatter:off
@JsonProperty("type") EventType type) implements StreamEvent {
}// @formatter:on
///////////////////////////////////////
/// ERROR EVENT
///////////////////////////////////////
@JsonInclude(Include.NON_NULL)
public record ErrorEvent(// @formatter:off
@JsonProperty("type") EventType type,
@JsonProperty("error") Error error) implements StreamEvent {
@JsonInclude(Include.NON_NULL)
public record Error(
@JsonProperty("type") String type,
@JsonProperty("message") String message) {
}
}// @formatter:on
///////////////////////////////////////
/// PING EVENT
///////////////////////////////////////
@JsonInclude(Include.NON_NULL)
public record PingEvent(// @formatter:off
@JsonProperty("type") EventType type) implements StreamEvent {
}// @formatter:on
/**
* Creates a model response for the given chat conversation.
* @param chatRequest The chat completion request.
* @return Entity response with {@link ChatCompletionResponse} as a body and HTTP
* status code and headers.
*/
public ResponseEntity<ChatCompletionResponse> chatCompletionEntity(ChatCompletionRequest chatRequest) {
Assert.notNull(chatRequest, "The request body can not be null.");
Assert.isTrue(!chatRequest.stream(), "Request must set the steam property to false.");
return this.restClient.post()
.uri("/v1/messages")
.body(chatRequest)
.retrieve()
.toEntity(ChatCompletionResponse.class);
}
private final StreamHelper streamHelper = new StreamHelper();
/**
* Creates a streaming chat response for the given chat conversation.
* @param chatRequest The chat completion request. Must have the stream property set
* to true.
* @return Returns a {@link Flux} stream from chat completion chunks.
*/
public Flux<ChatCompletionResponse> chatCompletionStream(ChatCompletionRequest chatRequest) {
Assert.notNull(chatRequest, "The request body can not be null.");
Assert.isTrue(chatRequest.stream(), "Request must set the steam property to true.");
AtomicBoolean isInsideTool = new AtomicBoolean(false);
AtomicReference<ChatCompletionResponseBuilder> chatCompletionReference = new AtomicReference<>();
return this.webClient.post()
.uri("/v1/messages")
.body(Mono.just(chatRequest), ChatCompletionRequest.class)
.retrieve()
.bodyToFlux(String.class)
.takeUntil(SSE_DONE_PREDICATE)
.filter(SSE_DONE_PREDICATE.negate())
.map(content -> ModelOptionsUtils.jsonToObject(content, StreamEvent.class))
// Detect if the chunk is part of a streaming function call.
.map(event -> {
if (this.streamHelper.isToolUseStart(event)) {
isInsideTool.set(true);
}
return event;
})
// Group all chunks belonging to the same function call.
.windowUntil(event -> {
if (isInsideTool.get() && this.streamHelper.isToolUseFinish(event)) {
isInsideTool.set(false);
return true;
}
return !isInsideTool.get();
})
// Merging the window chunks into a single chunk.
.concatMapIterable(window -> {
Mono<StreamEvent> monoChunk = window.reduce(new ToolUseAggregationEvent(),
this.streamHelper::mergeToolUseEvents);
return List.of(monoChunk);
})
.flatMap(mono -> mono)
.map(event -> streamHelper.eventToChatCompletionResponse(event, chatCompletionReference))
.filter(chatCompletionResponse -> chatCompletionResponse.type() != null);
}
}