-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtypes.dart
More file actions
2128 lines (1884 loc) · 75.5 KB
/
Copy pathtypes.dart
File metadata and controls
2128 lines (1884 loc) · 75.5 KB
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// types.dart — typed models mirroring bindings/node/src/types/*.ts (ts-rs).
//
// Hand-written Dart classes with json_serializable. Field names are
// camelCase; `@JsonKey(name: ...)` maps to the snake_case wire format
// produced by the Rust core (serde). These wrap the raw
// `Map<String, dynamic>` boundary exposed by the dart:ffi binding in
// `aimux.dart`, so callers get compile-time types instead of dynamic maps.
//
// Wire shapes are derived from the Rust structs in aimux-core
// (`types.rs`, `tool.rs`, `generate.rs`, `result.rs`, `stream_part.rs`,
// `shared.rs`):
// - GenerateTextResult (generate.rs:90)
// - GenerateContent (result.rs) — sealed, externally-tagged
// - StreamPart (stream_part.rs) — sealed, externally-tagged
// - ContentPart (content.rs) — sealed, internally-tagged (type)
// - FileData/FileBytes (shared.rs) — sealed, externally-tagged
// - ToolCall (tool.rs:102)
// - Usage / TokenUsage (types.rs:33, types.rs:44)
// - FinishReason (types.rs:10)
import 'package:json_annotation/json_annotation.dart';
part 'types.g.dart';
// ─────────────────────────────────────────────────────────────────────────────
// Shared enums
// ─────────────────────────────────────────────────────────────────────────────
enum Role {
system('system'),
user('user'),
assistant('assistant'),
tool('tool');
const Role(this.wireValue);
final String wireValue;
static Role fromJson(String value) =>
Role.values.firstWhere((item) => item.wireValue == value);
String toJson() => wireValue;
}
enum FinishReasonUnified {
stop('stop'),
length('length'),
contentFilter('content-filter'),
toolCalls('tool-calls'),
error('error'),
other('other');
const FinishReasonUnified(this.wireValue);
final String wireValue;
static FinishReasonUnified fromJson(String value) =>
FinishReasonUnified.values.firstWhere((item) => item.wireValue == value);
String toJson() => wireValue;
}
enum ReasoningEffort {
providerDefault('provider-default'),
none('none'),
minimal('minimal'),
low('low'),
medium('medium'),
high('high'),
xhigh('xhigh');
const ReasoningEffort(this.wireValue);
final String wireValue;
static ReasoningEffort fromJson(String value) =>
ReasoningEffort.values.firstWhere((item) => item.wireValue == value);
String toJson() => wireValue;
}
// ─────────────────────────────────────────────────────────────────────────────
// Token usage
// ─────────────────────────────────────────────────────────────────────────────
/// Token usage detail (with cache breakdown). Mirrors `TokenUsage.ts`.
///
/// All fields are nullable: `total` is always serialized by the Rust core
/// (null when unknown), the rest are omitted when `None`.
@JsonSerializable()
class TokenUsage {
final int? total;
@JsonKey(name: 'no_cache')
final int? noCache;
@JsonKey(name: 'cache_read')
final int? cacheRead;
@JsonKey(name: 'cache_write')
final int? cacheWrite;
final int? text;
final int? reasoning;
TokenUsage({
this.total,
this.noCache,
this.cacheRead,
this.cacheWrite,
this.text,
this.reasoning,
});
factory TokenUsage.fromJson(Map<String, dynamic> json) =>
_$TokenUsageFromJson(json);
Map<String, dynamic> toJson() => _$TokenUsageToJson(this);
}
/// Token usage statistics. Mirrors `Usage.ts`.
@JsonSerializable()
class Usage {
@JsonKey(name: 'input_tokens')
final TokenUsage inputTokens;
@JsonKey(name: 'output_tokens')
final TokenUsage outputTokens;
/// Raw usage information from the provider (opaque JSON).
final Map<String, dynamic>? raw;
Usage({required this.inputTokens, required this.outputTokens, this.raw});
factory Usage.fromJson(Map<String, dynamic> json) => _$UsageFromJson(json);
Map<String, dynamic> toJson() => _$UsageToJson(this);
}
// ─────────────────────────────────────────────────────────────────────────────
// Finish reason
// ─────────────────────────────────────────────────────────────────────────────
/// Why generation stopped. Mirrors `FinishReason.ts`.
///
/// `unified` is the kebab-case unified reason (`"stop"`, `"length"`,
/// `"content-filter"`, `"tool-calls"`, `"error"`, `"other"`); `raw` is the
/// provider-specific reason string (nullable).
@JsonSerializable()
class FinishReason {
final String unified;
final String? raw;
FinishReason({required this.unified, this.raw});
factory FinishReason.fromJson(Map<String, dynamic> json) =>
_$FinishReasonFromJson(json);
Map<String, dynamic> toJson() => _$FinishReasonToJson(this);
}
// ─────────────────────────────────────────────────────────────────────────────
// Tool calls
// ─────────────────────────────────────────────────────────────────────────────
/// A tool call requested by the model. Mirrors `ToolCall.ts`.
@JsonSerializable()
class ToolCall {
@JsonKey(name: 'tool_call_id')
final String toolCallId;
@JsonKey(name: 'tool_name')
final String toolName;
final dynamic input;
@JsonKey(name: 'provider_executed')
final bool? providerExecuted;
// `dynamic` is a Dart built-in identifier — field is named `isDynamic`
// and mapped to the `dynamic` JSON key.
@JsonKey(name: 'dynamic')
final bool? isDynamic;
@JsonKey(name: 'thought_signature')
final String? thoughtSignature;
ToolCall({
required this.toolCallId,
required this.toolName,
required this.input,
this.providerExecuted,
this.isDynamic,
this.thoughtSignature,
});
factory ToolCall.fromJson(Map<String, dynamic> json) =>
_$ToolCallFromJson(json);
Map<String, dynamic> toJson() => _$ToolCallToJson(this);
}
// ─────────────────────────────────────────────────────────────────────────────
// Tools
// ─────────────────────────────────────────────────────────────────────────────
/// A function tool definition. Mirrors `FunctionTool.ts`.
@JsonSerializable()
class FunctionTool {
final String name;
final String? description;
@JsonKey(name: 'input_schema')
final Map<String, dynamic> inputSchema;
final bool? strict;
@JsonKey(name: 'provider_options')
final Map<String, dynamic>? providerOptions;
@JsonKey(name: 'input_examples')
final List<Map<String, dynamic>>? inputExamples;
FunctionTool({
required this.name,
this.description,
required this.inputSchema,
this.strict,
this.providerOptions,
this.inputExamples,
});
factory FunctionTool.fromJson(Map<String, dynamic> json) =>
_$FunctionToolFromJson(json);
Map<String, dynamic> toJson() => _$FunctionToolToJson(this);
}
/// A tool definition: function or provider tool. Mirrors `Tool.ts`.
class Tool {
final String type;
final FunctionTool? function;
final String? id;
final String? name;
final Map<String, dynamic>? args;
Tool._({required this.type, this.function, this.id, this.name, this.args});
factory Tool.function(FunctionTool fn) =>
Tool._(type: 'function', function: fn);
factory Tool.provider({required String id, required String name, required Map<String, dynamic> args}) =>
Tool._(type: 'provider', id: id, name: name, args: args);
Map<String, dynamic> toJson() {
if (function != null) return {'type': 'function', ...function!.toJson()};
return {'type': 'provider', 'id': id!, 'name': name!, 'args': args ?? {}};
}
factory Tool.fromJson(Map<String, dynamic> json) {
if (json['type'] == 'function') {
return Tool._(type: 'function', function: FunctionTool.fromJson(json));
}
return Tool._(type: 'provider', id: json['id'] as String, name: json['name'] as String, args: json['args'] as Map<String, dynamic>?);
}
}
/// How the model should choose tools. Mirrors `ToolChoice.ts`.
class ToolChoice {
final String _kind;
final String? toolName;
const ToolChoice._(this._kind, this.toolName);
static const auto = ToolChoice._('auto', null);
static const none = ToolChoice._('none', null);
static const required = ToolChoice._('required', null);
factory ToolChoice.tool(String toolName) => ToolChoice._('tool', toolName);
dynamic toJson() => _kind == 'tool' ? {'type': 'tool', 'toolName': toolName} : _kind;
factory ToolChoice.fromJson(dynamic json) =>
json is String ? ToolChoice._(json, null) : ToolChoice._('tool', (json as Map<String, dynamic>)['toolName'] as String);
}
// ─────────────────────────────────────────────────────────────────────────────
// GenerateResult (raw provider result)
// ─────────────────────────────────────────────────────────────────────────────
@JsonSerializable()
class ResponseMetadata {
final String? id;
final String? timestamp;
@JsonKey(name: 'model_id') final String? modelId;
ResponseMetadata({this.id, this.timestamp, this.modelId});
factory ResponseMetadata.fromJson(Map<String, dynamic> json) => _$ResponseMetadataFromJson(json);
Map<String, dynamic> toJson() => _$ResponseMetadataToJson(this);
}
/// A content item in a `GenerateResult`. Mirrors `GenerateContent.ts`
/// (`aimux-core/src/result.rs`).
///
/// Externally-tagged union — each item is a single-key map whose key is the
/// variant tag and whose value is the variant payload. Modeled as a sealed
/// class hierarchy so callers get compile-time types: every known variant is a
/// typed subclass with named fields, and [GenerateContentUnknown] is the
/// fallback for tags added by newer core versions so they pass through verbatim
/// instead of crashing.
///
/// Known variants: [GenerateContentText], [GenerateContentToolCall],
/// [GenerateContentSource], [GenerateContentReasoning], [GenerateContentFile],
/// [GenerateContentToolResult]. The `File` variant carries model-generated
/// files (e.g. images or documents) as a `FileData` tagged union under `data`,
/// alongside a `media_type` (there is **no** `filename` field). Narrow via
/// `switch`/`is`/`whereType` to read variant-specific fields.
sealed class GenerateContent {
const GenerateContent();
/// The variant tag — the single top-level key on the wire, e.g. `'Text'`,
/// `'ToolCall'`. Useful for logging / generic dispatch.
String get tag;
/// Re-encode to the externally-tagged wire shape (`{tag: payload}`).
Map<String, dynamic> toJson();
/// Decode an externally-tagged content map. Unknown tags fall back to
/// [GenerateContentUnknown] instead of throwing.
factory GenerateContent.fromJson(Map<String, dynamic> json) {
final e = json.entries.first;
final payload = e.value as Map<String, dynamic>;
return switch (e.key) {
'Text' => GenerateContentText.fromJson(payload),
'ToolCall' => GenerateContentToolCall.fromJson(payload),
'Source' => GenerateContentSource.fromJson(payload),
'Reasoning' => GenerateContentReasoning.fromJson(payload),
'File' => GenerateContentFile.fromJson(payload),
'ToolResult' => GenerateContentToolResult.fromJson(payload),
_ => GenerateContentUnknown(tag: e.key, data: payload),
};
}
}
/// Generated text.
final class GenerateContentText extends GenerateContent {
final String text;
final Map<String, dynamic>? providerMetadata;
GenerateContentText({required this.text, this.providerMetadata});
@override
String get tag => 'Text';
factory GenerateContentText.fromJson(Map<String, dynamic> json) =>
GenerateContentText(
text: json['text'] as String,
providerMetadata:
json['provider_metadata'] as Map<String, dynamic>?,
);
@override
Map<String, dynamic> toJson() => {
'Text': {
'text': text,
if (providerMetadata != null) 'provider_metadata': providerMetadata,
},
};
}
/// A tool call requested by the model.
final class GenerateContentToolCall extends GenerateContent {
final String toolCallId;
final String toolName;
final dynamic input;
final bool? providerExecuted;
final bool? isDynamic;
final String? thoughtSignature;
final Map<String, dynamic>? providerMetadata;
GenerateContentToolCall({
required this.toolCallId,
required this.toolName,
required this.input,
this.providerExecuted,
this.isDynamic,
this.thoughtSignature,
this.providerMetadata,
});
@override
String get tag => 'ToolCall';
factory GenerateContentToolCall.fromJson(Map<String, dynamic> json) =>
GenerateContentToolCall(
toolCallId: json['tool_call_id'] as String,
toolName: json['tool_name'] as String,
input: json['input'],
providerExecuted: json['provider_executed'] as bool?,
isDynamic: json['dynamic'] as bool?,
thoughtSignature: json['thought_signature'] as String?,
providerMetadata:
json['provider_metadata'] as Map<String, dynamic>?,
);
@override
Map<String, dynamic> toJson() => {
'ToolCall': {
'tool_call_id': toolCallId,
'tool_name': toolName,
'input': input,
if (providerExecuted != null) 'provider_executed': providerExecuted,
if (isDynamic != null) 'dynamic': isDynamic,
if (thoughtSignature != null) 'thought_signature': thoughtSignature,
if (providerMetadata != null) 'provider_metadata': providerMetadata,
},
};
}
/// A source / citation (e.g. URL citation from search-preview models).
final class GenerateContentSource extends GenerateContent {
final String id;
final String sourceType;
final String? url;
final String? title;
final Map<String, dynamic>? providerMetadata;
GenerateContentSource({
required this.id,
required this.sourceType,
this.url,
this.title,
this.providerMetadata,
});
@override
String get tag => 'Source';
factory GenerateContentSource.fromJson(Map<String, dynamic> json) =>
GenerateContentSource(
id: json['id'] as String,
sourceType: json['source_type'] as String,
url: json['url'] as String?,
title: json['title'] as String?,
providerMetadata:
json['provider_metadata'] as Map<String, dynamic>?,
);
@override
Map<String, dynamic> toJson() => {
'Source': {
'id': id,
'source_type': sourceType,
if (url != null) 'url': url,
if (title != null) 'title': title,
if (providerMetadata != null) 'provider_metadata': providerMetadata,
},
};
}
/// A reasoning / thinking segment produced by the model.
final class GenerateContentReasoning extends GenerateContent {
final String text;
final Map<String, dynamic>? providerMetadata;
GenerateContentReasoning({required this.text, this.providerMetadata});
@override
String get tag => 'Reasoning';
factory GenerateContentReasoning.fromJson(Map<String, dynamic> json) =>
GenerateContentReasoning(
text: json['text'] as String,
providerMetadata:
json['provider_metadata'] as Map<String, dynamic>?,
);
@override
Map<String, dynamic> toJson() => {
'Reasoning': {
'text': text,
if (providerMetadata != null) 'provider_metadata': providerMetadata,
},
};
}
/// A file generated by the model (e.g. an image or document). The `data`
/// field is a `FileData` tagged union; there is **no** `filename` field.
final class GenerateContentFile extends GenerateContent {
final FileData data;
final String mediaType;
final Map<String, dynamic>? providerMetadata;
GenerateContentFile({
required this.data,
required this.mediaType,
this.providerMetadata,
});
@override
String get tag => 'File';
factory GenerateContentFile.fromJson(Map<String, dynamic> json) =>
GenerateContentFile(
data: FileData.fromJson(json['data'] as Map<String, dynamic>),
mediaType: json['media_type'] as String,
providerMetadata:
json['provider_metadata'] as Map<String, dynamic>?,
);
@override
Map<String, dynamic> toJson() => {
'File': {
'data': data.toJson(),
'media_type': mediaType,
if (providerMetadata != null) 'provider_metadata': providerMetadata,
},
};
}
/// A tool result from a provider-executed tool (e.g. xAI file_search,
/// web_search). Emitted alongside the preceding `ToolCall`.
final class GenerateContentToolResult extends GenerateContent {
final String toolCallId;
final String toolName;
final dynamic result;
final bool? isError;
final bool? preliminary;
final bool? isDynamic;
final Map<String, dynamic>? providerMetadata;
GenerateContentToolResult({
required this.toolCallId,
required this.toolName,
required this.result,
this.isError,
this.preliminary,
this.isDynamic,
this.providerMetadata,
});
@override
String get tag => 'ToolResult';
factory GenerateContentToolResult.fromJson(Map<String, dynamic> json) =>
GenerateContentToolResult(
toolCallId: json['tool_call_id'] as String,
toolName: json['tool_name'] as String,
result: json['result'],
isError: json['is_error'] as bool?,
preliminary: json['preliminary'] as bool?,
isDynamic: json['dynamic'] as bool?,
providerMetadata:
json['provider_metadata'] as Map<String, dynamic>?,
);
@override
Map<String, dynamic> toJson() => {
'ToolResult': {
'tool_call_id': toolCallId,
'tool_name': toolName,
'result': result,
if (isError != null) 'is_error': isError,
if (preliminary != null) 'preliminary': preliminary,
if (isDynamic != null) 'dynamic': isDynamic,
if (providerMetadata != null) 'provider_metadata': providerMetadata,
},
};
}
/// Fallback for unknown/forward-compatible `GenerateContent` variants.
///
/// Newer core versions may emit tags this binding does not model yet; this
/// class passes them through verbatim (`{tag: data}`) instead of discarding
/// or crashing.
final class GenerateContentUnknown extends GenerateContent {
@override
final String tag;
final Map<String, dynamic> data;
GenerateContentUnknown({required this.tag, required this.data});
@override
Map<String, dynamic> toJson() => {tag: data};
}
class GenerateResult {
final List<GenerateContent> content;
final FinishReason finishReason;
final Usage usage;
final List<Map<String, dynamic>> warnings;
final Map<String, dynamic>? providerMetadata;
final ResponseMetadata response;
final Map<String, dynamic>? requestBody;
final Map<String, dynamic>? responseHeaders;
GenerateResult({required this.content, required this.finishReason, required this.usage, this.warnings = const [], this.providerMetadata, required this.response, this.requestBody, this.responseHeaders});
factory GenerateResult.fromJson(Map<String, dynamic> json) => GenerateResult(
content: (json['content'] as List<dynamic>? ?? []).map((e) => GenerateContent.fromJson(e as Map<String, dynamic>)).toList(),
finishReason: FinishReason.fromJson(json['finish_reason'] as Map<String, dynamic>),
usage: Usage.fromJson(json['usage'] as Map<String, dynamic>),
warnings: (json['warnings'] as List<dynamic>? ?? []).map((e) => e as Map<String, dynamic>).toList(),
providerMetadata: json['provider_metadata'] as Map<String, dynamic>?,
response: ResponseMetadata.fromJson(json['response'] as Map<String, dynamic>),
requestBody: json['request_body'] as Map<String, dynamic>?,
responseHeaders: json['response_headers'] as Map<String, dynamic>?,
);
Map<String, dynamic> toJson() => {'content': content.map((c) => c.toJson()).toList(), 'finish_reason': finishReason.toJson(), 'usage': usage.toJson(), 'warnings': warnings, 'response': response.toJson(), if (providerMetadata != null) 'provider_metadata': providerMetadata, if (requestBody != null) 'request_body': requestBody, if (responseHeaders != null) 'response_headers': responseHeaders};
}
// ─────────────────────────────────────────────────────────────────────────────
// Result / options
// ─────────────────────────────────────────────────────────────────────────────
/// Result of `generate_text` (user-facing). Mirrors `GenerateTextResult.ts`.
@JsonSerializable()
class GenerateTextResult {
final String text;
@JsonKey(name: 'tool_calls')
final List<ToolCall> toolCalls;
@JsonKey(name: 'finish_reason')
final FinishReason finishReason;
final Usage usage;
final List<Map<String, dynamic>> warnings;
final GenerateResult raw;
// M7: top-level aggregation fields
final List<Map<String, dynamic>> reasoning;
@JsonKey(name: 'reasoning_text')
final String reasoningText;
final List<Map<String, dynamic>> sources;
final List<Map<String, dynamic>> files;
@JsonKey(name: 'response_messages')
final List<ModelMessage> responseMessages;
/// Raw provider-specific finish reason string (M12, e.g. "stop", "end_turn").
@JsonKey(name: 'raw_finish_reason')
final String? rawFinishReason;
/// Provider-specific metadata (e.g. Anthropic cache info). Mirrored from
/// raw.provider_metadata for top-level convenience. Weak type.
@JsonKey(name: 'provider_metadata')
final Map<String, dynamic>? providerMetadata;
/// Response metadata (id, timestamp, model_id). Mirrored from raw.response.
final ResponseMetadata response;
/// Total token usage across all steps. In single-step mode (aimux's
/// default), equals usage. Provided for AI SDK parity.
@JsonKey(name: 'total_usage')
final Usage totalUsage;
GenerateTextResult({
required this.text,
required this.toolCalls,
required this.finishReason,
required this.usage,
this.warnings = const [],
required this.raw,
this.reasoning = const [],
this.reasoningText = '',
this.sources = const [],
this.files = const [],
this.responseMessages = const [],
this.rawFinishReason,
this.providerMetadata,
required this.response,
required this.totalUsage,
});
factory GenerateTextResult.fromJson(Map<String, dynamic> json) =>
_$GenerateTextResultFromJson(json);
Map<String, dynamic> toJson() => _$GenerateTextResultToJson(this);
}
/// Result of `generate_object` (user-facing, M12). The parsed JSON object plus
/// convenience fields from the underlying `generate_text` call.
///
/// Mirrors `GenerateObjectResult.ts`. `object` is an arbitrary JSON value
/// (weak type — `Map<String, dynamic>` / primitive).
@JsonSerializable()
class GenerateObjectResult {
/// The parsed JSON object returned by the model (arbitrary JSON, weak type).
final Object? object;
@JsonKey(name: 'finish_reason')
final FinishReason finishReason;
@JsonKey(name: 'raw_finish_reason')
final String? rawFinishReason;
final Usage usage;
final List<Map<String, dynamic>> warnings;
/// Concatenated reasoning text (if the model produced reasoning/thinking).
final String? reasoning;
/// Provider-specific metadata (e.g. Anthropic cache info). Weak type.
@JsonKey(name: 'provider_metadata')
final Map<String, dynamic>? providerMetadata;
/// Response metadata (id, timestamp, model_id).
final ResponseMetadata response;
final GenerateTextResult raw;
GenerateObjectResult({
this.object,
required this.finishReason,
this.rawFinishReason,
required this.usage,
this.warnings = const [],
this.reasoning,
this.providerMetadata,
required this.response,
required this.raw,
});
factory GenerateObjectResult.fromJson(Map<String, dynamic> json) =>
_$GenerateObjectResultFromJson(json);
Map<String, dynamic> toJson() => _$GenerateObjectResultToJson(this);
}
/// Aggregated result of `stream_text().consume()` (M11). Mirrors
/// `GenerateTextResult`'s user-facing fields (without `raw`, since streaming
/// has no `GenerateResult` equivalent).
///
/// Mirrors `StreamTextResultAggregated.ts`. reasoning/sources/files use weak
/// types (`Map<String, dynamic>`) — same strategy as `GenerateTextResult`.
@JsonSerializable()
class StreamTextResultAggregated {
final String text;
// reasoning/sources/files use weak types — same strategy as GenerateTextResult.
final List<Map<String, dynamic>> reasoning;
@JsonKey(name: 'reasoning_text')
final String reasoningText;
@JsonKey(name: 'tool_calls')
final List<ToolCall> toolCalls;
final List<Map<String, dynamic>> sources;
final List<Map<String, dynamic>> files;
@JsonKey(name: 'finish_reason')
final FinishReason finishReason;
@JsonKey(name: 'raw_finish_reason')
final String? rawFinishReason;
final Usage usage;
/// Total token usage across all steps. In single-step mode (aimux's
/// default), equals usage. Provided for AI SDK parity.
@JsonKey(name: 'total_usage')
final Usage totalUsage;
final List<Map<String, dynamic>> warnings;
/// Provider-specific metadata from the Finish chunk. Weak type.
@JsonKey(name: 'provider_metadata')
final Map<String, dynamic>? providerMetadata;
/// Response metadata (id, timestamp, model_id) if emitted by the stream.
final ResponseMetadata? response;
@JsonKey(name: 'response_messages')
final List<ModelMessage> responseMessages;
StreamTextResultAggregated({
this.text = '',
this.reasoning = const [],
this.reasoningText = '',
this.toolCalls = const [],
this.sources = const [],
this.files = const [],
required this.finishReason,
this.rawFinishReason,
required this.usage,
required this.totalUsage,
this.warnings = const [],
this.providerMetadata,
this.response,
this.responseMessages = const [],
});
factory StreamTextResultAggregated.fromJson(Map<String, dynamic> json) =>
_$StreamTextResultAggregatedFromJson(json);
Map<String, dynamic> toJson() => _$StreamTextResultAggregatedToJson(this);
}
/// Per-call timeout configuration. Mirrors `TimeoutConfiguration.ts`.
///
/// All values are milliseconds; `null` disables the corresponding limit.
@JsonSerializable()
class TimeoutConfiguration {
@JsonKey(name: 'total_ms')
final int? totalMs;
@JsonKey(name: 'first_chunk_ms')
final int? firstChunkMs;
@JsonKey(name: 'chunk_ms')
final int? chunkMs;
TimeoutConfiguration({this.totalMs, this.firstChunkMs, this.chunkMs});
factory TimeoutConfiguration.fromJson(Map<String, dynamic> json) =>
TimeoutConfiguration(
totalMs: json['total_ms'] as int?,
firstChunkMs: json['first_chunk_ms'] as int?,
chunkMs: json['chunk_ms'] as int?,
);
Map<String, dynamic> toJson() => {
if (totalMs != null) 'total_ms': totalMs,
if (firstChunkMs != null) 'first_chunk_ms': firstChunkMs,
if (chunkMs != null) 'chunk_ms': chunkMs,
};
}
/// User-facing options for `generate_text` / `stream_text`. Mirrors
/// `GenerateTextOptions.ts`.
@JsonSerializable()
class GenerateTextOptions {
@JsonKey(name: 'max_output_tokens')
final int? maxOutputTokens;
final double? temperature;
@JsonKey(name: 'stop_sequences')
final List<String>? stopSequences;
@JsonKey(name: 'top_p')
final double? topP;
@JsonKey(name: 'top_k')
final double? topK;
@JsonKey(name: 'presence_penalty')
final double? presencePenalty;
@JsonKey(name: 'frequency_penalty')
final double? frequencyPenalty;
@JsonKey(name: 'response_format')
final Map<String, dynamic>? responseFormat;
final int? seed;
final List<Tool>? tools;
@JsonKey(name: 'tool_choice')
final ToolChoice? toolChoice;
final Map<String, String>? headers;
@JsonKey(name: 'provider_options')
final Map<String, dynamic>? providerOptions;
final ReasoningEffort? reasoning;
final String? instructions;
@JsonKey(name: 'body_overrides')
final Map<String, dynamic>? bodyOverrides;
@JsonKey(name: 'max_retries')
final int? maxRetries;
final TimeoutConfiguration? timeout;
@JsonKey(name: 'include_raw_chunks')
final bool? includeRawChunks;
@JsonKey(name: 'session_id')
final String? sessionId;
GenerateTextOptions({
this.maxOutputTokens,
this.temperature,
this.stopSequences,
this.topP,
this.topK,
this.presencePenalty,
this.frequencyPenalty,
this.responseFormat,
this.seed,
this.tools,
this.toolChoice,
this.headers,
this.providerOptions,
this.reasoning,
this.instructions,
this.bodyOverrides,
this.maxRetries,
this.timeout,
this.includeRawChunks,
this.sessionId,
});
factory GenerateTextOptions.fromJson(Map<String, dynamic> json) {
return GenerateTextOptions(
maxOutputTokens: json['max_output_tokens'] as int?,
temperature: (json['temperature'] as num?)?.toDouble(),
stopSequences: (json['stop_sequences'] as List<dynamic>?)?.cast<String>(),
topP: (json['top_p'] as num?)?.toDouble(),
topK: (json['top_k'] as num?)?.toDouble(),
presencePenalty: (json['presence_penalty'] as num?)?.toDouble(),
frequencyPenalty: (json['frequency_penalty'] as num?)?.toDouble(),
responseFormat: json['response_format'] as Map<String, dynamic>?,
seed: json['seed'] as int?,
tools: (json['tools'] as List<dynamic>?)
?.map((e) => Tool.fromJson(e as Map<String, dynamic>))
.toList(),
toolChoice: json['tool_choice'] != null
? ToolChoice.fromJson(json['tool_choice'])
: null,
headers: (json['headers'] as Map<String, dynamic>?)?.cast<String, String>(),
providerOptions: json['provider_options'] as Map<String, dynamic>?,
reasoning: json['reasoning'] != null
? ReasoningEffort.fromJson(json['reasoning'] as String)
: null,
instructions: json['instructions'] as String?,
bodyOverrides: json['body_overrides'] as Map<String, dynamic>?,
maxRetries: json['max_retries'] as int?,
timeout: json['timeout'] != null
? TimeoutConfiguration.fromJson(json['timeout'] as Map<String, dynamic>)
: null,
includeRawChunks: json['include_raw_chunks'] as bool?,
sessionId: json['session_id'] as String?,
);
}
Map<String, dynamic> toJson() => {
if (maxOutputTokens != null) 'max_output_tokens': maxOutputTokens,
if (temperature != null) 'temperature': temperature,
if (stopSequences != null) 'stop_sequences': stopSequences,
if (topP != null) 'top_p': topP,
if (topK != null) 'top_k': topK,
if (presencePenalty != null) 'presence_penalty': presencePenalty,
if (frequencyPenalty != null) 'frequency_penalty': frequencyPenalty,
if (responseFormat != null) 'response_format': responseFormat,
if (seed != null) 'seed': seed,
if (tools != null) 'tools': tools!.map((t) => t.toJson()).toList(),
if (toolChoice != null) 'tool_choice': toolChoice!.toJson(),
if (headers != null) 'headers': headers,
if (providerOptions != null) 'provider_options': providerOptions,
if (reasoning != null) 'reasoning': reasoning!.toJson(),
if (instructions != null) 'instructions': instructions,
if (bodyOverrides != null) 'body_overrides': bodyOverrides,
if (maxRetries != null) 'max_retries': maxRetries,
if (timeout != null) 'timeout': timeout!.toJson(),
if (includeRawChunks != null) 'include_raw_chunks': includeRawChunks,
if (sessionId != null) 'session_id': sessionId,
};
}
// ─────────────────────────────────────────────────────────────────────────────
// Messages
// ─────────────────────────────────────────────────────────────────────────────
/// A single user-facing chat message. Mirrors `ModelMessage.ts`.
///
/// `content` is either a plain `String` or a `List` of content-part maps
/// (`[{"type":"text","text":"..."}, ...]`); it is kept as `Object` so both
/// shapes pass through verbatim.
@JsonSerializable()
class ModelMessage {
final String role;
final Object content;
ModelMessage({required this.role, required this.content});
factory ModelMessage.fromJson(Map<String, dynamic> json) =>
_$ModelMessageFromJson(json);
Map<String, dynamic> toJson() => _$ModelMessageToJson(this);
/// Convenience view of [content] as a list of content-part maps.
///
/// If [content] is a `String`, returns `[{'type': 'text', 'text': content}]`;
/// if it is a `List`, returns it cast to `List<Map<String, dynamic>>`;
/// otherwise an empty list. `content` itself stays `Object` so both the
/// string and the part-list wire shapes pass through verbatim.
List<Map<String, dynamic>> get contentParts {
final c = content;
if (c is String) {
return <Map<String, dynamic>>[
{'type': 'text', 'text': c},
];
}
if (c is List) {
return c.whereType<Map<String, dynamic>>().toList();
}
return const <Map<String, dynamic>>[];
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Streaming
// ─────────────────────────────────────────────────────────────────────────────
/// A single chunk in the stream returned by `stream_text`. Mirrors
/// `StreamPart.ts` (`aimux-core/src/stream_part.rs`).
///
/// `StreamPart` is an externally-tagged union: each part is a single-key map
/// like `{"TextDelta": {"id": "...", "delta": "..."}}`. Modeled as a sealed
/// class hierarchy so callers get compile-time types: every known variant is a
/// typed subclass with named fields, and [StreamPartUnknown] is the fallback
/// for tags added by newer core versions.
///
/// Known variants: [StreamPartTextStart]/[StreamPartTextDelta]/[StreamPartTextEnd],
/// [StreamPartStreamStart], [StreamPartFinish], [StreamPartError],
/// [StreamPartToolInputStart]/[StreamPartToolInputDelta]/[StreamPartToolInputEnd],
/// [StreamPartToolCall], [StreamPartToolResult], [StreamPartFile],
/// [StreamPartReasoningStart]/[StreamPartReasoningDelta]/[StreamPartReasoningEnd],
/// [StreamPartResponseMetadata], [StreamPartSource], [StreamPartRaw]. Narrow
/// via `switch`/`is`/`whereType` to read variant-specific fields.
sealed class StreamPart {
const StreamPart();
/// The variant tag — the single top-level key on the wire (e.g.
/// `'TextDelta'`, `'ToolCall'`, `'ToolResult'`, `'File'`, `'Finish'`,
/// `'Error'`). Empty only for a malformed part.
String get type => switch (this) {
StreamPartTextStart() => 'TextStart',
StreamPartTextDelta() => 'TextDelta',
StreamPartTextEnd() => 'TextEnd',
StreamPartStreamStart() => 'StreamStart',
StreamPartFinish() => 'Finish',
StreamPartError() => 'Error',
StreamPartToolInputStart() => 'ToolInputStart',
StreamPartToolInputDelta() => 'ToolInputDelta',
StreamPartToolInputEnd() => 'ToolInputEnd',
StreamPartToolCall() => 'ToolCall',
StreamPartToolResult() => 'ToolResult',
StreamPartFile() => 'File',
StreamPartReasoningStart() => 'ReasoningStart',
StreamPartReasoningDelta() => 'ReasoningDelta',
StreamPartReasoningEnd() => 'ReasoningEnd',
StreamPartResponseMetadata() => 'ResponseMetadata',
StreamPartSource() => 'Source',
StreamPartRaw() => 'Raw',
StreamPartUnknown(:final tag) => tag,
};
/// Re-encode to the externally-tagged wire shape (`{tag: payload}`).
Map<String, dynamic> toJson();
/// Decode an externally-tagged stream-part map. Unknown tags fall back to
/// [StreamPartUnknown] instead of throwing.
factory StreamPart.fromJson(Map<String, dynamic> json) {
final e = json.entries.first;
final payload = e.value as Map<String, dynamic>;
return switch (e.key) {
'TextStart' => StreamPartTextStart.fromJson(payload),
'TextDelta' => StreamPartTextDelta.fromJson(payload),
'TextEnd' => StreamPartTextEnd.fromJson(payload),
'StreamStart' => StreamPartStreamStart.fromJson(payload),
'Finish' => StreamPartFinish.fromJson(payload),
'Error' => StreamPartError.fromJson(payload),
'ToolInputStart' => StreamPartToolInputStart.fromJson(payload),
'ToolInputDelta' => StreamPartToolInputDelta.fromJson(payload),
'ToolInputEnd' => StreamPartToolInputEnd.fromJson(payload),
'ToolCall' => StreamPartToolCall.fromJson(payload),
'ToolResult' => StreamPartToolResult.fromJson(payload),
'File' => StreamPartFile.fromJson(payload),
'ReasoningStart' => StreamPartReasoningStart.fromJson(payload),
'ReasoningDelta' => StreamPartReasoningDelta.fromJson(payload),
'ReasoningEnd' => StreamPartReasoningEnd.fromJson(payload),
'ResponseMetadata' => StreamPartResponseMetadata.fromJson(payload),
'Source' => StreamPartSource.fromJson(payload),
'Raw' => StreamPartRaw.fromJson(payload),
_ => StreamPartUnknown(tag: e.key, data: payload),
};
}
@override
String toString() => 'StreamPart($type)';
}
// ── Text variants ────────────────────────────────────────────────────────────