Compare commits

...

27 Commits

Author SHA1 Message Date
Amith Koujalgi
339f788832
Merge pull request #133 from ollama4j/docs-updates
All checks were successful
Mark stale issues / stale (push) Successful in 29s
Update index.js
2025-04-20 00:33:32 +05:30
amithkoujalgi
ccf738127d
Update index.js 2025-04-20 00:33:00 +05:30
Amith Koujalgi
b90c7a027a
Merge pull request #132 from ollama4j/docs-updates
Updated docs
2025-04-20 00:11:12 +05:30
amithkoujalgi
2b0506a393
Updated docs 2025-04-20 00:10:37 +05:30
Amith Koujalgi
81278be964
Merge pull request #131 from ollama4j/docs-updates
Updated docs
2025-04-19 23:36:47 +05:30
amithkoujalgi
cef4a00d17
Updated docs 2025-04-19 23:36:03 +05:30
Amith Koujalgi
9083c3ace3
Merge pull request #130 from ollama4j/docs-updates
Updated docs
2025-04-19 23:25:06 +05:30
amithkoujalgi
79923451d0
Updated docs 2025-04-19 23:24:44 +05:30
Amith Koujalgi
02168e6fd9
Merge pull request #129 from ollama4j/docs-updates
Updated docs
2025-04-19 23:16:09 +05:30
amithkoujalgi
a3debc0983
Updated docs 2025-04-19 23:15:27 +05:30
Amith Koujalgi
9a0908f504
Merge pull request #128 from ollama4j/docs-updates
Updated docs
2025-04-19 22:14:09 +05:30
amithkoujalgi
4d03673d8c
Updated docs 2025-04-19 22:11:36 +05:30
Amith Koujalgi
c4ebd5cd31
Merge pull request #127 from ollama4j/docs-updates
Updated docs
2025-04-19 00:24:08 +05:30
amithkoujalgi
43361ff271
Updated docs 2025-04-19 00:23:27 +05:30
Amith Koujalgi
f1d9fc154a
Merge pull request #126 from ollama4j/docs-updates
Updated docs
2025-04-19 00:19:27 +05:30
amithkoujalgi
9811d9f7fd
Updated docs 2025-04-19 00:16:23 +05:30
Amith Koujalgi
63e2fc2c49
Merge pull request #125 from ollama4j/docs-updates
All checks were successful
Mark stale issues / stale (push) Successful in 57s
Docs updates
2025-04-18 23:03:10 +05:30
amithkoujalgi
63b3bcb71e
Updated docs 2025-04-18 23:02:32 +05:30
amithkoujalgi
9d9bc53e0b
Updated docs 2025-04-18 22:52:08 +05:30
amithkoujalgi
8fd203931d
Updated docs 2025-04-18 22:45:30 +05:30
amithkoujalgi
9c181486a5
Added CodeEmbed component to embed code snippets in markdowns 2025-04-18 12:15:49 +05:30
amithkoujalgi
2b036c8a62
Added CodeEmbed component to embed code snippets in markdowns 2025-04-17 20:31:01 +05:30
Amith Koujalgi
ec0ebc9654 Update list-library-models.md 2025-04-17 18:39:07 +05:30
Amith Koujalgi
c2e4e3fa7f
Merge pull request #124 from ollama4j/113-tests-fix
All checks were successful
Mark stale issues / stale (push) Successful in 42s
Added search for docs
2025-04-16 21:43:36 +05:30
amithkoujalgi
d6a57560fe
added search for docs 2025-04-16 21:41:33 +05:30
Amith Koujalgi
a4c47216f5
Merge pull request #123 from ollama4j/amithkoujalgi-patch-1
Update README.md
2025-04-16 21:16:19 +05:30
Amith Koujalgi
202fbef8b7
Update README.md 2025-04-16 21:15:49 +05:30
44 changed files with 17683 additions and 17637 deletions

View File

@ -29,10 +29,10 @@ list-releases:
--compressed \
--silent | jq -r '.components[].version'
docs:
docs-build:
npm i --prefix docs && npm run build --prefix docs
docs-dev:
docs-serve:
npm i --prefix docs && npm run start --prefix docs
start-cpu:

View File

@ -102,7 +102,7 @@ In your Maven project, add this dependency:
<dependency>
<groupId>io.github.ollama4j</groupId>
<artifactId>ollama4j</artifactId>
<version>1.0.93</version>
<version>1.0.100</version>
</dependency>
```
@ -158,7 +158,7 @@ In your Maven project, add this dependency:
<dependency>
<groupId>io.github.ollama4j</groupId>
<artifactId>ollama4j</artifactId>
<version>1.0.93</version>
<version>1.0.100</version>
</dependency>
```
@ -168,7 +168,7 @@ In your Maven project, add this dependency:
```groovy
dependencies {
implementation 'io.github.ollama4j:ollama4j:1.0.93'
implementation 'io.github.ollama4j:ollama4j:1.0.100'
}
```

View File

@ -1,9 +0,0 @@
---
slug: welcome
title: Welcome
authors: [ amith ]
tags: [ Java, AI, LLM, GenAI, GenerativeAI, Ollama, Ollama4J, OpenSource, Developers
]
---
Welcome Java Developers!

View File

@ -1,6 +1,6 @@
---
slug: release-post
title: Release
title: First Release 🚀
authors: [ amith ]
tags: [ Java, AI, LLM, GenAI, GenerativeAI, Ollama, Ollama4j, OpenSource, Developers
]

View File

@ -0,0 +1,26 @@
---
sidebar_position: 2
---
# Set Bearer Authentication
This API lets you set the bearer authentication for the Ollama client. This would help in scenarios where
Ollama server would be setup behind a gateway/reverse proxy with bearer auth.
After configuring bearer authentication, all subsequent requests will include the Bearer Auth header.
```java
import io.github.ollama4j.OllamaAPI;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
ollamaAPI.setBearerAuth("YOUR-TOKEN");
}
}
```

View File

@ -0,0 +1,69 @@
---
sidebar_position: 8
---
import CodeEmbed from '@site/src/components/CodeEmbed';
# Chat with Tools
### Using Tools in Chat
If you want to have a natural back-and-forth chat experience with tools, you can directly integrate tools into
the `chat()` method, instead of using the `generateWithTools()` method. This allows you to register tools that are
automatically used during the conversation between the user and the assistant, creating a more conversational
experience.
When the model determines that a tool should be used, the tool is automatically executed. The result is then seamlessly
incorporated back into the conversation, enhancing the interaction with real-world data and actions.
The following example demonstrates usage of a simple tool, registered with the `OllamaAPI`, and then used within a chat
session. The tool invocation and response handling are all managed internally by the API.
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/ChatWithTools.java"/>
::::tip[LLM Response]
> First answer: 6527fb60-9663-4073-b59e-855526e0a0c2 is the ID of the employee named 'Rahul Kumar'.
>
> Second answer: Kumar is the last name of the employee named 'Rahul Kumar'.
::::
This tool calling can also be done using the streaming API.
### Annotation-Based Tool Registration
Ollama4j provides a declarative and convenient way to define and register tools using Java annotations and reflection.
This approach offers an alternative to the more verbose, explicit tool registration method.
To use a method as a tool within a chat call, follow these steps:
* **Annotate the Tool Method:**
* Use the `@ToolSpec` annotation to mark a method as a tool. This annotation describes the tool's purpose.
* Use the `@ToolProperty` annotation to define the input parameters of the tool. The following data types are
currently supported:
* `java.lang.String`
* `java.lang.Integer`
* `java.lang.Boolean`
* `java.math.BigDecimal`
* **Annotate the Ollama Service Class:**
* Annotate the class that interacts with the `OllamaAPI` client using the `@OllamaToolService` annotation. Reference
the provider class(es) containing the `@ToolSpec` annotated methods within this annotation.
* **Register the Annotated Tools:**
* Before making a chat request with the `OllamaAPI`, call the `OllamaAPI.registerAnnotatedTools()` method. This
registers the annotated tools, making them available for use during the chat session.
Let's try an example. Consider an `OllamaToolService` class that needs to ask the LLM a question that can only be answered by a specific tool.
This tool is implemented within a `GlobalConstantGenerator` class. Following is the code that exposes an annotated method as a tool:
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/toolcalling/annotated/GlobalConstantGenerator.java"/>
The annotated method can then be used as a tool in the chat session:
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/toolcalling/annotated/AnnotatedToolCallingExample.java"/>
Running the above would produce a response similar to:
::::tip[LLM Response]
> First answer: 0.0000112061 is the most important constant in the world using 10 digits, according to my function. This constant is known as Planck's constant and plays a fundamental role in quantum mechanics. It relates energy and frequency in electromagnetic radiation and action (the product of momentum and distance) for particles.
>
> Second answer: 3-digit constant: 8.001
::::

View File

