Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
## Unreleased

- An attached `SpeechToTextEngine` whose `LlamaEngine` was disposed now
reports the disposed engine, instead of asking to load a model
([#924](https://github.com/leehack/llamadart/issues/924)).
- A `ModelLoadOptions.sha256` mismatch in `ImageGenerationEngine.load` names
the main file by position, not by its local path or URL
([#907](https://github.com/leehack/llamadart/issues/907)).

## 0.12.2

- Pair this release with Apple companions `llamadart_llama_cpp_flutter`
Expand Down
14 changes: 11 additions & 3 deletions lib/src/core/engine/chat_session_tool_loop.dart
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,10 @@ class LlamaToolLoopResult {
///
/// To resume a rolled-back turn, add [messages] back with
/// `ChatSession.addMessage`, answer [pendingToolCalls], and call
/// `completeWithTools(const [], ...)`.
/// `completeWithTools(const [], ...)`. After
/// [LlamaToolLoopStopReason.truncated], raise `maxTokens` and send the
/// turn again instead: [messages] ends with the partial reply, and
/// templates such as Ministral 3's can reject the next user turn after it.
final bool rolledBack;

/// Creates a tool loop result.
Expand Down Expand Up @@ -236,8 +239,13 @@ extension ChatSessionToolLoopExtension on ChatSession {
/// [LlamaToolLoopResult.rolledBack].
/// For empty [parts] that is the open turn being continued, including the
/// messages added before this call, such as the app's tool results.
/// Messages that other callers added meanwhile stay. Older turns that
/// context trimming dropped stay dropped, as after [ChatSession.create].
/// Messages that other callers added meanwhile stay. Messages that a
/// [ChatSession.addMessage] override appends while the loop adds a
/// message, including those a synchronous listener adds from inside the
/// override, belong to the turn: a rollback removes them too, and they are
/// neither in [LlamaToolLoopResult.messages] nor reported to
/// [onMessageAdded]. Older turns that context trimming dropped stay
/// dropped, as after [ChatSession.create].
/// [LlamaToolLoopResult.rolledBack] reports a rollback,
/// [LlamaToolLoopResult.messages] keeps the turn, and [onMessageAdded] has
/// already reported the messages this call added.
Expand Down
37 changes: 27 additions & 10 deletions lib/src/core/image/image_generation_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ class ImageGenerationTask {
/// The generated images.
///
/// Throws the task's [LlamaException] when it fails, and
/// [LlamaStateException] when it is cancelled.
/// [LlamaStateException] when it is cancelled. Await this future or attach
/// an error handler as soon as you read it: a stored future that fails
/// before it has a handler reports an uncaught async error.
Future<ImageGenerationResult> get result => _result;

late final Future<ImageGenerationResult> _result = done.then(
Expand Down Expand Up @@ -407,15 +409,30 @@ class ImageGenerationEngine {
};

final effectiveStore = store ?? ModelFileStore();
final paths = await resolveModelSourceFiles(
sources,
store: effectiveStore,
download: download,
onProgress: onProgress,
operation: 'Image model loading',
knownSizes: knownSizes,
assetType: 'image model',
);
final List<String> paths;
try {
paths = await resolveModelSourceFiles(
sources,
store: effectiveStore,
download: download,
onProgress: onProgress,
operation: 'Image model loading',
knownSizes: knownSizes,
assetType: 'image model',
);
} on LlamaModelException catch (error) {
// The download manager names a local file by its path; image errors
// name files by position. ModelLoadOptions.sha256 applies only to a
// single (main) file.
if (download.sha256 == null ||
!error.message.startsWith('Checksum mismatch')) {
rethrow;
}
throw LlamaModelException(
'Checksum mismatch for ${describeImageModelFile(0)}: its SHA-256 '
'does not match ModelLoadOptions.sha256.',
);
}
void throwIfCancelled() {
if (download.cancelToken?.isCancelled ?? false) {
throw LlamaStateException('Image model loading was cancelled.');
Expand Down
12 changes: 11 additions & 1 deletion lib/src/core/speech/speech_to_text.dart
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,9 @@ class SpeechToTextTask {
/// The final transcript.
///
/// Throws the task's [LlamaException] when it fails, and
/// [LlamaStateException] when it is cancelled.
/// [LlamaStateException] when it is cancelled. Await this future or attach
/// an error handler as soon as you read it: a stored future that fails
/// before it has a handler reports an uncaught async error.
Future<SpeechToTextResult> get result => _result;

late final Future<SpeechToTextResult> _result = done.then(
Expand Down Expand Up @@ -933,6 +935,14 @@ class SpeechToTextEngine {
}

final engine = _engine!;
if (engine.isDisposed) {
return const SpeechToTextCapabilities(
isSupported: false,
unsupportedReason:
'The attached LlamaEngine is disposed. Create a new LlamaEngine '
'and attach a new SpeechToTextEngine.',
);
}
if (speechToTextRequiresBackendCapability) {
final backend = engine.backend;
final speechBackend = backend is BackendPromptSpeechToTextSupport
Expand Down
4 changes: 3 additions & 1 deletion lib/src/core/speech/text_to_speech.dart
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,9 @@ class TextToSpeechTask {
/// The complete synthesized audio.
///
/// Throws the task's [LlamaException] when it fails, and
/// [LlamaStateException] when it is cancelled.
/// [LlamaStateException] when it is cancelled. Await this future or attach
/// an error handler as soon as you read it: a stored future that fails
/// before it has a handler reports an uncaught async error.
Future<TextToSpeechResult> get result => _result;

late final Future<TextToSpeechResult> _result = done.then(
Expand Down
65 changes: 65 additions & 0 deletions test/unit/core/engine/chat_session_tool_loop_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -998,6 +998,38 @@ void main() {
expect(session.history.last.content, 'Sunny');
});

test('takes precedence over a cut-off reply and rolls it back', () async {
final earlier = [
_text(LlamaChatRole.user, 'Hi'),
_text(LlamaChatRole.assistant, 'Hello'),
];
earlier.forEach(session.addMessage);
engine.replies
..add(scriptedCalls([('a', 'weather', '{}')]))
..add(() async* {
engine.cancelGeneration();
yield scriptedChunk(content: 'It is sun', finishReason: 'length');
});

final result = await session.sendWithTools(
'Weather',
tools: [_tool('weather', (_) async => 'sunny')],
);

expect(result.stopReason, LlamaToolLoopStopReason.cancelled);
expect(result.completion.finishReason, LlamaFinishReason.length);
expect(result.text, 'It is sun');
expect(result.rounds, 1);
expect(result.rolledBack, isTrue);
expect(session.history, orderedEquals(earlier));
expect(_roles(result.messages), [
LlamaChatRole.user,
LlamaChatRole.assistant,
LlamaChatRole.tool,
LlamaChatRole.assistant,
]);
});

test('reported as a stream error keeps a partial answer', () async {
engine.replies
..add(scriptedCalls([('a', 'weather', '{}')]))
Expand Down Expand Up @@ -1325,6 +1357,39 @@ void main() {
expect(session.systemPrompt, 'Be brief.');
});

test('a class that implements ChatSession over an addMessage that stores '
'copies rolls the copies back', () async {
final copying = _CopyingSession(engine);
[
_text(LlamaChatRole.user, 'Hi'),
_text(LlamaChatRole.assistant, 'Hello'),
].forEach(copying.addMessage);
final delegate = _DelegatingSession(copying);
engine.replies
..add(scriptedCalls([('a', 'weather', '{}')]))
..add(scriptedCalls([('b', 'weather', '{}')]));

final result = await delegate.sendWithTools(
'Weather',
tools: [_tool('weather', (_) async => 'sunny')],
maxRounds: 1,
);

expect(result.stopReason, LlamaToolLoopStopReason.maxRounds);
expect(result.rolledBack, isTrue);
expect(_roles(result.messages), [
LlamaChatRole.user,
LlamaChatRole.assistant,
LlamaChatRole.tool,
LlamaChatRole.assistant,
]);
expect(_toolResults(copying), isEmpty);
expect(
[for (final message in copying.history) message.content],
['Hi', 'Hello'],
);
});

test('completeWithTools sends media parts as the user turn', () async {
engine.replies.add(scriptedAnswer('A cat.'));

Expand Down
82 changes: 82 additions & 0 deletions test/unit/core/image/image_generation_engine_io_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
@TestOn('vm')
library;

import 'dart:io';

import 'package:llamadart/llamadart.dart';
import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_runtime_status.dart';
import 'package:llamadart/src/core/image/image_generation_driver.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';

void main() {
late Directory directory;

setUp(() {
directory = Directory.systemTemp.createTempSync('llamadart_image_io_');
debugImageGenerationDriverOverride = _ProbeOnlyDriver();
});
tearDown(() {
debugImageGenerationDriverOverride = null;
directory.deleteSync(recursive: true);
});

test('the default download manager\'s local checksum mismatch names the '
'main file by position, not by path', () async {
final secretDirectory = Directory(p.join(directory.path, 'secret-user'))
..createSync();
final model = File(p.join(secretDirectory.path, 'private-sd.gguf'))
..writeAsStringSync('weights');

await expectLater(
ImageGenerationEngine.load(
ImageGenerationModel(ModelSource.path(model.path)),
download: ModelLoadOptions(sha256: '0' * 64),
store: ModelFileStore(
downloadManager: DefaultModelDownloadManager.appPrivate(
cacheDirectory: p.join(directory.path, 'cache'),
),
),
),
throwsA(
isA<LlamaModelException>().having(
(error) => '$error',
'toString',
allOf(
contains(
'Checksum mismatch for the main file: its SHA-256 does not '
'match ModelLoadOptions.sha256.',
),
isNot(contains('secret-user')),
isNot(contains('private-sd')),
isNot(contains(directory.path)),
),
),
),
);
});
}

/// A driver that only probes and sizes files; nothing reaches the runtime.
final class _ProbeOnlyDriver implements ImageGenerationDriver {
@override
String get operatingSystem => 'linux';

@override
Future<StableDiffusionRuntimeStatus> probeInBackground() async =>
StableDiffusionRuntimeStatus.available(
version: 'master-929',
commit: '3f8527a',
devices: parseStableDiffusionDeviceList('CPU\tHost\n'),
);

@override
int? fileSize(String path) {
final file = File(path);
return file.existsSync() ? file.lengthSync() : null;
}

@override
dynamic noSuchMethod(Invocation invocation) =>
throw UnimplementedError('${invocation.memberName}');
}
56 changes: 56 additions & 0 deletions test/unit/core/image/image_generation_engine_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1036,6 +1036,56 @@ void main() {
});
}

for (final (name, source, message) in [
(
'local',
_local(_model),
'Checksum mismatch for local model file: $_model.',
),
(
'remote',
_remote,
'Checksum mismatch for hf://owner/sdxs@0123abc/sdxs.gguf.',
),
]) {
test('a checksum mismatch for a single $name file names it by '
'position', () async {
downloads.checksumError = LlamaModelException(message);

await expectLater(
load(_sdxs(source), download: ModelLoadOptions(sha256: 'a' * 64)),
throwsA(
isA<LlamaModelException>().having(
(error) => error.message,
'message',
allOf(
equals(
'Checksum mismatch for the main file: its SHA-256 does not '
'match ModelLoadOptions.sha256.',
),
isNot(contains('sdxs')),
isNot(contains('/models')),
),
),
),
);
expect(driver.started, isEmpty);
});
}

test(
'another model error from a checksummed load passes through',
() async {
final failure = LlamaModelException('Local model file does not exist.');
downloads.checksumError = failure;

await expectLater(
load(_sdxs(), download: ModelLoadOptions(sha256: 'a' * 64)),
throwsA(same(failure)),
);
},
);

test('a checksum for several files is rejected before anything '
'downloads', () async {
await expectLater(
Expand Down Expand Up @@ -2087,6 +2137,9 @@ final class _FakeDownloads implements ModelDownloadManager {
/// a checkpoint and `.safetensors` files to a TAESD.
final Map<String, Uint8List> remoteHeaders = {};
Object? error;

/// Thrown for any file when the load sets [ModelLoadOptions.sha256].
Object? checksumError;
Completer<void>? gate;

static String cachePath(ModelSource source) =>
Expand All @@ -2099,6 +2152,9 @@ final class _FakeDownloads implements ModelDownloadManager {
ModelDownloadProgressCallback? onProgress,
}) async {
calls.add((source, options));
if (options.sha256 != null && checksumError != null) {
throw checksumError!;
}
final path = source.isLocal ? source.path! : cachePath(source);
if (!source.isLocal) {
final failure = error;
Expand Down
Loading
Loading