-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathengine.dart
More file actions
1474 lines (1335 loc) · 47.1 KB
/
engine.dart
File metadata and controls
1474 lines (1335 loc) · 47.1 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
import 'dart:async';
import 'dart:convert';
import '../../backends/backend.dart';
import '../template/chat_template_engine.dart';
import '../exceptions.dart';
import '../models/config/log_level.dart';
import '../models/chat/chat_message.dart';
import '../models/chat/completion_chunk.dart';
import '../models/chat/content_part.dart';
import '../models/chat/chat_template_result.dart';
import '../llama_logger.dart';
import '../models/inference/model_params.dart';
import '../models/inference/generation_params.dart';
import '../models/inference/tool_choice.dart';
import '../models/tools/tool_definition.dart';
enum _ToolStreamingMode { undecided, raw, parsed }
class _ThinkingSplitEmission {
final String text;
final bool isThinking;
const _ThinkingSplitEmission({required this.text, required this.isThinking});
}
class _ThinkingSplitResult {
final String pendingBuffer;
final bool isThinking;
final List<_ThinkingSplitEmission> emissions;
const _ThinkingSplitResult({
required this.pendingBuffer,
required this.isThinking,
required this.emissions,
});
}
/// Stateless chat completions engine (like OpenAI's Chat Completions API).
///
/// [LlamaEngine] is the primary API for chat-based inference. Each call to
/// [create] is stateless - you must pass the full conversation history.
/// For automatic history management, use [ChatSession] instead.
///
/// Example (OpenAI-style stateless usage):
/// ```dart
/// final engine = LlamaEngine(LlamaBackend());
/// await engine.loadModel('path/to/model.gguf');
///
/// // Build messages array (you manage history)
/// final messages = [
/// LlamaChatMessage.fromText(role: LlamaChatRole.system, text: 'You are helpful.'),
/// LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'Hello!'),
/// ];
///
/// // Create completion
/// final response = await engine.create(messages).join();
///
/// // Append response and continue conversation
/// messages.add(LlamaChatMessage.fromText(role: LlamaChatRole.assistant, text: response));
/// messages.add(LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'Follow up?'));
/// final response2 = await engine.create(messages).join();
/// ```
class LlamaEngine {
/// The backend implementation used for inference.
final LlamaBackend backend;
int? _modelHandle;
int? _contextHandle;
int? _mmContextHandle;
bool _isReady = false;
String? _modelPath;
Map<String, String>? _cachedModelMetadata;
LlamaLogLevel _dartLogLevel = LlamaLogLevel.none;
LlamaLogLevel _nativeLogLevel = LlamaLogLevel.none;
/// Configures logging for the library.
///
/// [level] determines which logs are output.
/// [handler] is an optional custom callback. If null and level != none,
/// logs are printed to stdout.
static void configureLogging({
LlamaLogLevel level = LlamaLogLevel.none,
LlamaLogHandler? handler,
}) {
LlamaLogger.instance.setLevel(level);
LlamaLogger.instance.setHandler(handler);
}
/// Creates a new [LlamaEngine] instance with the given [backend].
LlamaEngine(this.backend);
/// Sets both Dart and native log levels to [level].
///
/// For independent control, use [setDartLogLevel] and [setNativeLogLevel].
Future<void> setLogLevel(LlamaLogLevel level) async {
await setDartLogLevel(level);
await setNativeLogLevel(level);
}
/// Sets only the Dart-side logger level.
Future<void> setDartLogLevel(LlamaLogLevel level) async {
_dartLogLevel = level;
LlamaLogger.instance.setLevel(level);
}
/// Sets only the native backend logger level.
Future<void> setNativeLogLevel(LlamaLogLevel level) async {
_nativeLogLevel = level;
await backend.setLogLevel(level);
}
/// Current Dart-side logger level.
LlamaLogLevel get dartLogLevel => _dartLogLevel;
/// Current native backend logger level.
LlamaLogLevel get nativeLogLevel => _nativeLogLevel;
// ============================================================
// MODEL LIFECYCLE
// ============================================================
/// Whether the engine is initialized and ready for inference.
bool get isReady => _isReady;
/// Loads a model from a local [path].
///
/// Optionally provide [ModelParams] to configure context size, GPU offloading,
/// and more.
Future<void> loadModel(
String path, {
ModelParams modelParams = const ModelParams(),
}) async {
final modelName = _displayNameForSource(path);
LlamaLogger.instance.info('Loading model: $modelName');
if (backend.supportsUrlLoading) {
LlamaLogger.instance.info(
'Backend supports URL loading, attempting loadModelFromUrl.',
);
return loadModelFromUrl(path, modelParams: modelParams);
}
try {
await backend.setLogLevel(_nativeLogLevel);
_ensureNotReady();
_modelPath = path;
_cachedModelMetadata = null;
_modelHandle = await backend.modelLoad(path, modelParams);
_contextHandle = await backend.contextCreate(_modelHandle!, modelParams);
_isReady = true;
LlamaLogger.instance.info(
'Model $modelName loaded successfully from $path',
);
} catch (e, stackTrace) {
await _cleanupFailedLoadState();
LlamaLogger.instance.error(
'Failed to load model $modelName from $path',
e,
stackTrace,
);
throw LlamaModelException('Failed to load model from $path', e);
}
}
/// Loads a model from a [url].
///
/// This is typically used on the Web platform. Use [ModelParams] to
/// configure loading options.
Future<void> loadModelFromUrl(
String url, {
ModelParams modelParams = const ModelParams(),
Function(double progress)? onProgress,
}) async {
final modelName = _displayNameForSource(url);
LlamaLogger.instance.info('Loading model from URL: $modelName');
if (!backend.supportsUrlLoading) {
throw UnimplementedError(
"loadModelFromUrl for Native should be handled by the caller or a helper.",
);
}
try {
await backend.setLogLevel(_nativeLogLevel);
_ensureNotReady();
_modelPath = url;
_cachedModelMetadata = null;
_modelHandle = await backend.modelLoadFromUrl(
url,
modelParams,
onProgress: onProgress,
);
_contextHandle = await backend.contextCreate(_modelHandle!, modelParams);
_isReady = true;
LlamaLogger.instance.info(
'Model $modelName loaded successfully from $url',
);
} catch (e, stackTrace) {
await _cleanupFailedLoadState();
LlamaLogger.instance.error(
'Failed to load model $modelName from URL $url',
e,
stackTrace,
);
throw LlamaModelException("Failed to load model from $url", e);
}
}
/// Loads a multimodal projector model for vision/audio support.
Future<void> loadMultimodalProjector(String mmProjPath) async {
final mmProjName = _displayNameForSource(mmProjPath);
LlamaLogger.instance.info('Loading multimodal projector: $mmProjName');
_ensureReady(requireContext: false);
try {
if (_mmContextHandle != null) {
await unloadMultimodalProjector();
}
_mmContextHandle = await backend.multimodalContextCreate(
_modelHandle!,
mmProjPath,
);
LlamaLogger.instance.info(
'Multimodal projector $mmProjName loaded successfully',
);
} catch (e, stackTrace) {
LlamaLogger.instance.error(
'Failed to load multimodal projector $mmProjName',
e,
stackTrace,
);
rethrow;
}
}
/// Unloads the active multimodal projector while keeping the model loaded.
Future<void> unloadMultimodalProjector() async {
final mmContextHandle = _mmContextHandle;
if (mmContextHandle == null) {
return;
}
LlamaLogger.instance.info('Unloading multimodal projector');
_mmContextHandle = null;
await backend.multimodalContextFree(mmContextHandle);
}
/// Releases all allocated resources.
Future<void> dispose() async {
await unloadModel();
await backend.dispose();
}
/// Unloads the currently loaded model and frees its resources.
Future<void> unloadModel() async {
if (!isReady && _modelHandle == null && _mmContextHandle == null) return;
LlamaLogger.instance.info('Unloading model...');
if (_contextHandle != null) {
await backend.contextFree(_contextHandle!);
_contextHandle = null;
}
if (_mmContextHandle != null) {
await backend.multimodalContextFree(_mmContextHandle!);
_mmContextHandle = null;
}
if (_modelHandle != null) {
await backend.modelFree(_modelHandle!);
_modelHandle = null;
}
_modelPath = null;
_cachedModelMetadata = null;
_isReady = false;
LlamaLogger.instance.info('Model unloaded.');
}
// ============================================================
// CHAT COMPLETIONS (Primary API)
// ============================================================
/// Creates a chat completion from a list of [messages].
///
/// This is the primary stateless API (like OpenAI's Chat Completions).
/// You must pass the full conversation history with each call.
///
/// Pass [tools] to enable function calling. Use [toolChoice] to control
/// whether the model should use tools:
/// - [ToolChoice.none]: Model won't call any tool
/// - [ToolChoice.auto]: Model can choose (default when tools present)
/// - [ToolChoice.required]: Model must call at least one tool
///
/// Set [parallelToolCalls] to allow multiple tool calls in one response for
/// templates that support it.
///
/// For TranslateGemma-style templates, set [sourceLangCode] and
/// [targetLangCode] to control language metadata injected into user
/// content blocks.
///
/// Use [chatTemplateKwargs] to inject additional template globals (equivalent
/// to llama.cpp `chat_template_kwargs`).
/// Use [templateNow] to set deterministic template time context.
///
/// Example:
/// ```dart
/// final messages = [
/// LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'Hello!'),
/// ];
/// await for (final token in engine.create(messages)) {
/// print(token);
/// }
/// ```
Stream<LlamaCompletionChunk> create(
List<LlamaChatMessage> messages, {
GenerationParams? params,
List<ToolDefinition>? tools,
ToolChoice? toolChoice,
bool parallelToolCalls = false,
bool enableThinking = true,
String? sourceLangCode,
String? targetLangCode,
Map<String, dynamic>? chatTemplateKwargs,
DateTime? templateNow,
}) async* {
_ensureReady();
// Keep tools available to template routing even with toolChoice.none,
// matching llama.cpp behavior.
final effectiveTools = tools;
// Apply chat template with tools - returns grammar for constraining
final result = await chatTemplate(
messages,
tools: effectiveTools,
toolChoice: toolChoice ?? ToolChoice.auto,
parallelToolCalls: parallelToolCalls,
enableThinking: enableThinking,
sourceLangCode: sourceLangCode,
targetLangCode: targetLangCode,
chatTemplateKwargs: chatTemplateKwargs,
templateNow: templateNow,
includeTokenCount: false,
);
final stops = {...result.stopSequences, ...?params?.stopSequences}.toList();
LlamaLogger.instance.debug('Chat template result:');
LlamaLogger.instance.debug(' Format: ${result.format}');
LlamaLogger.instance.debug(' Prompt: ${result.prompt}');
LlamaLogger.instance.debug(' Stop sequences: $stops');
LlamaLogger.instance.debug(' Grammar present: ${result.grammar != null}');
LlamaLogger.instance.debug(' Grammar lazy: ${result.grammarLazy}');
LlamaLogger.instance.debug(
' Grammar triggers: ${result.grammarTriggers.length}',
);
LlamaLogger.instance.debug(
' Thinking forced open: ${result.thinkingForcedOpen}',
);
// Collect media parts from all messages
final allParts = messages.expand((m) => m.parts).toList();
final hasTemplateGrammar = result.grammar != null;
final effectiveGrammar = hasTemplateGrammar
? result.grammar
: params?.grammar;
final effectiveGrammarLazy = hasTemplateGrammar
? result.grammarLazy
: (params?.grammarLazy ?? false);
final effectiveGrammarTriggers = hasTemplateGrammar
? result.grammarTriggers
.map(
(trigger) => GenerationGrammarTrigger(
type: trigger.type,
value: trigger.value,
token: trigger.token,
),
)
.toList(growable: false)
: (params?.grammarTriggers ?? const <GenerationGrammarTrigger>[]);
final effectivePreservedTokens = {
...result.preservedTokens,
...?params?.preservedTokens,
}.toList(growable: false);
// Generate raw tokens with grammar constraint
final tokenStream = generate(
result.prompt,
params: (params ?? const GenerationParams()).copyWith(
stopSequences: stops,
grammar: effectiveGrammar,
grammarLazy: effectiveGrammarLazy,
grammarTriggers: effectiveGrammarTriggers,
preservedTokens: effectivePreservedTokens,
),
parts: allParts,
);
// Parse the tokens into structured chunks using the detected format
final completionId = DateTime.now().millisecondsSinceEpoch.toString();
final buffer = StringBuffer();
final parseToolCallsEnabled =
effectiveTools != null &&
effectiveTools.isNotEmpty &&
(toolChoice ?? ToolChoice.auto) != ToolChoice.none;
var streamedContent = '';
var streamedReasoning = '';
const structuredPartialParseInterval = 8;
const plainPartialParseProbeInterval = 4;
const signalDrivenPartialParseMinTokens = 2;
const partialParseMinIntervalMs = 24;
var tokensSincePartialParse = 0;
var sawStructuredOutputSignal = false;
var didInitialPartialParse = false;
var lastPartialParseAtMs = 0;
final partialParseStopwatch = Stopwatch()..start();
var streamingMode = _ToolStreamingMode.undecided;
var undecidedPrefix = '';
final thinkingTags = ChatTemplateEngine.thinkingTagsFor(result.format);
final startTag = thinkingTags.startTag;
final endTag = thinkingTags.endTag;
var isThinking = result.thinkingForcedOpen;
var pendingBuffer = '';
if (parseToolCallsEnabled) {
await for (final token in tokenStream) {
buffer.write(token);
if (streamingMode == _ToolStreamingMode.undecided) {
undecidedPrefix += token;
final mode = _decideToolStreamingMode(undecidedPrefix);
if (mode == _ToolStreamingMode.undecided) {
continue;
}
if (mode == _ToolStreamingMode.raw) {
streamingMode = _ToolStreamingMode.raw;
} else {
streamingMode = _ToolStreamingMode.parsed;
undecidedPrefix = '';
}
}
if (streamingMode == _ToolStreamingMode.raw) {
if (undecidedPrefix.isNotEmpty) {
pendingBuffer += undecidedPrefix;
undecidedPrefix = '';
} else if (token.isNotEmpty) {
pendingBuffer += token;
}
final split = _splitThinkingBuffer(
pendingBuffer: pendingBuffer,
isThinking: isThinking,
startTag: startTag,
endTag: endTag,
);
pendingBuffer = split.pendingBuffer;
isThinking = split.isThinking;
for (final emission in split.emissions) {
if (emission.isThinking) {
streamedReasoning += emission.text;
} else {
streamedContent += emission.text;
}
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: emission.isThinking
? LlamaCompletionChunkDelta(thinking: emission.text)
: LlamaCompletionChunkDelta(content: emission.text),
),
],
);
}
continue;
}
tokensSincePartialParse++;
final tokenHasSignal = _mayNeedStructuredPartialParse(token);
if (tokenHasSignal) {
sawStructuredOutputSignal = true;
}
final elapsedMs = partialParseStopwatch.elapsedMilliseconds;
final intervalElapsed =
elapsedMs - lastPartialParseAtMs >= partialParseMinIntervalMs;
final signalParseReady =
tokenHasSignal &&
intervalElapsed &&
tokensSincePartialParse >= signalDrivenPartialParseMinTokens;
final periodicParseReady =
(sawStructuredOutputSignal &&
tokensSincePartialParse >= structuredPartialParseInterval) ||
(!sawStructuredOutputSignal &&
tokensSincePartialParse >= plainPartialParseProbeInterval);
final shouldRunPartialParse =
!didInitialPartialParse || signalParseReady || periodicParseReady;
if (!shouldRunPartialParse) {
continue;
}
didInitialPartialParse = true;
tokensSincePartialParse = 0;
lastPartialParseAtMs = elapsedMs;
try {
final partialParsed = ChatTemplateEngine.parse(
result.format,
buffer.toString(),
isPartial: true,
parseToolCalls: true,
thinkingForcedOpen: result.thinkingForcedOpen,
parser: result.parser,
);
final partialReasoning = partialParsed.reasoningContent ?? '';
if (partialReasoning.length > streamedReasoning.length) {
final delta = partialReasoning.substring(streamedReasoning.length);
if (delta.isNotEmpty) {
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: LlamaCompletionChunkDelta(thinking: delta),
),
],
);
}
}
if (partialParsed.content.length > streamedContent.length) {
final delta = partialParsed.content.substring(
streamedContent.length,
);
if (delta.isNotEmpty) {
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: LlamaCompletionChunkDelta(content: delta),
),
],
);
}
}
if (partialReasoning.length >= streamedReasoning.length) {
streamedReasoning = partialReasoning;
}
if (partialParsed.content.length >= streamedContent.length) {
streamedContent = partialParsed.content;
}
} catch (_) {
// Partial parser failures are expected during incremental generation.
// Keep buffering and let the final parse determine structured output.
}
}
// Preserve raw output for whitespace-only replies where routing mode
// never resolved (no non-whitespace token observed).
if (streamingMode == _ToolStreamingMode.undecided &&
undecidedPrefix.isNotEmpty) {
streamedContent += undecidedPrefix;
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: LlamaCompletionChunkDelta(content: undecidedPrefix),
),
],
);
}
if (streamingMode == _ToolStreamingMode.raw && pendingBuffer.isNotEmpty) {
if (isThinking) {
streamedReasoning += pendingBuffer;
} else {
streamedContent += pendingBuffer;
}
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: isThinking
? LlamaCompletionChunkDelta(thinking: pendingBuffer)
: LlamaCompletionChunkDelta(content: pendingBuffer),
),
],
);
}
} else {
await for (final token in tokenStream) {
buffer.write(token);
pendingBuffer += token;
final split = _splitThinkingBuffer(
pendingBuffer: pendingBuffer,
isThinking: isThinking,
startTag: startTag,
endTag: endTag,
);
pendingBuffer = split.pendingBuffer;
isThinking = split.isThinking;
for (final emission in split.emissions) {
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: emission.isThinking
? LlamaCompletionChunkDelta(thinking: emission.text)
: LlamaCompletionChunkDelta(content: emission.text),
),
],
);
}
}
// Final flush of any pending buffer
if (pendingBuffer.isNotEmpty) {
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: isThinking
? LlamaCompletionChunkDelta(thinking: pendingBuffer)
: LlamaCompletionChunkDelta(content: pendingBuffer),
),
],
);
}
}
// After generation completes, parse the full output for tool calls
final fullOutput = buffer.toString();
final parsed = ChatTemplateEngine.parse(
result.format,
fullOutput,
parseToolCalls: parseToolCallsEnabled,
thinkingForcedOpen: result.thinkingForcedOpen,
parser: result.parser,
);
if (parseToolCallsEnabled) {
final finalReasoning = parsed.reasoningContent ?? '';
final reasoningDelta = _computeFinalReconciliationDelta(
streamedValue: streamedReasoning,
finalValue: finalReasoning,
channel: 'thinking',
);
if (reasoningDelta != null && reasoningDelta.isNotEmpty) {
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: LlamaCompletionChunkDelta(thinking: reasoningDelta),
),
],
);
}
final contentDelta = _computeFinalReconciliationDelta(
streamedValue: streamedContent,
finalValue: parsed.content,
channel: 'content',
);
if (contentDelta != null && contentDelta.isNotEmpty) {
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: LlamaCompletionChunkDelta(content: contentDelta),
),
],
);
}
}
LlamaLogger.instance.debug('Parsed result: $parsed');
if (parsed.hasToolCalls) {
for (final tc in parsed.toolCalls) {
LlamaLogger.instance.debug(
' Tool call: ${tc.function?.name}(${tc.function?.arguments})',
);
}
}
if (parsed.hasReasoning) {
LlamaLogger.instance.debug(
' Reasoning: ${parsed.reasoningContent?.length ?? 0} chars',
);
}
if (parsed.hasToolCalls) {
final toolCallsWithIds = parsed.toolCalls
.asMap()
.entries
.map(
(entry) => LlamaCompletionChunkToolCall(
index: entry.value.index,
id: (entry.value.id == null || entry.value.id!.isEmpty)
? 'call_${entry.key}'
: entry.value.id,
type: entry.value.type,
function: entry.value.function,
),
)
.toList(growable: false);
// Emit a final chunk with tool calls
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: LlamaCompletionChunkDelta(toolCalls: toolCallsWithIds),
finishReason: 'tool_calls',
),
],
);
} else {
// Emit the stop chunk
yield LlamaCompletionChunk(
id: 'chatcmpl-$completionId',
object: 'chat.completion.chunk',
created: DateTime.now().millisecondsSinceEpoch ~/ 1000,
model: _modelPath ?? 'llama_model',
choices: [
LlamaCompletionChunkChoice(
index: 0,
delta: LlamaCompletionChunkDelta(),
finishReason: 'stop',
),
],
);
}
}
/// Formats a list of [messages] into a prompt string using the model's template.
///
/// This is useful for preparing messages before calling [generate] directly,
/// or for inspecting the formatted prompt for debugging purposes.
///
/// Pass [customTemplate] to override default routing.
/// Pass [responseFormat] or legacy [jsonSchema] to request structured output
/// grammar generation.
///
/// For TranslateGemma-style templates, [sourceLangCode] and
/// [targetLangCode] are forwarded to the template renderer.
///
/// Set [includeTokenCount] to false to skip the prompt tokenization pass
/// and reduce per-request overhead when token count is not needed.
///
/// Use [chatTemplateKwargs] to inject additional template globals (equivalent
/// to llama.cpp `chat_template_kwargs`).
/// Use [templateNow] to set deterministic template time context.
///
Future<LlamaChatTemplateResult> chatTemplate(
List<LlamaChatMessage> messages, {
bool addAssistant = true,
Map<String, dynamic>? jsonSchema,
List<ToolDefinition>? tools,
ToolChoice toolChoice = ToolChoice.auto,
bool parallelToolCalls = false,
bool enableThinking = true,
Map<String, dynamic>? responseFormat,
String? customTemplate,
String? sourceLangCode,
String? targetLangCode,
bool includeTokenCount = true,
Map<String, dynamic>? chatTemplateKwargs,
DateTime? templateNow,
}) async {
_ensureReady(requireContext: false);
String? templateSource;
// Get metadata for template source and token info
Map<String, String> metadata = {};
try {
metadata = await _getCachedMetadata();
templateSource = metadata['tokenizer.chat_template'];
} catch (e) {
LlamaLogger.instance.warning('Failed to read metadata: $e');
}
if (sourceLangCode != null && sourceLangCode.isNotEmpty) {
metadata['source_lang_code'] = sourceLangCode;
}
if (targetLangCode != null && targetLangCode.isNotEmpty) {
metadata['target_lang_code'] = targetLangCode;
}
// Use ChatTemplateEngine for format detection, rendering, and grammar
try {
final effectiveResponseFormat =
responseFormat ??
(jsonSchema == null
? null
: {
'type': 'json_schema',
'json_schema': {'schema': jsonSchema},
});
final result = ChatTemplateEngine.render(
templateSource: templateSource,
messages: messages,
metadata: metadata,
addAssistant: addAssistant,
tools: tools,
toolChoice: toolChoice,
parallelToolCalls: parallelToolCalls,
enableThinking: enableThinking,
responseFormat: effectiveResponseFormat,
customTemplate: customTemplate,
chatTemplateKwargs: chatTemplateKwargs,
now: templateNow,
);
int? tokenCount;
if (includeTokenCount) {
final tokens = await tokenize(result.prompt, addSpecial: false);
tokenCount = tokens.length;
}
return LlamaChatTemplateResult(
prompt: result.prompt,
format: result.format,
grammar: result.grammar,
grammarLazy: result.grammarLazy,
additionalStops: result.additionalStops,
grammarTriggers: result.grammarTriggers,
thinkingForcedOpen: result.thinkingForcedOpen,
preservedTokens: result.preservedTokens,
parser: result.parser,
tokenCount: tokenCount,
);
} catch (_) {
rethrow;
}
}
// ============================================================
// LOW-LEVEL GENERATION
// ============================================================
/// Generates a stream of text tokens based on the provided raw [prompt].
///
/// This is the low-level generation API. For chat-style interactions with
/// proper template formatting, use [create] instead.
///
/// Use [GenerationParams] to tune the sampling process.
///
/// If [parts] contains media content, markers will be automatically injected
/// into the prompt if missing.
Stream<String> generate(
String prompt, {
GenerationParams params = const GenerationParams(),
List<LlamaContentPart>? parts,
}) async* {
_ensureReady();
final stream = backend.generate(
_contextHandle!,
prompt,
params,
parts: parts,
);
yield* stream.transform(const Utf8Decoder(allowMalformed: true));
}
/// Immediately cancels any ongoing generation process.
void cancelGeneration() {
backend.cancelGeneration();
}
// ============================================================
// TOKENIZATION
// ============================================================
/// Encodes the given [text] into a list of token IDs.
Future<List<int>> tokenize(String text, {bool addSpecial = true}) {
_ensureReady(requireContext: false);
return backend.tokenize(_modelHandle!, text, addSpecial: addSpecial);
}
/// Decodes a list of [tokens] back into a human-readable string.
Future<String> detokenize(List<int> tokens, {bool special = false}) {
_ensureReady(requireContext: false);
return backend.detokenize(_modelHandle!, tokens, special: special);
}
/// Utility to count the number of tokens in [text] without running inference.
Future<int> getTokenCount(String text) async {
final tokens = await tokenize(text, addSpecial: false);
return tokens.length;
}
// ============================================================
// EMBEDDINGS
// ============================================================
/// Generates a single embedding vector for [text].
///
/// When [normalize] is true, the returned vector is L2-normalized.
Future<List<double>> embed(String text, {bool normalize = true}) {
_ensureReady();
final embeddingBackend = _resolveEmbeddingBackend();
return embeddingBackend.embed(_contextHandle!, text, normalize: normalize);
}
/// Generates embedding vectors for all [texts] in order.
///
/// When [normalize] is true, each returned vector is L2-normalized.
Future<List<List<double>>> embedBatch(
List<String> texts, {
bool normalize = true,
}) async {
_ensureReady();
if (texts.isEmpty) {
return const <List<double>>[];
}
final embeddingBackend = _resolveEmbeddingBackend();
if (embeddingBackend is BackendBatchEmbeddings) {
return embeddingBackend.embedBatch(
_contextHandle!,
texts,
normalize: normalize,
);
}
final vectors = <List<double>>[];
for (final text in texts) {
final vector = await embeddingBackend.embed(
_contextHandle!,
text,
normalize: normalize,
);
vectors.add(vector);
}
return vectors;
}
// ============================================================
// MODEL INTROSPECTION
// ============================================================
/// Retrieves all available metadata from the loaded model.
Future<Map<String, String>> getMetadata() async {
if (!_isReady || _modelHandle == null) {
return <String, String>{};
}
final metadata = await backend.modelMetadata(_modelHandle!);
_cachedModelMetadata = Map<String, String>.from(metadata);
return metadata;
}
/// Returns the actual context size being used by the current session.
Future<int> getContextSize() async {
if (_isReady && _contextHandle != null) {
final size = await backend.getContextSize(_contextHandle!);
if (size > 0) return size;