@ -2,267 +2,109 @@
sidebar_position: 7
---
import CodeEmbed from '@site/src/components/CodeEmbed';
import TypewriterTextarea from '@site/src/components/TypewriterTextarea';
# Chat
This API lets you create a conversation with LLMs. Using this API enables you to ask questions to the model including
information using the history of already asked questions and the respective answers.
### Create a new conversation and use chat history to augment follow up questions
## Create a new conversation and use chat history to augment follow up questions
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
import io.github.ollama4j.models.chat.OllamaChatRequestBuilder;
import io.github.ollama4j.models.chat.OllamaChatRequest;
import io.github.ollama4j.models.chat.OllamaChatResult;
import io.github.ollama4j.types.OllamaModelType;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
OllamaChatRequestBuilder builder = OllamaChatRequestBuilder.getInstance(OllamaModelType.LLAMA2);
// create first user question
OllamaChatRequest requestModel = builder.withMessage(OllamaChatMessageRole.USER, "What is the capital of France?")
.build();
// start conversation with model
OllamaChatResult chatResult = ollamaAPI.chat(requestModel);
System.out.println("First answer: " + chatResult.getResponseModel().getMessage().getContent());
// create next userQuestion
requestModel = builder.withMessages(chatResult.getChatHistory()).withMessage(OllamaChatMessageRole.USER, "And what is the second largest city?").build();
// "continue" conversation with model
chatResult = ollamaAPI.chat(requestModel);
System.out.println("Second answer: " + chatResult.getResponseModel().getMessage().getContent());
System.out.println("Chat History: " + chatResult.getChatHistory());
}
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/ChatExample.java" />
You will get a response similar to:
> First answer: Should be Paris!
::::tip[LLM Response]
> First answer: The capital of France is Paris.
>
> Second answer: Marseille.
> Second answer: The second-largest city in France is Marseille.
>
> Chat History:
```json
[
{
"role": "user",
"content": "What is the capital of France?",
"images": []
},
{
"role": "assistant",
"content": "Should be Paris!",
"images": []
},
{
"role": "user",
"content": "And what is the second largest city?",
"images": []
},
{
"role": "assistant",
"content": "Marseille.",
"images": []
}
]
[{
"role" : "user",
"content" : "What is the capital of France?",
"images" : null,
"tool_calls" : [ ]
}, {
"role" : "assistant",
"content" : "The capital of France is Paris.",
"images" : null,
"tool_calls" : null
}, {
"role" : "user",
"content" : "And what is the second largest city?",
"images" : null,
"tool_calls" : [ ]
}, {
"role" : "assistant",
"content" : "The second-largest city in France is Marseille.",
"images" : null,
"tool_calls" : null
}]
```
::::
## Conversational loop
### Create a conversation where the answer is streamed
```java
public class Main {
public static void main(String[] args) {
OllamaAPI ollamaAPI = new OllamaAPI();
ollamaAPI.setRequestTimeoutSeconds(60);
OllamaChatRequestBuilder builder = OllamaChatRequestBuilder.getInstance("<your-model>");
OllamaChatRequest requestModel = builder.withMessage(OllamaChatMessageRole.USER, "<your-first-message>").build();
OllamaChatResult initialChatResult = ollamaAPI.chat(requestModel);
System.out.println(initialChatResult.getResponse());
List<OllamaChatMessage> history = initialChatResult.getChatHistory();
while (true) {
OllamaChatResult chatResult = ollamaAPI.chat(builder.withMessages(history).withMessage(OllamaChatMessageRole.USER, "<your-new-message").build());
System.out.println(chatResult.getResponse());
history = chatResult.getChatHistory();
}
}
}
```
## Create a conversation where the answer is streamed
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
import io.github.ollama4j.models.chat.OllamaChatRequest;
import io.github.ollama4j.models.chat.OllamaChatRequestBuilder;
import io.github.ollama4j.models.chat.OllamaChatResult;
import io.github.ollama4j.models.generate.OllamaStreamHandler;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
OllamaChatRequestBuilder builder = OllamaChatRequestBuilder.getInstance(config.getModel());
OllamaChatRequest requestModel = builder.withMessage(OllamaChatMessageRole.USER,
"What is the capital of France? And what's France's connection with Mona Lisa?")
.build();
// define a handler (Consumer<String>)
OllamaStreamHandler streamHandler = (s) -> {
System.out.println(s);
};
OllamaChatResult chatResult = ollamaAPI.chat(requestModel, streamHandler);
}
}
```
You will get a response similar to:
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/ChatStreamingWithTokenConcatenationExample.java" />
<!-- ::::tip[LLM Response]
>
> The
>
> The capital
>
> The capital of
>
> The capital of France
>
> The capital of France is
>
> The capital of France is Paris
>
> The capital of France is Paris.
>
:::: -->
## Use a simple Console Output Stream Handler
<TypewriterTextarea
textContent='The capital of France is Paris.'
typingSpeed={30}
pauseBetweenSentences={1200}
height='55px'
width='100%'
/>
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.impl.ConsoleOutputStreamHandler;
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
import io.github.ollama4j.models.chat.OllamaChatRequestBuilder;
import io.github.ollama4j.models.chat.OllamaChatRequest;
import io.github.ollama4j.models.generate.OllamaStreamHandler;
import io.github.ollama4j.types.OllamaModelType;
### Using a simple Console Output Stream Handler
public class Main {
public static void main(String[] args) throws Exception {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/ConsoleOutputStreamHandlerExample.java" />
OllamaChatRequestBuilder builder = OllamaChatRequestBuilder.getInstance(OllamaModelType.LLAMA2);
OllamaChatRequest requestModel = builder.withMessage(OllamaChatMessageRole.USER, "List all cricket world cup teams of 2019. Name the teams!")
.build();
OllamaStreamHandler streamHandler = new ConsoleOutputStreamHandler();
ollamaAPI.chat(requestModel, streamHandler);
}
}
```
### With a Stream Handler to receive the tokens as they are generated
## Create a new conversation with individual system prompt
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/ChatStreamingExample.java" />
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
import io.github.ollama4j.models.chat.OllamaChatRequestBuilder;
import io.github.ollama4j.models.chat.OllamaChatRequest;
import io.github.ollama4j.models.chat.OllamaChatResult;
import io.github.ollama4j.types.OllamaModelType;
### Create a new conversation with custom system prompt
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/ChatWithCustomSystemPrompt.java" />
You will get a response as:
::::tip[LLM Response]
> Shhh!
::::
public class Main {
## Create a conversation about an image (requires a vision model)
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
OllamaChatRequestBuilder builder = OllamaChatRequestBuilder.getInstance(OllamaModelType.LLAMA2);
// create request with system-prompt (overriding the model defaults) and user question
OllamaChatRequest requestModel = builder.withMessage(OllamaChatMessageRole.SYSTEM, "You are a silent bot that only says 'NI'. Do not say anything else under any circumstances!")
.withMessage(OllamaChatMessageRole.USER, "What is the capital of France? And what's France's connection with Mona Lisa?")
.build();
// start conversation with model
OllamaChatResult chatResult = ollamaAPI.chat(requestModel);
System.out.println(chatResult.getResponseModel());
}
}
```
You will get a response similar to:
> NI.
## Create a conversation about an image (requires model with image recognition skills)
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
import io.github.ollama4j.models.chat.OllamaChatRequest;
import io.github.ollama4j.models.chat.OllamaChatRequestBuilder;
import io.github.ollama4j.models.chat.OllamaChatResult;
import io.github.ollama4j.types.OllamaModelType;
import java.io.File;
import java.util.List;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
OllamaChatRequestBuilder builder = OllamaChatRequestBuilder.getInstance(OllamaModelType.LLAVA);
// Load Image from File and attach to user message (alternatively images could also be added via URL)
OllamaChatRequest requestModel =
builder.withMessage(OllamaChatMessageRole.USER, "What's in the picture?",
List.of(
new File("/path/to/image"))).build();
OllamaChatResult chatResult = ollamaAPI.chat(requestModel);
System.out.println("First answer: " + chatResult.getResponseModel());
builder.reset();
// Use history to ask further questions about the image or assistant answer
requestModel =
builder.withMessages(chatResult.getChatHistory())
.withMessage(OllamaChatMessageRole.USER, "What's the dogs breed?").build();
chatResult = ollamaAPI.chat(requestModel);
System.out.println("Second answer: " + chatResult.getResponseModel());
}
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/ChatWithImage.java" />
You will get a response similar to:
::::tip[LLM Response]
> First Answer: The image shows a dog sitting on the bow of a boat that is docked in calm water. The boat has two
> levels, with the lower level containing seating and what appears to be an engine cover. The dog seems relaxed and
> comfortable on the boat, looking out over the water. The background suggests it might be late afternoon or early
@ -272,11 +114,4 @@ You will get a response similar to:
> appears to be medium-sized with a short coat and a brown coloration, which might suggest that it is a Golden Retriever
> or a similar breed. Without more details like ear shape and tail length, it's not possible to identify the exact breed
> confidently.
[//]: # (Generated using: https://emgithub.com/)
<iframe style={{ width: '100%', height: '919px', border: 'none' }} allow="clipboard-write" src="https://emgithub.com/iframe.html?target=https%3A%2F%2Fgithub.com%2Follama4j%2Follama4j-examples%2Fblob%2Fmain%2Fsrc%2Fmain%2Fjava%2Fio%2Fgithub%2Follama4j%2Fexamples%2FChatExample.java&style=default&type=code&showBorder=on&showLineNumbers=on&showFileMeta=on&showFullPath=on&showCopy=on" />
<a href="https://github.com/ollama4j/ollama4j-examples/blob/main/src/main/java/io/github/ollama4j/examples/ChatExample.java" target="_blank">
View ChatExample.java on GitHub
</a>
::::

View File

@ -1,5 +1,5 @@
---
sidebar_position: 8
sidebar_position: 9
---
# Custom Roles

View File

@ -2,7 +2,9 @@
sidebar_position: 2
---
# Generate - Async
import CodeEmbed from '@site/src/components/CodeEmbed';
# Generate (Async)
This API lets you ask questions to the LLMs in a asynchronous way.
This is particularly helpful when you want to issue a generate request to the LLM and collect the response in the
@ -11,38 +13,18 @@ background (such as threads) without blocking your code until the response arriv
This API corresponds to
the [completion](https://github.com/jmorganca/ollama/blob/main/docs/api.md#generate-a-completion) API.
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.OllamaAsyncResultStreamer;
import io.github.ollama4j.types.OllamaModelType;
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/GenerateAsync.java" />
public class Main {
::::tip[LLM Response]
Here are the participating teams in the 2019 ICC Cricket World Cup:
public static void main(String[] args) throws Exception {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
ollamaAPI.setRequestTimeoutSeconds(60);
String prompt = "List all cricket world cup teams of 2019.";
OllamaAsyncResultStreamer streamer = ollamaAPI.generateAsync(OllamaModelType.LLAMA3, prompt, false);
// Set the poll interval according to your needs.
// Smaller the poll interval, more frequently you receive the tokens.
int pollIntervalMilliseconds = 1000;
while (true) {
String tokens = streamer.getStream().poll();
System.out.print(tokens);
if (!streamer.isAlive()) {
break;
}
Thread.sleep(pollIntervalMilliseconds);
}
System.out.println("\n------------------------");
System.out.println("Complete Response:");
System.out.println("------------------------");
System.out.println(streamer.getCompleteResponse());
}
}
```
1. Australia
2. Bangladesh
3. India
4. New Zealand
5. Pakistan
6. England
7. South Africa
8. West Indies (as a team)
9. Afghanistan
::::

File diff suppressed because one or more lines are too long

View File

@ -1,8 +1,10 @@
---
sidebar_position: 4
sidebar_position: 3
---
# Generate - With Image Files
import CodeEmbed from '@site/src/components/CodeEmbed';
# Generate with Image Files
This API lets you ask questions along with the image files to the LLMs.
This API corresponds to
@ -21,34 +23,11 @@ If you have this image downloaded and you pass the path to the downloaded image
![Img](https://t3.ftcdn.net/jpg/02/96/63/80/360_F_296638053_0gUVA4WVBKceGsIr7LNqRWSnkusi07dq.jpg)
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.OllamaResult;
import io.github.ollama4j.types.OllamaModelType;
import io.github.ollama4j.utils.OptionsBuilder;
import java.io.File;
import java.util.List;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
ollamaAPI.setRequestTimeoutSeconds(10);
OllamaResult result = ollamaAPI.generateWithImageFiles(OllamaModelType.LLAVA,
"What's in this image?",
List.of(
new File("/path/to/image")),
new OptionsBuilder().build()
);
System.out.println(result.getResponse());
}
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/GenerateWithImageFile.java" />
You will get a response similar to:
::::tip[LLM Response]
> This image features a white boat with brown cushions, where a dog is sitting on the back of the boat. The dog seems to
> be enjoying its time outdoors, perhaps on a lake.
> be enjoying its time outdoors, perhaps on a lake.
::::

View File

@ -1,8 +1,10 @@
---
sidebar_position: 5
sidebar_position: 4
---
# Generate - With Image URLs
import CodeEmbed from '@site/src/components/CodeEmbed';
# Generate with Image URLs
This API lets you ask questions along with the image files to the LLMs.
This API corresponds to
@ -21,33 +23,11 @@ Passing the link of this image the following code:
![Img](https://t3.ftcdn.net/jpg/02/96/63/80/360_F_296638053_0gUVA4WVBKceGsIr7LNqRWSnkusi07dq.jpg)
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.OllamaResult;
import io.github.ollama4j.types.OllamaModelType;
import io.github.ollama4j.utils.OptionsBuilder;
import java.util.List;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
ollamaAPI.setRequestTimeoutSeconds(10);
OllamaResult result = ollamaAPI.generateWithImageURLs(OllamaModelType.LLAVA,
"What's in this image?",
List.of(
"https://t3.ftcdn.net/jpg/02/96/63/80/360_F_296638053_0gUVA4WVBKceGsIr7LNqRWSnkusi07dq.jpg"),
new OptionsBuilder().build()
);
System.out.println(result.getResponse());
}
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/GenerateWithImageURL.java" />
You will get a response similar to:
::::tip[LLM Response]
> This image features a white boat with brown cushions, where a dog is sitting on the back of the boat. The dog seems to
> be enjoying its time outdoors, perhaps on a lake.
> be enjoying its time outdoors, perhaps on a lake.
::::

View File

