From 23d23c4ad7762e5d5f524dc5084ebd3a7ea5dff6 Mon Sep 17 00:00:00 2001 From: Amith Koujalgi Date: Mon, 17 Feb 2025 22:25:25 +0530 Subject: [PATCH] Added new `createModel` API to make it conform to Ollama's new API - https://github.com/ollama/ollama/blob/main/docs/api.md#create-a-model --- .../apis-model-management/create-model.md | 292 +++++++++++------- .../java/io/github/ollama4j/OllamaAPI.java | 31 ++ .../embeddings/OllamaEmbedRequestBuilder.java | 2 +- .../models/request/CustomModelRequest.java | 45 +++ .../ollama4j/unittests/TestMockedAPIs.java | 10 +- 5 files changed, 266 insertions(+), 114 deletions(-) create mode 100644 src/main/java/io/github/ollama4j/models/request/CustomModelRequest.java diff --git a/docs/docs/apis-model-management/create-model.md b/docs/docs/apis-model-management/create-model.md index a66d815..77b5aeb 100644 --- a/docs/docs/apis-model-management/create-model.md +++ b/docs/docs/apis-model-management/create-model.md @@ -6,7 +6,7 @@ sidebar_position: 5 This API lets you create a custom model on the Ollama server. -### Create a model from an existing Modelfile in the Ollama server +### Create a custom model from an existing model in the Ollama server ```java title="CreateModel.java" import io.github.ollama4j.OllamaAPI; @@ -19,144 +19,220 @@ public class CreateModel { OllamaAPI ollamaAPI = new OllamaAPI(host); - ollamaAPI.createModelWithFilePath("mario", "/path/to/mario/modelfile/on/ollama-server"); - } -} -``` - -### Create a model by passing the contents of Modelfile - -```java title="CreateModel.java" -public class CreateModel { - - public static void main(String[] args) { - - String host = "http://localhost:11434/"; - - OllamaAPI ollamaAPI = new OllamaAPI(host); - - ollamaAPI.createModelWithModelFileContents("mario", "FROM llama2\nSYSTEM You are mario from Super Mario Bros."); + ollamaAPI.createModel(CustomModelRequest.builder().model("mario").from("llama3.2:latest").system("You are Mario from Super Mario Bros.").build()); } } ``` Once created, you can see it when you use [list models](./list-models) API. -### Example of a `Modelfile` +[Read more](https://github.com/ollama/ollama/blob/main/docs/api.md#create-a-model) about custom model creation and the parameters available for model creation. -``` -FROM llama2 -# sets the temperature to 1 [higher is more creative, lower is more coherent] -PARAMETER temperature 1 -# sets the context window size to 4096, this controls how many tokens the LLM can use as context to generate the next token -PARAMETER num_ctx 4096 +[//]: # () +[//]: # (### Example of a `Modelfile`) -# sets a custom system message to specify the behavior of the chat assistant -SYSTEM You are Mario from super mario bros, acting as an assistant. -``` +[//]: # () +[//]: # (```) -### Format of the `Modelfile` +[//]: # (FROM llama2) -```modelfile -# comment -INSTRUCTION arguments -``` +[//]: # (# sets the temperature to 1 [higher is more creative, lower is more coherent]) -| Instruction | Description | -|-------------------------------------|----------------------------------------------------------------| -| [`FROM`](#from-required) (required) | Defines the base model to use. | -| [`PARAMETER`](#parameter) | Sets the parameters for how Ollama will run the model. | -| [`TEMPLATE`](#template) | The full prompt template to be sent to the model. | -| [`SYSTEM`](#system) | Specifies the system message that will be set in the template. | -| [`ADAPTER`](#adapter) | Defines the (Q)LoRA adapters to apply to the model. | -| [`LICENSE`](#license) | Specifies the legal license. | +[//]: # (PARAMETER temperature 1) -#### PARAMETER +[//]: # (# sets the context window size to 4096, this controls how many tokens the LLM can use as context to generate the next token) -The `PARAMETER` instruction defines a parameter that can be set when the model is run. +[//]: # (PARAMETER num_ctx 4096) -| Parameter | Description | Value Type | Example Usage | -|----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|----------------------| -| mirostat | Enable Mirostat sampling for controlling perplexity. (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0) | int | mirostat 0 | -| mirostat_eta | Influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. (Default: 0.1) | float | mirostat_eta 0.1 | -| mirostat_tau | Controls the balance between coherence and diversity of the output. A lower value will result in more focused and coherent text. (Default: 5.0) | float | mirostat_tau 5.0 | -| num_ctx | Sets the size of the context window used to generate the next token. (Default: 2048) | int | num_ctx 4096 | -| num_gqa | The number of GQA groups in the transformer layer. Required for some models, for example it is 8 for llama2:70b | int | num_gqa 1 | -| num_gpu | The number of layers to send to the GPU(s). On macOS it defaults to 1 to enable metal support, 0 to disable. | int | num_gpu 50 | -| num_thread | Sets the number of threads to use during computation. By default, Ollama will detect this for optimal performance. It is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). | int | num_thread 8 | -| repeat_last_n | Sets how far back for the model to look back to prevent repetition. (Default: 64, 0 = disabled, -1 = num_ctx) | int | repeat_last_n 64 | -| repeat_penalty | Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. (Default: 1.1) | float | repeat_penalty 1.1 | -| temperature | The temperature of the model. Increasing the temperature will make the model answer more creatively. (Default: 0.8) | float | temperature 0.7 | -| seed | Sets the random number seed to use for generation. Setting this to a specific number will make the model generate the same text for the same prompt. (Default: 0) | int | seed 42 | -| stop | Sets the stop sequences to use. When this pattern is encountered the LLM will stop generating text and return. Multiple stop patterns may be set by specifying multiple separate `stop` parameters in a modelfile. | string | stop "AI assistant:" | -| tfs_z | Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. (default: 1) | float | tfs_z 1 | -| num_predict | Maximum number of tokens to predict when generating text. (Default: 128, -1 = infinite generation, -2 = fill context) | int | num_predict 42 | -| top_k | Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. (Default: 40) | int | top_k 40 | -| top_p | Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. (Default: 0.9) | float | top_p 0.9 | +[//]: # () +[//]: # (# sets a custom system message to specify the behavior of the chat assistant) -#### TEMPLATE +[//]: # (SYSTEM You are Mario from super mario bros, acting as an assistant.) -`TEMPLATE` of the full prompt template to be passed into the model. It may include (optionally) a system message and a -user's prompt. This is used to create a full custom prompt, and syntax may be model specific. You can usually find the -template for a given model in the readme for that model. +[//]: # (```) -#### Template Variables +[//]: # () +[//]: # (### Format of the `Modelfile`) -| Variable | Description | -|-----------------|---------------------------------------------------------------------------------------------------------------| -| `{{ .System }}` | The system message used to specify custom behavior, this must also be set in the Modelfile as an instruction. | -| `{{ .Prompt }}` | The incoming prompt, this is not specified in the model file and will be set based on input. | -| `{{ .First }}` | A boolean value used to render specific template information for the first generation of a session. | +[//]: # () +[//]: # (```modelfile) -```modelfile -TEMPLATE """ -{{- if .First }} -### System: -{{ .System }} -{{- end }} +[//]: # (# comment) -### User: -{{ .Prompt }} +[//]: # (INSTRUCTION arguments) -### Response: -""" +[//]: # (```) -SYSTEM """""" -``` +[//]: # () +[//]: # (| Instruction | Description |) -### SYSTEM +[//]: # (|-------------------------------------|----------------------------------------------------------------|) -The `SYSTEM` instruction specifies the system message to be used in the template, if applicable. +[//]: # (| [`FROM`](#from-required) (required) | Defines the base model to use. |) -```modelfile -SYSTEM """""" -``` +[//]: # (| [`PARAMETER`](#parameter) | Sets the parameters for how Ollama will run the model. |) -### ADAPTER +[//]: # (| [`TEMPLATE`](#template) | The full prompt template to be sent to the model. |) -The `ADAPTER` instruction specifies the LoRA adapter to apply to the base model. The value of this instruction should be -an absolute path or a path relative to the Modelfile and the file must be in a GGML file format. The adapter should be -tuned from the base model otherwise the behaviour is undefined. +[//]: # (| [`SYSTEM`](#system) | Specifies the system message that will be set in the template. |) -```modelfile -ADAPTER ./ollama-lora.bin -``` +[//]: # (| [`ADAPTER`](#adapter) | Defines the (Q)LoRA adapters to apply to the model. |) -### LICENSE +[//]: # (| [`LICENSE`](#license) | Specifies the legal license. |) -The `LICENSE` instruction allows you to specify the legal license under which the model used with this Modelfile is -shared or distributed. +[//]: # () +[//]: # (#### PARAMETER) -```modelfile -LICENSE """ - -""" -``` +[//]: # () +[//]: # (The `PARAMETER` instruction defines a parameter that can be set when the model is run.) -## Notes +[//]: # () +[//]: # (| Parameter | Description | Value Type | Example Usage |) -- the **`Modelfile` is not case sensitive**. In the examples, uppercase instructions are used to make it easier to - distinguish it from arguments. -- Instructions can be in any order. In the examples, the `FROM` instruction is first to keep it easily readable. +[//]: # (|----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|----------------------|) -Read more about Modelfile: https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md \ No newline at end of file +[//]: # (| mirostat | Enable Mirostat sampling for controlling perplexity. (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0) | int | mirostat 0 |) + +[//]: # (| mirostat_eta | Influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. (Default: 0.1) | float | mirostat_eta 0.1 |) + +[//]: # (| mirostat_tau | Controls the balance between coherence and diversity of the output. A lower value will result in more focused and coherent text. (Default: 5.0) | float | mirostat_tau 5.0 |) + +[//]: # (| num_ctx | Sets the size of the context window used to generate the next token. (Default: 2048) | int | num_ctx 4096 |) + +[//]: # (| num_gqa | The number of GQA groups in the transformer layer. Required for some models, for example it is 8 for llama2:70b | int | num_gqa 1 |) + +[//]: # (| num_gpu | The number of layers to send to the GPU(s). On macOS it defaults to 1 to enable metal support, 0 to disable. | int | num_gpu 50 |) + +[//]: # (| num_thread | Sets the number of threads to use during computation. By default, Ollama will detect this for optimal performance. It is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). | int | num_thread 8 |) + +[//]: # (| repeat_last_n | Sets how far back for the model to look back to prevent repetition. (Default: 64, 0 = disabled, -1 = num_ctx) | int | repeat_last_n 64 |) + +[//]: # (| repeat_penalty | Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. (Default: 1.1) | float | repeat_penalty 1.1 |) + +[//]: # (| temperature | The temperature of the model. Increasing the temperature will make the model answer more creatively. (Default: 0.8) | float | temperature 0.7 |) + +[//]: # (| seed | Sets the random number seed to use for generation. Setting this to a specific number will make the model generate the same text for the same prompt. (Default: 0) | int | seed 42 |) + +[//]: # (| stop | Sets the stop sequences to use. When this pattern is encountered the LLM will stop generating text and return. Multiple stop patterns may be set by specifying multiple separate `stop` parameters in a modelfile. | string | stop "AI assistant:" |) + +[//]: # (| tfs_z | Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. (default: 1) | float | tfs_z 1 |) + +[//]: # (| num_predict | Maximum number of tokens to predict when generating text. (Default: 128, -1 = infinite generation, -2 = fill context) | int | num_predict 42 |) + +[//]: # (| top_k | Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. (Default: 40) | int | top_k 40 |) + +[//]: # (| top_p | Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. (Default: 0.9) | float | top_p 0.9 |) + +[//]: # () +[//]: # (#### TEMPLATE) + +[//]: # () +[//]: # (`TEMPLATE` of the full prompt template to be passed into the model. It may include (optionally) a system message and a) + +[//]: # (user's prompt. This is used to create a full custom prompt, and syntax may be model specific. You can usually find the) + +[//]: # (template for a given model in the readme for that model.) + +[//]: # () +[//]: # (#### Template Variables) + +[//]: # () +[//]: # (| Variable | Description |) + +[//]: # (|-----------------|---------------------------------------------------------------------------------------------------------------|) + +[//]: # (| `{{ .System }}` | The system message used to specify custom behavior, this must also be set in the Modelfile as an instruction. |) + +[//]: # (| `{{ .Prompt }}` | The incoming prompt, this is not specified in the model file and will be set based on input. |) + +[//]: # (| `{{ .First }}` | A boolean value used to render specific template information for the first generation of a session. |) + +[//]: # () +[//]: # (```modelfile) + +[//]: # (TEMPLATE """) + +[//]: # ({{- if .First }}) + +[//]: # (### System:) + +[//]: # ({{ .System }}) + +[//]: # ({{- end }}) + +[//]: # () +[//]: # (### User:) + +[//]: # ({{ .Prompt }}) + +[//]: # () +[//]: # (### Response:) + +[//]: # (""") + +[//]: # () +[//]: # (SYSTEM """""") + +[//]: # (```) + +[//]: # () +[//]: # (### SYSTEM) + +[//]: # () +[//]: # (The `SYSTEM` instruction specifies the system message to be used in the template, if applicable.) + +[//]: # () +[//]: # (```modelfile) + +[//]: # (SYSTEM """""") + +[//]: # (```) + +[//]: # () +[//]: # (### ADAPTER) + +[//]: # () +[//]: # (The `ADAPTER` instruction specifies the LoRA adapter to apply to the base model. The value of this instruction should be) + +[//]: # (an absolute path or a path relative to the Modelfile and the file must be in a GGML file format. The adapter should be) + +[//]: # (tuned from the base model otherwise the behaviour is undefined.) + +[//]: # () +[//]: # (```modelfile) + +[//]: # (ADAPTER ./ollama-lora.bin) + +[//]: # (```) + +[//]: # () +[//]: # (### LICENSE) + +[//]: # () +[//]: # (The `LICENSE` instruction allows you to specify the legal license under which the model used with this Modelfile is) + +[//]: # (shared or distributed.) + +[//]: # () +[//]: # (```modelfile) + +[//]: # (LICENSE """) + +[//]: # () + +[//]: # (""") + +[//]: # (```) + +[//]: # () +[//]: # (## Notes) + +[//]: # () +[//]: # (- the **`Modelfile` is not case sensitive**. In the examples, uppercase instructions are used to make it easier to) + +[//]: # ( distinguish it from arguments.) + +[//]: # (- Instructions can be in any order. In the examples, the `FROM` instruction is first to keep it easily readable.) + +[//]: # () +[//]: # (Read more about Modelfile: https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md) \ No newline at end of file diff --git a/src/main/java/io/github/ollama4j/OllamaAPI.java b/src/main/java/io/github/ollama4j/OllamaAPI.java index 790478b..7d8385f 100644 --- a/src/main/java/io/github/ollama4j/OllamaAPI.java +++ b/src/main/java/io/github/ollama4j/OllamaAPI.java @@ -391,6 +391,7 @@ public class OllamaAPI { * @throws InterruptedException if the operation is interrupted * @throws URISyntaxException if the URI for the request is malformed */ + @Deprecated public void createModelWithFilePath(String modelName, String modelFilePath) throws IOException, InterruptedException, OllamaBaseException, URISyntaxException { String url = this.host + "/api/create"; String jsonData = new CustomModelFilePathRequest(modelName, modelFilePath).toString(); @@ -423,6 +424,7 @@ public class OllamaAPI { * @throws InterruptedException if the operation is interrupted * @throws URISyntaxException if the URI for the request is malformed */ + @Deprecated public void createModelWithModelFileContents(String modelName, String modelFileContents) throws IOException, InterruptedException, OllamaBaseException, URISyntaxException { String url = this.host + "/api/create"; String jsonData = new CustomModelFileContentsRequest(modelName, modelFileContents).toString(); @@ -442,6 +444,35 @@ public class OllamaAPI { } } + /** + * Create a custom model. Read more about custom model creation here. + * + * @param customModelRequest custom model spec + * @throws OllamaBaseException if the response indicates an error status + * @throws IOException if an I/O error occurs during the HTTP request + * @throws InterruptedException if the operation is interrupted + * @throws URISyntaxException if the URI for the request is malformed + */ + public void createModel(CustomModelRequest customModelRequest) throws IOException, InterruptedException, OllamaBaseException, URISyntaxException { + String url = this.host + "/api/create"; + String jsonData = customModelRequest.toString(); + HttpRequest request = getRequestBuilderDefault(new URI(url)).header("Accept", "application/json").header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8)).build(); + HttpClient client = HttpClient.newHttpClient(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + int statusCode = response.statusCode(); + String responseString = response.body(); + if (statusCode != 200) { + throw new OllamaBaseException(statusCode + " - " + responseString); + } + if (responseString.contains("error")) { + throw new OllamaBaseException(responseString); + } + if (verbose) { + logger.info(responseString); + } + } + /** * Delete a model from Ollama server. * diff --git a/src/main/java/io/github/ollama4j/models/embeddings/OllamaEmbedRequestBuilder.java b/src/main/java/io/github/ollama4j/models/embeddings/OllamaEmbedRequestBuilder.java index 7b85789..83c619d 100644 --- a/src/main/java/io/github/ollama4j/models/embeddings/OllamaEmbedRequestBuilder.java +++ b/src/main/java/io/github/ollama4j/models/embeddings/OllamaEmbedRequestBuilder.java @@ -5,7 +5,7 @@ import io.github.ollama4j.utils.Options; import java.util.List; /** - * Builderclass to easily create Requests for Embedding models using ollama. + * Builder class to easily create Requests for Embedding models using ollama. */ public class OllamaEmbedRequestBuilder { diff --git a/src/main/java/io/github/ollama4j/models/request/CustomModelRequest.java b/src/main/java/io/github/ollama4j/models/request/CustomModelRequest.java new file mode 100644 index 0000000..15725f0 --- /dev/null +++ b/src/main/java/io/github/ollama4j/models/request/CustomModelRequest.java @@ -0,0 +1,45 @@ +package io.github.ollama4j.models.request; + +import static io.github.ollama4j.utils.Utils.getObjectMapper; + +import com.fasterxml.jackson.core.JsonProcessingException; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.Data; +import lombok.AllArgsConstructor; +import lombok.Builder; + +import java.util.List; +import java.util.Map; + + +@Data +@AllArgsConstructor +@Builder +public class CustomModelRequest { + private String model; + private String from; + private Map files; + private Map adapters; + private String template; + private Object license; // Using Object to handle both String and List + private String system; + private Map parameters; + private List messages; + private Boolean stream; + private Boolean quantize; + + public CustomModelRequest() { + this.stream = true; + this.quantize = false; + } + + @Override + public String toString() { + try { + return getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/io/github/ollama4j/unittests/TestMockedAPIs.java b/src/test/java/io/github/ollama4j/unittests/TestMockedAPIs.java index c775a89..8499cd8 100644 --- a/src/test/java/io/github/ollama4j/unittests/TestMockedAPIs.java +++ b/src/test/java/io/github/ollama4j/unittests/TestMockedAPIs.java @@ -6,6 +6,7 @@ import io.github.ollama4j.exceptions.RoleNotFoundException; import io.github.ollama4j.models.chat.OllamaChatMessageRole; import io.github.ollama4j.models.embeddings.OllamaEmbedRequestModel; import io.github.ollama4j.models.embeddings.OllamaEmbedResponseModel; +import io.github.ollama4j.models.request.CustomModelRequest; import io.github.ollama4j.models.response.ModelDetail; import io.github.ollama4j.models.response.OllamaAsyncResultStreamer; import io.github.ollama4j.models.response.OllamaResult; @@ -52,12 +53,11 @@ class TestMockedAPIs { @Test void testCreateModel() { OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class); - String model = OllamaModelType.LLAMA2; - String modelFilePath = "FROM llama2\nSYSTEM You are mario from Super Mario Bros."; + CustomModelRequest customModelRequest = CustomModelRequest.builder().model("mario").from("llama3.2:latest").system("You are Mario from Super Mario Bros.").build(); try { - doNothing().when(ollamaAPI).createModelWithModelFileContents(model, modelFilePath); - ollamaAPI.createModelWithModelFileContents(model, modelFilePath); - verify(ollamaAPI, times(1)).createModelWithModelFileContents(model, modelFilePath); + doNothing().when(ollamaAPI).createModel(customModelRequest); + ollamaAPI.createModel(customModelRequest); + verify(ollamaAPI, times(1)).createModel(customModelRequest); } catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) { throw new RuntimeException(e); }