forked from kherud/java-llama.cpp
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLlamaIterable.java
More file actions
51 lines (44 loc) · 1.52 KB
/
Copy pathLlamaIterable.java
File metadata and controls
51 lines (44 loc) · 1.52 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
// SPDX-FileCopyrightText: 2026 Bernard Ladenthin <bernard.ladenthin@gmail.com>
// SPDX-FileCopyrightText: 2023-2025 Konstantin Herud
//
// SPDX-License-Identifier: MIT
package net.ladenthin.llama;
import org.jetbrains.annotations.NotNull;
/**
* An {@link Iterable} wrapper around {@link LlamaIterator} returned by
* {@link LlamaModel#generate(InferenceParameters)} and {@link LlamaModel#generateChat(InferenceParameters)}.
*
* <p>Implements {@link AutoCloseable} so that a try-with-resources block automatically cancels
* any in-progress generation when the loop exits early (e.g. via {@code break}), preventing the
* native task slot from leaking:
*
* <pre>{@code
* try (LlamaIterable it = model.generate(params)) {
* for (LlamaOutput o : it) {
* if (done) break; // close() cancels the native task automatically
* }
* }
* }</pre>
*
* <p>A plain for-each loop without try-with-resources continues to work; the {@link #close()}
* method just will not be called on early exit in that case.
*/
public final class LlamaIterable implements Iterable<LlamaOutput>, AutoCloseable {
private final LlamaIterator iterator;
LlamaIterable(LlamaIterator iterator) {
this.iterator = iterator;
}
@NotNull
@Override
public LlamaIterator iterator() {
return iterator;
}
/**
* Cancels any in-progress generation. Delegates to {@link LlamaIterator#close()}.
* Safe to call multiple times.
*/
@Override
public void close() {
iterator.close();
}
}