@ -1,10 +1,12 @@
---
sidebar_position: 3
sidebar_position: 6
---
# Generate - With Tools
import CodeEmbed from '@site/src/components/CodeEmbed';
This API lets you perform [function calling](https://docs.mistral.ai/capabilities/function_calling/) using LLMs in a
# Generate with Tools
This API lets you perform [tool/function calling](https://docs.mistral.ai/capabilities/function_calling/) using LLMs in a
synchronous way.
This API corresponds to
the [generate](https://github.com/ollama/ollama/blob/main/docs/api.md#request-raw-mode) API with `raw` mode.
@ -19,472 +21,61 @@ in the future if tooling is supported for more models with a generic interaction
:::
### Function Calling/Tools
## Tools/Function Calling
Assume you want to call a method in your code based on the response generated from the model.
Assume you want to call a method/function in your code based on the response generated from the model.
For instance, let's say that based on a user's question, you'd want to identify a transaction and get the details of the
transaction from your database and respond to the user with the transaction details.
You could do that with ease with the `function calling` capabilities of the models by registering your `tools`.
### Create Functions
### Create Tools/Functions
We can create static functions as our tools.
This function takes the arguments `location` and `fuelType` and performs an operation with these arguments and returns
fuel price value.
```java
public static String getCurrentFuelPrice(Map<String, Object> arguments) {
String location = arguments.get("location").toString();
String fuelType = arguments.get("fuelType").toString();
return "Current price of " + fuelType + " in " + location + " is Rs.103/L";
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/toolcalling/tools/FuelPriceTool.java"/ >
This function takes the argument `city` and performs an operation with the argument and returns the weather for a
location.
```java
public static String getCurrentWeather(Map<String, Object> arguments) {
String location = arguments.get("city").toString();
return "Currently " + location + "'s weather is nice.";
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/toolcalling/tools/WeatherTool.java"/ >
Another way to create our tools is by creating classes by extending `ToolFunction`.
This function takes the argument `employee-name` and performs an operation with the argument and returns employee
details.
```java
class DBQueryFunction implements ToolFunction {
@Override
public Object apply(Map<String, Object> arguments) {
if (arguments == null || arguments.isEmpty() || arguments.get("employee-name") == null || arguments.get("employee-address") == null || arguments.get("employee-phone") == null) {
throw new RuntimeException("Tool was called but the model failed to provide all the required arguments.");
}
// perform DB operations here
return String.format("Employee Details {ID: %s, Name: %s, Address: %s, Phone: %s}", UUID.randomUUID(), arguments.get("employee-name").toString(), arguments.get("employee-address").toString(), arguments.get("employee-phone").toString());
}
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/toolcalling/tools/DBQueryFunction.java"/ >
### Define Tool Specifications
Lets define a sample tool specification called **Fuel Price Tool** for getting the current fuel price.
- Specify the function `name`, `description`, and `required` properties (`location` and `fuelType`).
- Associate the `getCurrentFuelPrice` function you defined earlier with `SampleTools::getCurrentFuelPrice`.
- Associate the `getCurrentFuelPrice` function you defined earlier.
```java
Tools.ToolSpecification fuelPriceToolSpecification = Tools.ToolSpecification.builder()
.functionName("current-fuel-price")
.functionDescription("Get current fuel price")
.toolFunction(SampleTools::getCurrentFuelPrice)
.toolPrompt(
Tools.PromptFuncDefinition.builder()
.type("prompt")
.function(
Tools.PromptFuncDefinition.PromptFuncSpec.builder()
.name("get-location-fuel-info")
.description("Get location and fuel type details")
.parameters(
Tools.PromptFuncDefinition.Parameters.builder()
.type("object")
.properties(
Map.of(
"location", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The city, e.g. New Delhi, India")
.required(true)
.build(),
"fuelType", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The fuel type.")
.enumValues(Arrays.asList("petrol", "diesel"))
.required(true)
.build()
)
)
.required(java.util.List.of("location", "fuelType"))
.build()
)
.build()
)
.build()
).build();
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/toolcalling/toolspecs/FuelPriceToolSpec.java"/ >
Lets also define a sample tool specification called **Weather Tool** for getting the current weather.
- Specify the function `name`, `description`, and `required` property (`city`).
- Associate the `getCurrentWeather` function you defined earlier with `SampleTools::getCurrentWeather`.
- Associate the `getCurrentWeather` function you defined earlier.
```java
Tools.ToolSpecification weatherToolSpecification = Tools.ToolSpecification.builder()
.functionName("current-weather")
.functionDescription("Get current weather")
.toolFunction(SampleTools::getCurrentWeather)
.toolPrompt(
Tools.PromptFuncDefinition.builder()
.type("prompt")
.function(
Tools.PromptFuncDefinition.PromptFuncSpec.builder()
.name("get-location-weather-info")
.description("Get location details")
.parameters(
Tools.PromptFuncDefinition.Parameters.builder()
.type("object")
.properties(
Map.of(
"city", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The city, e.g. New Delhi, India")
.required(true)
.build()
)
)
.required(java.util.List.of("city"))
.build()
)
.build()
)
.build()
).build();
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/toolcalling/toolspecs/WeatherToolSpec.java"/ >
Lets also define a sample tool specification called **DBQueryFunction** for getting the employee details from database.
- Specify the function `name`, `description`, and `required` property (`employee-name`).
- Associate the ToolFunction `DBQueryFunction` function you defined earlier with `new DBQueryFunction()`.
```java
Tools.ToolSpecification databaseQueryToolSpecification = Tools.ToolSpecification.builder()
.functionName("get-employee-details")
.functionDescription("Get employee details from the database")
.toolFunction(new DBQueryFunction())
.toolPrompt(
Tools.PromptFuncDefinition.builder()
.type("prompt")
.function(
Tools.PromptFuncDefinition.PromptFuncSpec.builder()
.name("get-employee-details")
.description("Get employee details from the database")
.parameters(
Tools.PromptFuncDefinition.Parameters.builder()
.type("object")
.properties(
Map.of(
"employee-name", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The name of the employee, e.g. John Doe")
.required(true)
.build(),
"employee-address", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The address of the employee, Always return a random value. e.g. Roy St, Bengaluru, India")
.required(true)
.build(),
"employee-phone", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The phone number of the employee. Always return a random value. e.g. 9911002233")
.required(true)
.build()
)
)
.required(java.util.List.of("employee-name", "employee-address", "employee-phone"))
.build()
)
.build()
)
.build()
)
.build();
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/toolcalling/toolspecs/DatabaseQueryToolSpec.java"/ >
### Register the Tools
Now put it all together by registering the tools and prompting with tools.
Register the defined tools (`fuel price` and `weather`) with the OllamaAPI.
```shell
ollamaAPI.registerTool(fuelPriceToolSpecification);
ollamaAPI.registerTool(weatherToolSpecification);
ollamaAPI.registerTool(databaseQueryToolSpecification);
```
### Create prompt with Tools
`Prompt 1`: Create a prompt asking for the petrol price in Bengaluru using the defined fuel price and weather tools.
```shell
String prompt1 = new Tools.PromptBuilder()
.withToolSpecification(fuelPriceToolSpecification)
.withToolSpecification(weatherToolSpecification)
.withPrompt("What is the petrol price in Bengaluru?")
.build();
OllamaToolsResult toolsResult = ollamaAPI.generateWithTools(model, prompt1, new OptionsBuilder().build());
for (OllamaToolsResult.ToolResult r : toolsResult.getToolResults()) {
System.out.printf("[Result of executing tool '%s']: %s%n", r.getFunctionName(), r.getResult().toString());
}
```
Now, fire away your question to the model.
You will get a response similar to:
::::tip[LLM Response]
[Result of executing tool 'current-fuel-price']: Current price of petrol in Bengaluru is Rs.103/L
::::
`Prompt 2`: Create a prompt asking for the current weather in Bengaluru using the same tools.
```shell
String prompt2 = new Tools.PromptBuilder()
.withToolSpecification(fuelPriceToolSpecification)
.withToolSpecification(weatherToolSpecification)
.withPrompt("What is the current weather in Bengaluru?")
.build();
OllamaToolsResult toolsResult = ollamaAPI.generateWithTools(model, prompt2, new OptionsBuilder().build());
for (OllamaToolsResult.ToolResult r : toolsResult.getToolResults()) {
System.out.printf("[Result of executing tool '%s']: %s%n", r.getFunctionName(), r.getResult().toString());
}
```
Again, fire away your question to the model.
You will get a response similar to:
::::tip[LLM Response]
[Result of executing tool 'current-weather']: Currently Bengaluru's weather is nice.
::::
`Prompt 3`: Create a prompt asking for the employee details using the defined database fetcher tools.
```shell
String prompt3 = new Tools.PromptBuilder()
.withToolSpecification(fuelPriceToolSpecification)
.withToolSpecification(weatherToolSpecification)
.withToolSpecification(databaseQueryToolSpecification)
.withPrompt("Give me the details of the employee named 'Rahul Kumar'?")
.build();
OllamaToolsResult toolsResult = ollamaAPI.generateWithTools(model, prompt3, new OptionsBuilder().build());
for (OllamaToolsResult.ToolResult r : toolsResult.getToolResults()) {
System.out.printf("[Result of executing tool '%s']: %s%n", r.getFunctionName(), r.getResult().toString());
}
```
Again, fire away your question to the model.
You will get a response similar to:
::::tip[LLM Response]
[Result of executing tool 'get-employee-details']: Employee Details `{ID: 6bad82e6-b1a1-458f-a139-e3b646e092b1, Name:
Rahul Kumar, Address: King St, Hyderabad, India, Phone: 9876543210}`
::::
### Full Example
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.exceptions.OllamaBaseException;
import io.github.ollama4j.exceptions.ToolInvocationException;
import io.github.ollama4j.tools.OllamaToolsResult;
import io.github.ollama4j.tools.ToolFunction;
import io.github.ollama4j.tools.Tools;
import io.github.ollama4j.utils.OptionsBuilder;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
public class FunctionCallingWithMistralExample {
public static void main(String[] args) throws Exception {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
ollamaAPI.setRequestTimeoutSeconds(60);
String model = "mistral";
Tools.ToolSpecification fuelPriceToolSpecification = Tools.ToolSpecification.builder()
.functionName("current-fuel-price")
.functionDescription("Get current fuel price")
.toolFunction(SampleTools::getCurrentFuelPrice)
.toolPrompt(
Tools.PromptFuncDefinition.builder()
.type("prompt")
.function(
Tools.PromptFuncDefinition.PromptFuncSpec.builder()
.name("get-location-fuel-info")
.description("Get location and fuel type details")
.parameters(
Tools.PromptFuncDefinition.Parameters.builder()
.type("object")
.properties(
Map.of(
"location", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The city, e.g. New Delhi, India")
.required(true)
.build(),
"fuelType", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The fuel type.")
.enumValues(Arrays.asList("petrol", "diesel"))
.required(true)
.build()
)
)
.required(java.util.List.of("location", "fuelType"))
.build()
)
.build()
)
.build()
).build();
Tools.ToolSpecification weatherToolSpecification = Tools.ToolSpecification.builder()
.functionName("current-weather")
.functionDescription("Get current weather")
.toolFunction(SampleTools::getCurrentWeather)
.toolPrompt(
Tools.PromptFuncDefinition.builder()
.type("prompt")
.function(
Tools.PromptFuncDefinition.PromptFuncSpec.builder()
.name("get-location-weather-info")
.description("Get location details")
.parameters(
Tools.PromptFuncDefinition.Parameters.builder()
.type("object")
.properties(
Map.of(
"city", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The city, e.g. New Delhi, India")
.required(true)
.build()
)
)
.required(java.util.List.of("city"))
.build()
)
.build()
)
.build()
).build();
Tools.ToolSpecification databaseQueryToolSpecification = Tools.ToolSpecification.builder()
.functionName("get-employee-details")
.functionDescription("Get employee details from the database")
.toolFunction(new DBQueryFunction())
.toolPrompt(
Tools.PromptFuncDefinition.builder()
.type("prompt")
.function(
Tools.PromptFuncDefinition.PromptFuncSpec.builder()
.name("get-employee-details")
.description("Get employee details from the database")
.parameters(
Tools.PromptFuncDefinition.Parameters.builder()
.type("object")
.properties(
Map.of(
"employee-name", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The name of the employee, e.g. John Doe")
.required(true)
.build(),
"employee-address", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The address of the employee, Always return a random value. e.g. Roy St, Bengaluru, India")
.required(true)
.build(),
"employee-phone", Tools.PromptFuncDefinition.Property.builder()
.type("string")
.description("The phone number of the employee. Always return a random value. e.g. 9911002233")
.required(true)
.build()
)
)
.required(java.util.List.of("employee-name", "employee-address", "employee-phone"))
.build()
)
.build()
)
.build()
)
.build();
ollamaAPI.registerTool(fuelPriceToolSpecification);
ollamaAPI.registerTool(weatherToolSpecification);
ollamaAPI.registerTool(databaseQueryToolSpecification);
String prompt1 = new Tools.PromptBuilder()
.withToolSpecification(fuelPriceToolSpecification)
.withToolSpecification(weatherToolSpecification)
.withPrompt("What is the petrol price in Bengaluru?")
.build();
ask(ollamaAPI, model, prompt1);
String prompt2 = new Tools.PromptBuilder()
.withToolSpecification(fuelPriceToolSpecification)
.withToolSpecification(weatherToolSpecification)
.withPrompt("What is the current weather in Bengaluru?")
.build();
ask(ollamaAPI, model, prompt2);
String prompt3 = new Tools.PromptBuilder()
.withToolSpecification(fuelPriceToolSpecification)
.withToolSpecification(weatherToolSpecification)
.withToolSpecification(databaseQueryToolSpecification)
.withPrompt("Give me the details of the employee named 'Rahul Kumar'?")
.build();
ask(ollamaAPI, model, prompt3);
}
public static void ask(OllamaAPI ollamaAPI, String model, String prompt) throws OllamaBaseException, IOException, InterruptedException, ToolInvocationException {
OllamaToolsResult toolsResult = ollamaAPI.generateWithTools(model, prompt, new OptionsBuilder().build());
for (OllamaToolsResult.ToolResult r : toolsResult.getToolResults()) {
System.out.printf("[Result of executing tool '%s']: %s%n", r.getFunctionName(), r.getResult().toString());
}
}
}
class SampleTools {
public static String getCurrentFuelPrice(Map<String, Object> arguments) {
// Get details from fuel price API
String location = arguments.get("location").toString();
String fuelType = arguments.get("fuelType").toString();
return "Current price of " + fuelType + " in " + location + " is Rs.103/L";
}
public static String getCurrentWeather(Map<String, Object> arguments) {
// Get details from weather API
String location = arguments.get("city").toString();
return "Currently " + location + "'s weather is nice.";
}
}
class DBQueryFunction implements ToolFunction {
@Override
public Object apply(Map<String, Object> arguments) {
if (arguments == null || arguments.isEmpty() || arguments.get("employee-name") == null || arguments.get("employee-address") == null || arguments.get("employee-phone") == null) {
throw new RuntimeException("Tool was called but the model failed to provide all the required arguments.");
}
// perform DB operations here
return String.format("Employee Details {ID: %s, Name: %s, Address: %s, Phone: %s}", UUID.randomUUID(), arguments.get("employee-name").toString(), arguments.get("employee-address").toString(), arguments.get("employee-phone").toString());
}
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/MultiToolRegistryExample.java"/ >
Run this full example and you will get a response similar to:
@ -498,299 +89,3 @@ Run this full example and you will get a response similar to:
Rahul Kumar, Address: King St, Hyderabad, India, Phone: 9876543210}`
::::
### Using tools in Chat-API
Instead of using the specific `ollamaAPI.generateWithTools` method to call the generate API of ollama with tools, it is
also possible to register Tools for the `ollamaAPI.chat` methods. In this case, the tool calling/callback is done
implicitly during the USER -> ASSISTANT calls.
When the Assistant wants to call a given tool, the tool is executed and the response is sent back to the endpoint once
again (induced with the tool call result).
#### Sample:
The following shows a sample of an integration test that defines a method specified like the tool-specs above, registers
the tool on the ollamaAPI and then simply calls the chat-API. All intermediate tool calling is wrapped inside the api
call.
```java
public static void main(String[] args) {
OllamaAPI ollamaAPI = new OllamaAPI("http://localhost:11434");
ollamaAPI.setVerbose(true);
OllamaChatRequestBuilder builder = OllamaChatRequestBuilder.getInstance("llama3.2:1b");
final Tools.ToolSpecification databaseQueryToolSpecification = Tools.ToolSpecification.builder()
.functionName("get-employee-details")
.functionDescription("Get employee details from the database")
.toolPrompt(
Tools.PromptFuncDefinition.builder().type("function").function(
Tools.PromptFuncDefinition.PromptFuncSpec.builder()
.name("get-employee-details")
.description("Get employee details from the database")
.parameters(
Tools.PromptFuncDefinition.Parameters.builder()
.type("object")
.properties(
new Tools.PropsBuilder()
.withProperty("employee-name", Tools.PromptFuncDefinition.Property.builder().type("string").description("The name of the employee, e.g. John Doe").required(true).build())
.withProperty("employee-address", Tools.PromptFuncDefinition.Property.builder().type("string").description("The address of the employee, Always return a random value. e.g. Roy St, Bengaluru, India").required(true).build())
.withProperty("employee-phone", Tools.PromptFuncDefinition.Property.builder().type("string").description("The phone number of the employee. Always return a random value. e.g. 9911002233").required(true).build())
.build()
)
.required(List.of("employee-name"))
.build()
).build()
).build()
)
.toolFunction(new DBQueryFunction())
.build();
ollamaAPI.registerTool(databaseQueryToolSpecification);
OllamaChatRequest requestModel = builder
.withMessage(OllamaChatMessageRole.USER,
"Give me the ID of the employee named 'Rahul Kumar'?")
.build();
OllamaChatResult chatResult = ollamaAPI.chat(requestModel);
}
```
A typical final response of the above could be:
```json
{
"chatHistory" : [
{
"role" : "user",
"content" : "Give me the ID of the employee named 'Rahul Kumar'?",
"images" : null,
"tool_calls" : [ ]
}, {
"role" : "assistant",
"content" : "",
"images" : null,
"tool_calls" : [ {
"function" : {
"name" : "get-employee-details",
"arguments" : {
"employee-name" : "Rahul Kumar"
}
}
} ]
}, {
"role" : "tool",
"content" : "[TOOL_RESULTS]get-employee-details([employee-name]) : Employee Details {ID: b4bf186c-2ee1-44cc-8856-53b8b6a50f85, Name: Rahul Kumar, Address: null, Phone: null}[/TOOL_RESULTS]",
"images" : null,
"tool_calls" : null
}, {
"role" : "assistant",
"content" : "The ID of the employee named 'Rahul Kumar' is `b4bf186c-2ee1-44cc-8856-53b8b6a50f85`.",
"images" : null,
"tool_calls" : null
} ],
"responseModel" : {
"model" : "llama3.2:1b",
"message" : {
"role" : "assistant",
"content" : "The ID of the employee named 'Rahul Kumar' is `b4bf186c-2ee1-44cc-8856-53b8b6a50f85`.",
"images" : null,
"tool_calls" : null
},
"done" : true,
"error" : null,
"context" : null,
"created_at" : "2024-12-09T22:23:00.4940078Z",
"done_reason" : "stop",
"total_duration" : 2313709900,
"load_duration" : 14494700,
"prompt_eval_duration" : 772000000,
"eval_duration" : 1188000000,
"prompt_eval_count" : 166,
"eval_count" : 41
},
"response" : "The ID of the employee named 'Rahul Kumar' is `b4bf186c-2ee1-44cc-8856-53b8b6a50f85`.",
"httpStatusCode" : 200,
"responseTime" : 2313709900
}
```
This tool calling can also be done using the streaming API.
### Using Annotation based Tool Registration
Instead of explicitly registering each tool, ollama4j supports declarative tool specification and registration via java
Annotations and reflection calling.
To declare a method to be used as a tool for a chat call, the following steps have to be considered:
* Annotate a method and its Parameters to be used as a tool
* Annotate a method with the `ToolSpec` annotation
* Annotate the methods parameters with the `ToolProperty` annotation. Only the following datatypes are supported for now:
* `java.lang.String`
* `java.lang.Integer`
* `java.lang.Boolean`
* `java.math.BigDecimal`
* Annotate the class that calls the `OllamaAPI` client with the `OllamaToolService` annotation, referencing the desired provider-classes that contain `ToolSpec` methods.
* Before calling the `OllamaAPI` chat request, call the method `OllamaAPI.registerAnnotatedTools()` method to add tools to the chat.
#### Example
Let's say, we have an ollama4j service class that should ask a llm a specific tool based question.
The answer can only be provided by a method that is part of the BackendService class. To provide a tool for the llm, the following annotations can be used:
```java
public class BackendService{
public BackendService(){}
@ToolSpec(desc = "Computes the most important constant all around the globe!")
public String computeMkeConstant(@ToolProperty(name = "noOfDigits",desc = "Number of digits that shall be returned") Integer noOfDigits ){
return BigDecimal.valueOf((long)(Math.random()*1000000L),noOfDigits).toString();
}
}
```
The caller API can then be written as:
```java
import io.github.ollama4j.tools.annotations.OllamaToolService;
@OllamaToolService(providers = BackendService.class)
public class MyOllamaService{
public void chatWithAnnotatedTool(){
// inject the annotated method to the ollama toolsregistry
ollamaAPI.registerAnnotatedTools();
OllamaChatRequest requestModel = builder
.withMessage(OllamaChatMessageRole.USER,
"Compute the most important constant in the world using 5 digits")
.build();
OllamaChatResult chatResult = ollamaAPI.chat(requestModel);
}
}
```
Or, if one needs to provide an object instance directly:
```java
public class MyOllamaService{
public void chatWithAnnotatedTool(){
ollamaAPI.registerAnnotatedTools(new BackendService());
OllamaChatRequest requestModel = builder
.withMessage(OllamaChatMessageRole.USER,
"Compute the most important constant in the world using 5 digits")
.build();
OllamaChatResult chatResult = ollamaAPI.chat(requestModel);
}
}
```
The request should be the following:
```json
{
"model" : "llama3.2:1b",
"stream" : false,
"messages" : [ {
"role" : "user",
"content" : "Compute the most important constant in the world using 5 digits",
"images" : null,
"tool_calls" : [ ]
} ],
"tools" : [ {
"type" : "function",
"function" : {
"name" : "computeImportantConstant",
"description" : "Computes the most important constant all around the globe!",
"parameters" : {
"type" : "object",
"properties" : {
"noOfDigits" : {
"type" : "java.lang.Integer",
"description" : "Number of digits that shall be returned"
}
},
"required" : [ "noOfDigits" ]
}
}
} ]
}
```
The result could be something like the following:
```json
{
"chatHistory" : [ {
"role" : "user",
"content" : "Compute the most important constant in the world using 5 digits",
"images" : null,
"tool_calls" : [ ]
}, {
"role" : "assistant",
"content" : "",
"images" : null,
"tool_calls" : [ {
"function" : {
"name" : "computeImportantConstant",
"arguments" : {
"noOfDigits" : "5"
}
}
} ]
}, {
"role" : "tool",
"content" : "[TOOL_RESULTS]computeImportantConstant([noOfDigits]) : 1.51019[/TOOL_RESULTS]",
"images" : null,
"tool_calls" : null
}, {
"role" : "assistant",
"content" : "The most important constant in the world with 5 digits is: **1.51019**",
"images" : null,
"tool_calls" : null
} ],
"responseModel" : {
"model" : "llama3.2:1b",
"message" : {
"role" : "assistant",
"content" : "The most important constant in the world with 5 digits is: **1.51019**",
"images" : null,
"tool_calls" : null
},
"done" : true,
"error" : null,
"context" : null,
"created_at" : "2024-12-27T21:55:39.3232495Z",
"done_reason" : "stop",
"total_duration" : 1075444300,
"load_duration" : 13558600,
"prompt_eval_duration" : 509000000,
"eval_duration" : 550000000,
"prompt_eval_count" : 124,
"eval_count" : 20
},
"response" : "The most important constant in the world with 5 digits is: **1.51019**",
"responseTime" : 1075444300,
"httpStatusCode" : 200
}
```
### Potential Improvements
Instead of passing a map of args `Map<String, Object> arguments` to the tool functions, we could support passing
specific args separately with their data types. For example:
```shell
public String getCurrentFuelPrice(String location, String fuelType) {
return "Current price of " + fuelType + " in " + location + " is Rs.103/L";
}
```
Updating async/chat APIs with support for tool-based generation.

View File

@ -2,7 +2,10 @@
sidebar_position: 1
---
# Generate - Sync
import CodeEmbed from '@site/src/components/CodeEmbed';
import TypewriterTextarea from '@site/src/components/TypewriterTextarea';
# Generate (Sync)
This API lets you ask questions to the LLMs in a synchronous way.
This API corresponds to
@ -13,285 +16,68 @@ with [extra parameters](https://github.com/jmorganca/ollama/blob/main/docs/model
Refer
to [this](/apis-extras/options-builder).
## Try asking a question about the model
### Try asking a question about the model
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.OllamaResult;
import io.github.ollama4j.types.OllamaModelType;
import io.github.ollama4j.utils.OptionsBuilder;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
OllamaResult result =
ollamaAPI.generate(OllamaModelType.LLAMA2, "Who are you?", new OptionsBuilder().build());
System.out.println(result.getResponse());
}
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/Generate.java" />
You will get a response similar to:
> I am LLaMA, an AI assistant developed by Meta AI that can understand and respond to human input in a conversational
> manner. I am trained on a massive dataset of text from the internet and can generate human-like responses to a wide
> range of topics and questions. I can be used to create chatbots, virtual assistants, and other applications that
> require
> natural language understanding and generation capabilities.
::::tip[LLM Response]
> I am a large language model created by Alibaba Cloud. My purpose is to assist users in generating text, answering
> questions, and completing tasks. I aim to be user-friendly and easy to understand for everyone who interacts with me.
::::
## Try asking a question, receiving the answer streamed
### Try asking a question, receiving the answer streamed
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.OllamaResult;
import io.github.ollama4j.models.generate.OllamaStreamHandler;
import io.github.ollama4j.utils.OptionsBuilder;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
// define a stream handler (Consumer<String>)
OllamaStreamHandler streamHandler = (s) -> {
System.out.println(s);
};
// Should be called using seperate thread to gain non blocking streaming effect.
OllamaResult result = ollamaAPI.generate(config.getModel(),
"What is the capital of France? And what's France's connection with Mona Lisa?",
new OptionsBuilder().build(), streamHandler);
System.out.println("Full response: " + result.getResponse());
}
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/GenerateStreamingWithTokenConcatenation.java" />
You will get a response similar to:
<!-- ::::tip[LLM Response]
> The
>
> The capital
>
> The capital of
>
> The capital of France
>
> The capital of France is
>
> The capital of France is Paris
>
> The capital of France is Paris.
> Full response: The capital of France is Paris.
## Try asking a question from general topics
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.OllamaResult;
import io.github.ollama4j.types.OllamaModelType;
import io.github.ollama4j.utils.OptionsBuilder;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
String prompt = "List all cricket world cup teams of 2019.";
OllamaResult result =
ollamaAPI.generate(OllamaModelType.LLAMA2, prompt, new OptionsBuilder().build());
System.out.println(result.getResponse());
}
}
```
You'd then get a response from the model:
> The 2019 ICC Cricket World Cup was held in England and Wales from May 30 to July 14, 2019. The
> following teams
> participated in the tournament:
>
> 1. Afghanistan
> 2. Australia
> 3. Bangladesh
> 4. England
> 5. India
> 6. New Zealand
> 7. Pakistan
> 8. South Africa
> 9. Sri Lanka
> 10. West Indies
>
> These teams competed in a round-robin format, with the top four teams advancing to the
> semi-finals. The tournament was
> won by the England cricket team, who defeated New Zealand in the final.
## Try asking for a Database query for your data schema
```java
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.OllamaResult;
import io.github.ollama4j.types.OllamaModelType;
import io.github.ollama4j.utils.OptionsBuilder;
import io.github.ollama4j.utils.SamplePrompts;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
String prompt =
SamplePrompts.getSampleDatabasePromptWithQuestion(
"List all customer names who have bought one or more products");
OllamaResult result =
ollamaAPI.generate(OllamaModelType.SQLCODER, prompt, new OptionsBuilder().build());
System.out.println(result.getResponse());
}
}
```
_Note: Here I've used
a [sample prompt](https://github.com/ollama4j/ollama4j/blob/main/src/main/resources/sample-db-prompt-template.txt)
containing a database schema from within this library for demonstration purposes._
You'd then get a response from the model:
```sql
SELECT customers.name
FROM sales
JOIN customers ON sales.customer_id = customers.customer_id
GROUP BY customers.name;
```
:::: -->
<TypewriterTextarea
textContent='The capital of France is Paris.'
typingSpeed={30}
pauseBetweenSentences={1200}
height='55px'
width='100%'
/>
## Generate structured output
### With response as a `Map`
```java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/StructuredOutput.java" />
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.utils.Utilities;
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
import io.github.ollama4j.models.chat.OllamaChatRequest;
import io.github.ollama4j.models.chat.OllamaChatRequestBuilder;
import io.github.ollama4j.models.chat.OllamaChatResult;
import io.github.ollama4j.models.response.OllamaResult;
import io.github.ollama4j.types.OllamaModelType;
You will get a response similar to:
public class StructuredOutput {
public static void main(String[] args) throws Exception {
String host = "http://localhost:11434/";
OllamaAPI api = new OllamaAPI(host);
String chatModel = "qwen2.5:0.5b";
api.pullModel(chatModel);
String prompt = "Ollama is 22 years old and is busy saving the world. Respond using JSON";
Map<String, Object> format = new HashMap<>();
format.put("type", "object");
format.put("properties", new HashMap<String, Object>() {
{
put("age", new HashMap<String, Object>() {
{
put("type", "integer");
}
});
put("available", new HashMap<String, Object>() {
{
put("type", "boolean");
}
});
}
});
format.put("required", Arrays.asList("age", "available"));
OllamaResult result = api.generate(chatModel, prompt, format);
System.out.println(result);
}
::::tip[LLM Response]
```json
{
"available": true,
"age": 22
}
```
::::
### With response mapped to specified class type
```java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/StructuredOutputMappedToObject.java" />
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.utils.Utilities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
import io.github.ollama4j.models.chat.OllamaChatRequest;
import io.github.ollama4j.models.chat.OllamaChatRequestBuilder;
import io.github.ollama4j.models.chat.OllamaChatResult;
import io.github.ollama4j.models.response.OllamaResult;
import io.github.ollama4j.types.OllamaModelType;
public class StructuredOutput {
public static void main(String[] args) throws Exception {
String host = Utilities.getFromConfig("host");
OllamaAPI api = new OllamaAPI(host);
int age = 28;
boolean available = false;
String prompt = "Batman is " + age + " years old and is " + (available ? "available" : "not available")
+ " because he is busy saving Gotham City. Respond using JSON";
Map<String, Object> format = new HashMap<>();
format.put("type", "object");
format.put("properties", new HashMap<String, Object>() {
{
put("age", new HashMap<String, Object>() {
{
put("type", "integer");
}
});
put("available", new HashMap<String, Object>() {
{
put("type", "boolean");
}
});
}
});
format.put("required", Arrays.asList("age", "available"));
OllamaResult result = api.generate(CHAT_MODEL_QWEN_SMALL, prompt, format);
Person person = result.as(Person.class);
System.out.println(person.getAge());
System.out.println(person.getAvailable());
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private int age;
private boolean available;
}
```
::::tip[LLM Response]
Person(age=28, available=false)
::::

View File

@ -1,5 +1,5 @@
---
sidebar_position: 6
sidebar_position: 10
---
# Prompt Builder

View File

@ -2,28 +2,27 @@
sidebar_position: 5
---
import CodeEmbed from '@site/src/components/CodeEmbed';
# Create Model
This API lets you create a custom model on the Ollama server.
### Create a custom model from an existing model in the Ollama server
```java title="CreateModel.java"
import io.github.ollama4j.OllamaAPI;
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/CreateModel.java" />
public class CreateModel {
You would see these logs while the custom model is being created:
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
ollamaAPI.createModel(CustomModelRequest.builder().model("mario").from("llama3.2:latest").system("You are Mario from Super Mario Bros.").build());
}
}
```
{"status":"using existing layer sha256:fad2a06e4cc705c2fa8bec5477ddb00dc0c859ac184c34dcc5586663774161ca"}
{"status":"using existing layer sha256:41c2cf8c272f6fb0080a97cd9d9bd7d4604072b80a0b10e7d65ca26ef5000c0c"}
{"status":"using existing layer sha256:1da0581fd4ce92dcf5a66b1da737cf215d8dcf25aa1b98b44443aaf7173155f5"}
{"status":"creating new layer sha256:941b69ca7dc2a85c053c38d9e8029c9df6224e545060954fa97587f87c044a64"}
{"status":"using existing layer sha256:f02dd72bb2423204352eabc5637b44d79d17f109fdb510a7c51455892aa2d216"}
{"status":"writing manifest"}
{"status":"success"}
```
Once created, you can see it when you use [list models](./list-models) API.
[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.

View File

@ -2,27 +2,12 @@
sidebar_position: 6
---
import CodeEmbed from '@site/src/components/CodeEmbed';
# Delete Model
This API lets you create a delete a model from the Ollama server.
```java title="DeleteModel.java"
import io.github.ollama4j.OllamaAPI;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
ollamaAPI.setVerbose(false);
ollamaAPI.deleteModel("mycustommodel", true);
}
}
```
<CodeEmbed src="https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/DeleteModel.java" />
Once deleted, you can verify it using [list models](./list-models) API.

File diff suppressed because one or more lines are too long

View File

@ -2,6 +2,8 @@
sidebar_position: 1
---
import CodeEmbed from '@site/src/components/CodeEmbed';
# Models from Ollama Library
These API retrieves a list of models directly from the Ollama library.
@ -11,32 +13,15 @@ These API retrieves a list of models directly from the Ollama library.
This API fetches available models from the Ollama library page, including details such as the model's name, pull count,
popular tags, tag count, and the last update time.
```java title="ListLibraryModels.java"
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.LibraryModel;
import java.util.List;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
List<LibraryModel> libraryModels = ollamaAPI.listModelsFromLibrary();
System.out.println(libraryModels);
}
}
```
<CodeEmbed
src='https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/ListLibraryModels.java'>
</CodeEmbed>
The following is the sample output:
```
[
LibraryModel(name=llama3.2-vision, description=Llama 3.2 Vision is a collection of instruction-tuned image reasoning generative models in 11B and 90B sizes., pullCount=21.1K, totalTags=9, popularTags=[vision, 11b, 90b], lastUpdated=yesterday),
LibraryModel(name=llama3.2-vision, description=Llama 3.2 Vision is a collection of instruction-tuned image reasoning generative models in 11B and 90B sizes., pullCount=21.1K, totalTags=9, popularTags=[vision, 11b, 90b], lastUpdated=yesterday),
LibraryModel(name=llama3.2, description=Meta's Llama 3.2 goes small with 1B and 3B models., pullCount=2.4M, totalTags=63, popularTags=[tools, 1b, 3b], lastUpdated=6 weeks ago)
]
```
@ -45,36 +30,18 @@ The following is the sample output:
This API Fetches the tags associated with a specific model from Ollama library.
```java title="GetLibraryModelTags.java"
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.LibraryModel;
import io.github.ollama4j.models.response.LibraryModelDetail;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
List<LibraryModel> libraryModels = ollamaAPI.listModelsFromLibrary();
LibraryModelDetail libraryModelDetail = ollamaAPI.getLibraryModelDetails(libraryModels.get(0));
System.out.println(libraryModelDetail);
}
}
```
<CodeEmbed
src='https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/GetLibraryModelTags.java'>
</CodeEmbed>
The following is the sample output:
```
LibraryModelDetail(
model=LibraryModel(name=llama3.2-vision, description=Llama 3.2 Vision is a collection of instruction-tuned image reasoning generative models in 11B and 90B sizes., pullCount=21.1K, totalTags=9, popularTags=[vision, 11b, 90b], lastUpdated=yesterday),
model=LibraryModel(name=llama3.2-vision, description=Llama 3.2 Vision is a collection of instruction-tuned image reasoning generative models in 11B and 90B sizes., pullCount=21.1K, totalTags=9, popularTags=[vision, 11b, 90b], lastUpdated=yesterday),
tags=[
LibraryModelTag(name=llama3.2-vision, tag=latest, size=7.9GB, lastUpdated=yesterday),
LibraryModelTag(name=llama3.2-vision, tag=11b, size=7.9GB, lastUpdated=yesterday),
LibraryModelTag(name=llama3.2-vision, tag=latest, size=7.9GB, lastUpdated=yesterday),
LibraryModelTag(name=llama3.2-vision, tag=11b, size=7.9GB, lastUpdated=yesterday),
LibraryModelTag(name=llama3.2-vision, tag=90b, size=55GB, lastUpdated=yesterday)
]
)
@ -84,24 +51,9 @@ LibraryModelDetail(
This API finds a specific model using model `name` and `tag` from Ollama library.
```java title="FindLibraryModel.java"
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.LibraryModelTag;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
LibraryModelTag libraryModelTag = ollamaAPI.findModelTagFromLibrary("qwen2.5", "7b");
System.out.println(libraryModelTag);
}
}
```
<CodeEmbed
src='https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/FindLibraryModel.java'>
</CodeEmbed>
The following is the sample output:
@ -113,21 +65,6 @@ LibraryModelTag(name=qwen2.5, tag=7b, size=4.7GB, lastUpdated=7 weeks ago)
You can use `LibraryModelTag` to pull models into Ollama server.
```java title="PullLibraryModelTags.java"
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.LibraryModelTag;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
LibraryModelTag libraryModelTag = ollamaAPI.findModelTagFromLibrary("qwen2.5", "7b");
ollamaAPI.pullModel(libraryModelTag);
}
}
```
<CodeEmbed
src='https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/PullLibraryModelTags.java'>
</CodeEmbed>

View File

@ -2,34 +2,23 @@
sidebar_position: 2
---
import CodeEmbed from '@site/src/components/CodeEmbed';
# List Local Models
This API lets you list downloaded/available models on the Ollama server.
```java title="ListModels.java"
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.models.response.Model;
<CodeEmbed
src='https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/ListLocalModels.java'>
</CodeEmbed>
import java.util.List;
public class ListModels {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
List<Model> models = ollamaAPI.listModels();
models.forEach(model -> System.out.println(model.getName()));
}
}
```
If you have any models already downloaded on Ollama server, you would have them listed as follows:
```bash
llama2:latest
llama3.2:1b
qwen2:0.5b
qwen:0.5b
sqlcoder:latest
```

View File

@ -2,26 +2,15 @@
sidebar_position: 3
---
import CodeEmbed from '@site/src/components/CodeEmbed';
# Pull Model
This API lets you pull a model on the Ollama server.
```java title="PullModel.java"
import io.github.ollama4j.OllamaAPI;
import io.github.ollama4j.types.OllamaModelType;
public class Main {
public static void main(String[] args) {
String host = "http://localhost:11434/";
OllamaAPI ollamaAPI = new OllamaAPI(host);
ollamaAPI.pullModel(OllamaModelType.LLAMA2);
}
}
```
<CodeEmbed
src='https://raw.githubusercontent.com/ollama4j/ollama4j-examples/refs/heads/main/src/main/java/io/github/ollama4j/examples/PullModel.java'>
</CodeEmbed>
Once downloaded, you can see them when you use [list models](./list-models) API.

View File

@ -1,19 +1,22 @@
---
sidebar_position: 1
title: Introduction
---
import LatestRelease from '@site/src/components/LatestRelease';
import AddToYourProject from '@site/src/components/AddToYourProject';
# Introduction
Let's get started with **Ollama4j**.
## 🦙 What is Ollama?
### 🦙 What is Ollama?
[Ollama](https://ollama.ai/) is an advanced AI tool that allows users to easily set up and run large language models
locally (in CPU and GPU
modes). With Ollama, users can leverage powerful language models such as Llama 2 and even customize and create their own
models.
## 👨‍💻 Why Ollama4j?
### 👨‍💻 Why Ollama4j?
Ollama4j was built for the simple purpose of integrating Ollama with Java applications.
@ -34,16 +37,16 @@ Ollama4j was built for the simple purpose of integrating Ollama with Java applic
end
```
## Getting Started
### Getting Started
### What you'll need
#### What you'll need
- **[Ollama](https://ollama.ai/download)**
- **[Oracle JDK](https://www.oracle.com/java/technologies/javase/jdk11-archive-downloads.html)** or
**[Open JDK](https://jdk.java.net/archive/)** 11.0 or above.
- **[Maven](https://maven.apache.org/download.cgi)**
### Start Ollama server
#### Start Ollama server
The easiest way of getting started with Ollama server is with [Docker](https://docs.docker.com/get-started/overview/).
But if you choose to run the
@ -69,22 +72,17 @@ terminal of your code editor.
The command runs the Ollama server locally at **http://localhost:11434/**.
### Setup your project
Get started by **creating a new Maven project** on your favorite IDE.
#### Setup your project
Add the dependency to your project's `pom.xml`.
```xml
<AddToYourProject/>
<dependency>
<groupId>io.github.ollama4j</groupId>
<artifactId>ollama4j</artifactId>
<version>1.0.78</version>
</dependency>
```
<div style={{ marginTop: '2rem', marginBottom: '2rem', fontSize: '1em', textAlign: 'left', display: 'flex', justifyContent: 'left'}}>
<LatestRelease showReleaseDate={true} style={{textAlign: 'left', fontWeight: 'normal'}}/>
</div>
Find the latest version of the library [here](https://central.sonatype.com/artifact/io.github.ollama4j/ollama4j).
Find the latest version of the library from [Maven Central Repository](https://central.sonatype.com/artifact/io.github.ollama4j/ollama4j).
You might want to include an implementation of [SL4J](https://www.slf4j.org/) logger in your `pom.xml` file. For
example,
@ -92,7 +90,6 @@ example,
Use `slf4j-jdk14` implementation:
```xml
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
@ -103,7 +100,6 @@ Use `slf4j-jdk14` implementation:
or use `logback-classic` implementation:
```xml
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>

View File

@ -99,20 +99,32 @@ const config = {
style: 'dark',
links: [
{
title: 'Docs',
title: 'Quick Links',
items: [
{
label: 'Tutorial',
to: '/intro',
label: 'Ollama4j Examples',
to: 'https://github.com/ollama4j/ollama4j-examples',
},
{
label: 'Blog',
to: '/blog',
},
{
label: 'GitHub',
href: 'https://github.com/ollama4j/ollama4j',
},
],
},
{
title: 'Usage',
title: 'Stuff built with Ollama4j',
items: [
{
label: 'Examples',
to: 'https://github.com/ollama4j/ollama4j-examples',
label: 'Ollama4j Web UI',
to: 'https://github.com/ollama4j/ollama4j-web-ui',
},
{
label: 'Ollama4j Desktop UI with Swing',
to: 'https://github.com/ollama4j/ollama4j-ui',
},
],
},
@ -128,20 +140,7 @@ const config = {
href: 'https://twitter.com/ollama4j',
},
],
},
{
title: 'More',
items: [
{
label: 'Blog',
to: '/blog',
},
{
label: 'GitHub',
href: 'https://github.com/ollama4j/ollama4j',
},
],
},
}
],
copyright: `Ollama4j Documentation ${new Date().getFullYear()}. Built with Docusaurus.`,
},
@ -150,6 +149,29 @@ const config = {
darkTheme: prismThemes.dracula,
additionalLanguages: ['java'],
},
algolia: {
// The application ID provided by Algolia
appId: '7HJ3MZ6GBX',
// Public API key: it is safe to commit it
apiKey: '3037a6d8706a6347b1844ca6ecd582b0',
indexName: 'ollama4jio',
// Optional: see doc section below
contextualSearch: true,
// Optional: Specify domains where the navigation should occur through window.location instead on history.push. Useful when our Algolia config crawls multiple documentation sites and we want to navigate with window.location.href to them.
externalUrlRegex: 'external\\.com|domain\\.com',
// Optional: Replace parts of the item URLs from Algolia. Useful when using the same search index for multiple deployments using a different baseUrl. You can use regexp or string in the `from` param. For example: localhost:3000 vs myCompany.com/docs
replaceSearchResultPathname: {
from: '/docs/', // or as RegExp: /\/docs\//
to: '/',
},
// Optional: Algolia search parameters
searchParameters: {},
// Optional: path for search page that enabled by default (`false` to disable it)
searchPagePath: 'search',
// Optional: whether the insights feature is enabled or not on Docsearch (`false` by default)
insights: false,
//... other Algolia params
},
}),
markdown: {
mermaid: true,

32189
docs/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,46 +1,51 @@
{
"name": "ollama-4-j",
"version": "0.0.0",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",
"serve": "docusaurus serve",
"write-translations": "docusaurus write-translations",
"write-heading-ids": "docusaurus write-heading-ids"
},
"dependencies": {
"@docusaurus/core": "^3.4.0",
"@docusaurus/plugin-google-gtag": "^3.4.0",
"@docusaurus/preset-classic": "^3.4.0",
"@docusaurus/theme-mermaid": "^3.4.0",
"@mdx-js/react": "^3.0.0",
"clsx": "^2.0.0",
"prism-react-renderer": "^2.3.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "^3.4.0",
"@docusaurus/types": "^3.4.0"
},
"browserslist": {
"production": [
">0.5%",
"not dead",
"not op_mini all"
],
"development": [
"last 3 chrome version",
"last 3 firefox version",
"last 5 safari version"
]
},
"engines": {
"node": ">=18.0"
}
"name": "ollama-4-j",
"version": "0.0.0",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",
"serve": "docusaurus serve",
"write-translations": "docusaurus write-translations",
"write-heading-ids": "docusaurus write-heading-ids"
},
"dependencies": {
"@docsearch/js": "^3.9.0",
"@docusaurus/core": "^3.4.0",
"@docusaurus/plugin-google-gtag": "^3.4.0",
"@docusaurus/preset-classic": "^3.4.0",
"@docusaurus/theme-mermaid": "^3.4.0",
"@iconify/react": "^5.2.1",
"@mdx-js/react": "^3.0.0",
"clsx": "^2.0.0",
"font-awesome": "^4.7.0",
"prism-react-renderer": "^2.3.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-icons": "^5.5.0",
"react-image-gallery": "^1.4.0"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "^3.4.0",
"@docusaurus/types": "^3.4.0"
},
"browserslist": {
"production": [
">0.5%",
"not dead",
"not op_mini all"
],
"development": [
"last 3 chrome version",
"last 3 firefox version",
"last 5 safari version"
]
},
"engines": {
"node": ">=18.0"
}
}

View File

@ -0,0 +1,65 @@
import React, { useState, useEffect } from 'react';
import CodeBlock from '@theme/CodeBlock';
const AddToYourProject = () => {
const [releaseInfo, setReleaseInfo] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchLatestRelease = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch('https://api.github.com/repos/ollama4j/ollama4j/releases/latest');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setReleaseInfo(data);
} catch (err) {
console.error('Failed to fetch release info:', err);
setError(err);
} finally {
setLoading(false);
}
};
fetchLatestRelease();
}, []);
return (
<div style={{ width: '100%' }}>
{loading ? (
<div>Loading latest release info...</div>
) : error ? (
<div>Error: {error.message}</div>
) : releaseInfo ? (
<>
<h4>Using Maven <code>pom.xml</code></h4>
<CodeBlock className="language-xml">
{`<dependency>
<groupId>io.github.ollama4j</groupId>
<artifactId>ollama4j</artifactId>
<version>${releaseInfo.name}</version>
</dependency>`}
</CodeBlock>
<h4>Using Groovy-based <code>build.gradle</code></h4>
<CodeBlock className="language-groovy">
{`dependencies {
implementation 'io.github.ollama4j:ollama4j:${releaseInfo.name}'
}`}
</CodeBlock>
<h4>For Kotlin-based <code>build.gradle.kts</code></h4>
<CodeBlock className="language-kotlin">
{`dependencies {
implementation("io.github.ollama4j:ollama4j:${releaseInfo.name}")
}`}
</CodeBlock>
</>
) : null}
</div>
);
};
export default AddToYourProject;

View File

@ -0,0 +1,170 @@
// import React, { useState, useEffect } from 'react';
// import CodeBlock from '@theme/CodeBlock';
// import Icon from '@site/src/components/Icon';
// const CodeEmbed = ({ src }) => {
// const [code, setCode] = useState('');
// const [loading, setLoading] = useState(true);
// const [error, setError] = useState(null);
// useEffect(() => {
// let isMounted = true;
// const fetchCodeFromUrl = async (url) => {
// if (!isMounted) return;
// setLoading(true);
// setError(null);
// try {
// const response = await fetch(url);
// if (!response.ok) {
// throw new Error(`HTTP error! status: ${response.status}`);
// }
// const data = await response.text();
// if (isMounted) {
// setCode(data);
// }
// } catch (err) {
// console.error('Failed to fetch code:', err);
// if (isMounted) {
// setError(err);
// setCode(`// Failed to load code from ${url}\n// ${err.message}`);
// }
// } finally {
// if (isMounted) {
// setLoading(false);
// }
// }
// };
// if (src) {
// fetchCodeFromUrl(src);
// }
// return () => {
// isMounted = false;
// };
// }, [src]);
// const githubUrl = src ? src.replace('https://raw.githubusercontent.com', 'https://github.com').replace('/refs/heads/', '/blob/') : null;
// const fileName = src ? src.substring(src.lastIndexOf('/') + 1) : null;
// return (
// loading ? (
// <div>Loading code...</div>
// ) : error ? (
// <div>Error: {error.message}</div>
// ) : (
// <div style={{ backgroundColor: 'transparent', padding: '0px', borderRadius: '5px' }}>
// <div style={{ textAlign: 'right' }}>
// {githubUrl && (
// <a href={githubUrl} target="_blank" rel="noopener noreferrer" style={{ paddingRight: '15px', color: 'gray', fontSize: '0.8em', fontStyle: 'italic', display: 'inline-flex', alignItems: 'center' }}>
// View on GitHub
// <Icon icon="mdi:github" height="48" />
// </a>
// )}
// </div>
// <CodeBlock title={fileName} className="language-java">{code}</CodeBlock>
// </div>
// )
// );
// };
// export default CodeEmbed;
import React, { useState, useEffect } from 'react';
import CodeBlock from '@theme/CodeBlock';
import Icon from '@site/src/components/Icon';
const CodeEmbed = ({ src }) => {
const [code, setCode] = useState('');
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let isMounted = true;
const fetchCodeFromUrl = async (url) => {
if (!isMounted) return;
setLoading(true);
setError(null);
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.text();
if (isMounted) {
setCode(data);
}
} catch (err) {
console.error('Failed to fetch code:', err);
if (isMounted) {
setError(err);
setCode(`// Failed to load code from ${url}\n// ${err.message}`);
}
} finally {
if (isMounted) {
setLoading(false);
}
}
};
if (src) {
fetchCodeFromUrl(src);
}
return () => {
isMounted = false;
};
}, [src]);
const githubUrl = src ? src.replace('https://raw.githubusercontent.com', 'https://github.com').replace('/refs/heads/', '/blob/') : null;
const fileName = src ? src.substring(src.lastIndexOf('/') + 1) : null;
const title = (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<a
href={githubUrl}
target="_blank"
rel="noopener noreferrer"
style={{
color: 'gray',
textDecoration: 'none',
}}
onMouseOver={e => {
e.target.style.textDecoration = 'underline';
}}
onMouseOut={e => {
e.target.style.textDecoration = 'none';
}}
>
<span>{fileName}</span>
</a>
{githubUrl && (
<a href={githubUrl} target="_blank" rel="noopener noreferrer" style={{ color: 'gray', fontSize: '0.9em', fontStyle: 'italic', display: 'inline-flex', alignItems: 'center' }}>
View on GitHub
<Icon icon="mdi:github" height="1em" />
</a>
)}
</div>
);
return (
loading ? (
<div>Loading code...</div>
) : error ? (
<div>Error: {error.message}</div>
) : (
<div style={{ backgroundColor: 'transparent', padding: '0px', borderRadius: '5px' }}>
<CodeBlock title={title} className="language-java">{code}</CodeBlock>
</div>
)
);
};
export default CodeEmbed;

View File

@ -1,39 +1,107 @@
import clsx from 'clsx';
import Heading from '@theme/Heading';
import styles from './styles.module.css';
import Ollama4jUIImageCarousel from '@site/src/components/Ollama4jUIImageCarousel';
const FeatureList = [
{
title: 'Easy LLM Integration',
Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default,
description: (
<>
Easy integration with Ollama, enabling the execution of large language models locally.
</>
),
},
{
title: 'Developer-Friendly',
Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default,
description: (
<>
Clean and simple <code>APIs</code>, focused on seamless interaction with Ollama.
Provides clean and simple <code>APIs</code> for interacting with Ollama, including model management, chat functionalities, and authentication capability when Ollama is deployed behind proxy server.
</>
),
},
{
title: 'Powered by Java',
title: 'Chat with Images',
Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default,
description: (
<>
Supports interactions with vision/image models, allowing you to build applications that can understand and respond to visual content. Upload images directly into your chat sessions and receive intelligent, context-aware replies.
</>
),
},
{
title: 'Tools Support',
Svg: require('@site/static/img/undraw_docusaurus_react.svg').default,
description: (
<>
Empowers Java developers to harness the full capabilities of Ollama.
Supports tool/function calling with tool calling models such as mistral, llama3.x, qwen, etc. Empower your models to interact with external services and data sources, enabling more complex and dynamic AI workflows.
</>
),
},
];
const UsageList = [
{
title: 'Datafaker',
Svg: require('@site/static/img/datafaker.svg').default,
link: 'https://www.datafaker.net/',
description: (
<>
A powerful fake data generation library designed for JVM programs, offering over 200 data providers to easily create realistic and diverse datasets within minutes.
</>
),
imageSize: '20%',
},
{
title: 'Katie',
Svg: require('@site/static/img/katie_logo_v3.svg').default,
link: 'https://katie.qa/home',
description: (
<>
An Open Source AI-based question-answering platform that helps companies and organizations make their private domain knowledge accessible and useful to their employees and customers.
</>
),
imageSize: '30%',
},
{
title: 'AI Player',
Svg: require('@site/static/img/ai-player.svg').default,
link: 'https://modrinth.com/mod/ai-player',
description: (
<>
A minecraft mod which aims to add a "second player" into the game which will actually be intelligent.
</>
),
imageSize: '15%',
},
{
title: 'Ollama Translator Plugin',
Svg: require('@site/static/img/minecraft-spigot.svg').default,
link: 'https://github.com/liebki/ollama-translator',
description: (
<>
A minecraft 1.21 spigot plugin allows to easily break language barriers by using ollama on the server to translate all messages into a specfic target language.
</>
),
imageSize: '20%',
},
{
title: 'JnsCLI',
Svg: require('@site/static/img/jnscli.svg').default,
link: 'https://github.com/mirum8/jnscli',
description: (
<>
JnsCLI is a command-line tool for Jenkins, allowing you to manage jobs, builds, and configurations directly from the terminal. It also features AI-powered error analysis for quick troubleshooting.
</>
),
imageSize: '20%',
},
{
title: 'Featured in a Research Article on AI-Assisted Code Optimization',
Svg: require('@site/static/img/pmc-logo.svg').default,
link: 'https://pmc.ncbi.nlm.nih.gov/articles/PMC11750896/',
description: (
<>
Ollama4j was used in a research article Large Language Model Based Mutations in Genetic Improvement (PubMed Central).
</>
),
imageSize: '50%',
},
];
function Feature({Svg, title, description}) {
function Feature({ Svg, title, description }) {
return (
<div className={clsx('col col--4')}>
<div className="text--center">
@ -47,16 +115,58 @@ function Feature({Svg, title, description}) {
);
}
export default function HomepageFeatures() {
function Usage({ Svg, title, description, link, imageSize }) {
return (
<section className={styles.features}>
<div className="container">
<div className="row">
{FeatureList.map((props, idx) => (
<Feature key={idx} {...props} />
))}
</div>
<div className={clsx('col col--4')}>
<div className="text--center">
<Svg className={styles.featureSvg} role="img" style={{ width: imageSize }} />
</div>
</section>
<div className="text--center padding-horiz--md">
<Heading as="h3" style={{ color: 'red' }}>
{link ? (
<a href={link} target="_blank" rel="noopener noreferrer" style={{ color: '#11bc11' }}>
{title}
</a>
) : (
<span style={{ color: 'red' }}>{title}</span>
)}
</Heading>
<p>{description}</p>
</div>
</div>
);
}
export default function HomepageFeatures() {
return (
<>
<section className={styles.features}>
<div className="container">
<div className="row">
{FeatureList.map((props, idx) => (
<Feature key={idx} {...props} />
))}
</div>
</div>
</section>
<hr />
<section className={styles.features}>
<div className="container">
<div style={{ fontSize: '20px', fontWeight: 'bold', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
Check out who's using Ollama4j
</div>
<div className="row">
{UsageList.map((props, idx) => (
<Usage key={idx} {...props} />
))}
</div>
</div>
</section>
<section className={styles.features}>
<div className="container">
<Ollama4jUIImageCarousel></Ollama4jUIImageCarousel>
</div>
</section>
</>
);
}

View File

@ -0,0 +1,9 @@
// @site/src/components/Icon.js
import React from 'react';
import { Icon as IconifyIcon } from '@iconify/react';
const IIcon = ({ icon, color, width = '24', height = '24' }) => (
<IconifyIcon icon={icon} color={color} width={width} height={height} />
);
export default IIcon;

View File

@ -0,0 +1,52 @@
import React, { useState, useEffect } from 'react';
const LatestRelease = ({ showReleaseDate }) => {
const [releaseInfo, setReleaseInfo] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchLatestRelease = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch('https://api.github.com/repos/ollama4j/ollama4j/releases/latest');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setReleaseInfo(data);
} catch (err) {
console.error('Failed to fetch release info:', err);
setError(err);
} finally {
setLoading(false);
}
};
fetchLatestRelease();
}, []);
return (
<div style={{ display: 'flex', justifyContent: 'center' }}>
{loading ? (
<div>Loading latest release info...</div>
) : error ? (
<div>Error: {error.message}</div>
) : releaseInfo ? (
<div>
{/* <h4 style={{ display: 'flex', justifyContent: 'center'}}>Latest Release</h4> */}
<div>
<span style={{ fontWeight: 'bold'}}>Latest Version</span>: <a href={releaseInfo.html_url} target='_blank' rel="noopener noreferrer"><span style={{color: 'white', fontWeight: 'bold', backgroundColor:'#11bc11', borderRadius: '15px', padding: '5px'}}>{releaseInfo.name}</span></a>
{showReleaseDate && ` released on ${new Date(releaseInfo.published_at).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })}`}
</div>
{/* <pre style={{ whiteSpace: 'pre-wrap' }}>
{JSON.stringify(releaseInfo, null, 2)}
</pre> */}
</div>
) : null}
</div>
);
};
export default LatestRelease;

View File

@ -0,0 +1,54 @@
import React from 'react';
import "react-image-gallery/styles/css/image-gallery.css";
import ImageGallery from "react-image-gallery";
const images = [
{
original: require('@site/static/img/ollama4j-ui/1.png').default,
thumbnail: require('@site/static/img/ollama4j-ui/1.png').default,
},
{
original: require('@site/static/img/ollama4j-ui/2.png').default,
thumbnail: require('@site/static/img/ollama4j-ui/2.png').default,
},
{
original: require('@site/static/img/ollama4j-ui/3.png').default,
thumbnail: require('@site/static/img/ollama4j-ui/3.png').default,
},
{
original: require('@site/static/img/ollama4j-ui/4.png').default,
thumbnail: require('@site/static/img/ollama4j-ui/4.png').default,
},
];
class Ollama4jUIImageCarousel extends React.Component {
renderItem = (item) => {
return (
<div className="image-gallery-image" style={{ textAlign: 'center' }}>
<img
src={item.original}
alt=""
style={{ maxHeight: '500px', width: 'auto', maxWidth: '100%' }}
/>
</div>
);
};
render() {
return (
<div style={{ margin: '0 auto', maxWidth: '800px' }}>
<div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', textAlign: 'center' }}>
<h2>Explore the stuff we have built with Ollama4j</h2>
<h4>
<a href="https://github.com/ollama4j/ollama4j-ui" target='_blank' rel="noopener noreferrer">
Ollama4j UI - Desktop UI built in Java with Swing
</a>
</h4>
</div>
<ImageGallery items={images} renderItem={this.renderItem} />
</div>
);
}
}
export default Ollama4jUIImageCarousel;

View File

@ -0,0 +1,66 @@
import React, { useEffect, useState, useRef } from 'react';
const TypewriterTextarea = ({ textContent, typingSpeed = 50, pauseBetweenSentences = 1000, height = '200px', width = '100%' }) => {
const [text, setText] = useState('');
const [sentenceIndex, setSentenceIndex] = useState(0);
const [charIndex, setCharIndex] = useState(0);
const sentences = textContent ? textContent.split('\n') : [];
const isTyping = useRef(false);
useEffect(() => {
if (!textContent) return;
if (!isTyping.current) {
isTyping.current = true;
}
if (sentenceIndex >= sentences.length) {
// Reset to start from the beginning
setSentenceIndex(0);
setCharIndex(0);
setText('');
return;
}
const currentSentence = sentences[sentenceIndex];
if (charIndex < currentSentence.length) {
const timeout = setTimeout(() => {
setText((prevText) => prevText + currentSentence[charIndex]);
setCharIndex((prevCharIndex) => prevCharIndex + 1);
}, typingSpeed);
return () => clearTimeout(timeout);
} else {
// Wait a bit, then go to the next sentence
const timeout = setTimeout(() => {
setSentenceIndex((prev) => prev + 1);
setCharIndex(0);
}, pauseBetweenSentences);
return () => clearTimeout(timeout);
}
}, [charIndex, sentenceIndex, sentences, typingSpeed, pauseBetweenSentences, textContent]);
return (
<textarea
value={text}
readOnly
rows={10}
cols={5}
style={{
width: typeof width === 'number' ? `${width}px` : width,
height: height,
padding: '1rem',
fontFamily: 'monospace',
fontSize: '1rem',
backgroundColor: '#f4f4f4',
border: '1px solid #ccc',
resize: 'none',
whiteSpace: 'pre-wrap',
}}
/>
);
};
export default TypewriterTextarea;

View File

@ -4,6 +4,8 @@
* work well for content-centric websites.
*/
@import 'font-awesome/css/font-awesome.min.css';
/* You can override the default Infima variables here. */
:root {
--ifm-color-primary: #2e8555;

View File

@ -7,39 +7,59 @@ import BuyMeACoffee from '@site/src/components/BuyMeACoffee';
import Heading from '@theme/Heading';
import styles from './index.module.css';
import BrowserOnly from '@docusaurus/BrowserOnly';
import LatestRelease from '@site/src/components/LatestRelease';
import TypewriterTextarea from '@site/src/components/TypewriterTextarea';
function HomepageHeader() {
const {siteConfig} = useDocusaurusContext();
return (<header className={clsx('hero hero--primary', styles.heroBanner)}>
<div className="container">
<Heading as="h1" className="hero__title">
{siteConfig.title}
</Heading>
<img src="img/logo.svg" alt="Ollama4j Logo" className={styles.logo}
style={{maxWidth: '20vh'}}/>
<p className="hero__subtitle">{siteConfig.tagline}</p>
<div className={styles.buttons}>
<Link
className="button button--secondary button--lg"
to="/intro">
Getting Started
</Link>
return (
<header className={clsx('hero hero--primary', styles.heroBanner)}>
<div className="container">
<Heading as="h1" className="hero__title">
{siteConfig.title}
</Heading>
<img
src="img/logo.svg"
alt="Ollama4j Logo"
className={styles.logo}
style={{ maxWidth: '20vh' }}
/>
<p className="hero__subtitle">{siteConfig.tagline}</p>
<div style={{ marginTop: '2rem' }}>
<TypewriterTextarea
textContent='Hello there! Im a handy little Java library that helps you talk to an Ollama server — nice and easy.'
typingSpeed={30}
pauseBetweenSentences={1200}
height='130px'
width='100%'
/>
</div>
<div className={styles.buttons} >
<Link className="button button--secondary button--lg" to="/intro" style={{ marginTop:'2rem' }}>
Get Started
</Link>
</div>
<div style={{ marginTop: '3rem' }}>
<LatestRelease showReleaseDate={false} />
</div>
</div>
</div>
</header>);
</header>
);
}
export default function Home() {
const {siteConfig} = useDocusaurusContext();
return (<Layout
title={`Hello from ${siteConfig.title}`}
return (
<Layout
title={`${siteConfig.title}`}
description="Description will go into a meta tag in <head />">
<HomepageHeader/>
<main>
<HomepageFeatures/>
<BrowserOnly>
{() => <BuyMeACoffee />}
</BrowserOnly>
</main>
</Layout>);
<HomepageHeader />
<main>
<HomepageFeatures />
<BrowserOnly>
{() => <BuyMeACoffee />}
</BrowserOnly>
</main>
</Layout>
);
}

7
docs/static/img/ai-player.svg vendored Normal file
View File

@ -0,0 +1,7 @@
<svg width="96" height="96" viewBox="0 0 96 96" xmlns="http://www.w3.org/2000/svg">
<rect width="96" height="96" rx="16" fill="#3F0F8D"/>
<path d="M26 24H70V32H26V24Z" fill="white"/>
<path d="M36 44H44V52H36V44Z" fill="white"/>
<path d="M52 44H60V52H52V44Z" fill="white"/>
<path d="M36 60H60V68H36V60Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 335 B

1
docs/static/img/datafaker.svg vendored Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="gray" d="M12 8a3 3 0 0 0 3-3 3 3 0 0 0-3-3 3 3 0 0 0-3 3 3 3 0 0 0 3 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54z"></path></svg>

After

Width:  |  Height:  |  Size: 263 B

345
docs/static/img/jnscli.svg vendored Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 501 KiB

13
docs/static/img/katie_logo_v3.svg vendored Normal file
View File

@ -0,0 +1,13 @@
<svg width="539" height="122" viewBox="0 0 539 122" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M233.794 106.267L194.606 73.1369L230.215 42.896C233.395 40.1969 233.755 35.4621 231.017 32.3237C228.282 29.1851 223.482 28.8263 220.301 31.533L177.914 67.5271V10.039C177.914 5.89749 174.511 2.54163 170.316 2.54163C166.119 2.54163 162.717 5.89749 162.717 10.039V111.961C162.717 116.103 166.119 119.458 170.316 119.458C174.511 119.458 177.914 116.103 177.914 111.961V78.7709L223.905 117.655C225.339 118.865 227.096 119.458 228.847 119.458C230.988 119.458 233.116 118.571 234.62 116.84C237.35 113.694 236.981 108.961 233.794 106.267Z" fill="#414041"/>
<path d="M323.056 30.4831C318.932 30.4831 315.592 33.8533 315.592 38.0129V42.0425C307.753 33.3984 296.966 27.9584 285.263 27.9584C262.554 27.9584 244.075 49.0502 244.075 74.9781C244.075 100.907 262.554 122 285.263 122C298.217 122 308.397 116.775 315.592 108.901V112.96C315.592 117.12 318.932 120.49 323.056 120.49C327.178 120.49 330.519 117.12 330.519 112.96V38.0129C330.519 33.8533 327.178 30.4831 323.056 30.4831ZM285.263 106.941C271.027 106.941 259.002 92.3023 259.002 74.9781C259.002 57.6537 271.027 43.018 285.263 43.018C298.803 43.018 313.299 55.8594 313.299 74.9781C313.299 95.962 299.197 106.941 285.263 106.941Z" fill="#414041"/>
<path d="M411.244 105.137C409.576 101.309 405.12 99.5521 401.277 101.222C400.739 101.454 400.076 101.763 399.304 102.121C395.776 103.764 385.034 108.765 380.927 106.146C378.976 104.904 377.859 100.863 377.859 95.0546V43.0501H394.522C398.705 43.0501 402.096 39.6633 402.096 35.4831C402.096 31.3029 398.705 27.9159 394.522 27.9159H377.859V7.56714C377.859 3.38695 374.47 0 370.285 0C366.102 0 362.711 3.38695 362.711 7.56714V27.9159H350.805C346.621 27.9159 343.231 31.3029 343.231 35.4831C343.231 39.6633 346.621 43.0501 350.805 43.0501H362.711V95.0546C362.711 106.629 366.102 114.654 372.785 118.909C376.316 121.155 380.207 122 384.1 122C392.482 122 400.877 118.088 405.707 115.839C406.339 115.544 406.885 115.288 407.327 115.095C411.161 113.428 412.917 108.969 411.244 105.137Z" fill="#414041"/>
<path d="M502.288 122C487.874 122 460.527 111.883 460.187 73.5909C460.052 58.2558 464.703 45.0328 473.288 36.3573C480.37 29.1992 489.739 25.4166 500.381 25.4166C526.708 25.4166 537.58 47.0116 538.976 67.2225C539.168 69.9859 538.2 72.7323 536.321 74.7481C534.467 76.7394 531.854 77.8793 529.147 77.8793H475.52C477.843 105.988 499.689 106.84 502.288 106.84C516.078 106.84 523.655 98.4106 523.729 98.327C526.452 95.1443 531.226 94.7713 534.398 97.4901C537.577 100.209 537.951 104.994 535.234 108.177C534.754 108.742 523.197 122 502.288 122ZM476.301 62.7194H523.227C519.981 43.6041 507.776 40.5766 500.381 40.5766C493.774 40.5766 488.273 42.7479 484.036 47.0289C480.257 50.851 477.621 56.2473 476.301 62.7194Z" fill="#414041"/>
<path d="M434.759 33.0416C430.546 33.0416 427.132 36.4385 427.132 40.6307V111.869C427.132 116.061 430.546 119.458 434.759 119.458C438.973 119.458 442.387 116.061 442.387 111.869V40.6307C442.387 36.4385 438.973 33.0416 434.759 33.0416Z" fill="#414041"/>
<path d="M434.759 22.875C440.376 22.875 444.929 18.3232 444.929 12.7083C444.929 7.09347 440.376 2.54163 434.759 2.54163C429.142 2.54163 424.59 7.09347 424.59 12.7083C424.59 18.3232 429.142 22.875 434.759 22.875Z" fill="#414041"/>
<path d="M111.868 0H10.1698C4.55318 0 0 4.55177 0 10.1667V111.833C0 117.448 4.55318 122 10.1698 122H111.868C117.485 122 122.038 117.448 122.038 111.833V10.1667C122.038 4.55177 117.485 0 111.868 0Z" fill="#FF89BB"/>
<path d="M119.138 3H3.10229V119H119.138V3Z" fill="#FF89BB"/>
<path d="M37.0639 65.2438C41.7531 65.2438 45.5543 60.8104 45.5543 55.3414C45.5543 49.8724 41.7531 45.439 37.0639 45.439C32.3748 45.439 28.5735 49.8724 28.5735 55.3414C28.5735 60.8104 32.3748 65.2438 37.0639 65.2438Z" fill="#414041"/>
<path d="M82.3464 56.756C87.0355 56.756 90.8368 52.3226 90.8368 46.8536C90.8368 41.3846 87.0355 36.9512 82.3464 36.9512C77.6573 36.9512 73.856 41.3846 73.856 46.8536C73.856 52.3226 77.6573 56.756 82.3464 56.756Z" fill="#414041"/>
<path d="M59.8714 99.1951C42.5471 99.1951 30.8795 89.4538 30.3195 88.985C28.2142 87.1935 27.9803 84.0583 29.7949 81.9799C31.6096 79.9085 34.771 79.6705 36.8763 81.448C37.0748 81.616 49.2599 91.5603 65.9462 88.747C83.0366 85.8638 93.003 73.0154 93.1022 72.8894C94.768 70.699 97.9153 70.2511 100.134 71.8887C102.353 73.5262 102.821 76.6194 101.169 78.8168C100.673 79.4746 88.8208 94.9683 67.6333 98.5373C64.9468 98.9992 62.3453 99.1951 59.8714 99.1951Z" fill="#414041"/>
</svg>

After

Width:  |  Height:  |  Size: 4.4 KiB

1
docs/static/img/minecraft-spigot.svg vendored Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" image-rendering="optimizeQuality" fill-rule="evenodd" clip-rule="evenodd" viewBox="0 0 512 448.012"><path fill="#424C57" fill-rule="nonzero" d="M386.912 404.082c-31.653 27.804-68.134 42.5-104.037 43.83-37.327 1.383-73.956-11.673-103.851-39.445l-15.148-14.072-54.139-44.075h-48.07c-25.406 0-43.633-20.936-46.214-46.212L.195 154.71c-2.581-25.279 20.879-48.258 46.214-46.215l189.276 15.258c25.335 2.042 46.214 20.793 46.214 46.215v134.14c0 25.418-20.805 46.212-46.214 46.212h-59.323l4.221 47.53 4.398 2.497c33.226 18.862 65.806 26.928 96.721 22.849 28.258-3.73 55.317-17.66 80.412-42.828l-15.449-13.603 64.278-14.309-7.532 67.307-16.499-15.681z"/><path fill="#337EC6" d="M276.315 73.91l113.118-9.119-30.176-17.127c-33.228-18.859-65.809-26.927-96.721-22.848-28.26 3.73-55.319 17.66-80.414 42.827l15.449 13.604-64.277 14.309 7.533-67.307 16.498 15.682C188.979 16.128 225.46 1.43 261.363.099c37.327-1.382 73.956 11.673 103.851 39.446l26.942 25.027 73.434-5.92c25.335-2.042 48.796 20.936 46.215 46.216l-15.258 149.397c-2.581 25.277-20.808 46.212-46.215 46.212h-50.099l-71.815 58.466 5.19-58.466h-57.293c-25.411 0-46.216-20.793-46.216-46.212V120.126c0-25.422 20.881-44.173 46.216-46.216z"/><path fill="#fff" d="M84.246 173.714h43.841v-12.353h19.585v12.353h44.001v20.281h-9.033c-1.629 12.811-5.21 23.368-11.297 34.746-5.149 9.611-11.796 18.87-19.516 27.744 12.32 14.735 27.616 27.554 45.826 39.24l-10.073 15.701c-19.119-12.267-35.356-25.774-48.699-41.332-11.936 11.547-25.496 22.303-39.7 32.127l-10.588-15.325c14.055-9.725 27.407-20.347 38.896-31.672-10.588-15.493-18.697-32.88-24.308-52.875l17.968-5.038c4.601 16.401 11.052 30.837 19.344 43.759 5.657-6.848 10.548-13.876 14.412-21.092 4.74-8.866 7.286-16.196 8.89-25.983H84.246v-20.281zM398.456 215.314h-55.931l-7.357 25.09h-27.814c11.988-31.729 25.831-69.829 37.825-101.573 4.318-11.466 9.234-30.467 24.943-30.467 16.284 0 21.691 17.409 26.222 29.436l38.4 103.122h-28.708l-7.58-25.608zm-6-24.398l-21.893-57.703-21.971 57.703h43.864z"/></svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

BIN
docs/static/img/ollama4j-ui/1.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 606 KiB

BIN
docs/static/img/ollama4j-ui/2.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 562 KiB

BIN
docs/static/img/ollama4j-ui/3.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 724 KiB

BIN
docs/static/img/ollama4j-ui/4.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 916 KiB

12
docs/static/img/pmc-logo.svg vendored Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.8 KiB