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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,12 @@ public static final class EmbeddingModel {
public static final String BEDROCK_SETUP =
"org.apache.flink.agents.integrations.embeddingmodels.bedrock.BedrockEmbeddingModelSetup";

// OpenAI
public static final String OPENAI_CONNECTION =
"org.apache.flink.agents.integrations.embeddingmodels.openai.OpenAIEmbeddingModelConnection";
public static final String OPENAI_SETUP =
"org.apache.flink.agents.integrations.embeddingmodels.openai.OpenAIEmbeddingModelSetup";

// Python Wrapper
public static final String PYTHON_WRAPPER_CONNECTION =
"org.apache.flink.agents.api.embedding.model.python.PythonEmbeddingModelConnection";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,11 @@ public VectorStoreQuery(
*
* @param mode the query mode
* @param queryText the text to search for
* @param limit maximum number of results to return
* @param limit maximum number of results to return; must be non-null and positive
* @param collection the collection to query to
* @param filters unified filter DSL (equality shorthand) or {@code null} for no filter
* @param extraArgs store-specific additional parameters
* @throws IllegalArgumentException if {@code limit} is {@code null} or non-positive
*/
public VectorStoreQuery(
VectorStoreQueryMode mode,
Expand All @@ -101,6 +102,13 @@ public VectorStoreQuery(
@Nullable String collection,
@Nullable Map<String, Object> filters,
Map<String, Object> extraArgs) {
if (limit == null) {
throw new IllegalArgumentException("`limit` must not be null.");
}
if (limit <= 0) {
throw new IllegalArgumentException(
String.format("`limit` must be positive, but was %d.", limit));
}
this.mode = mode;
this.queryText = queryText;
this.limit = limit;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ public final class Aliases {
Map<String, String> embConnJava = new HashMap<>();
embConnJava.put("ollama", ResourceName.EmbeddingModel.OLLAMA_CONNECTION);
embConnJava.put("bedrock", ResourceName.EmbeddingModel.BEDROCK_CONNECTION);
embConnJava.put("openai", ResourceName.EmbeddingModel.OPENAI_CONNECTION);
Map<String, String> embConnPython = new HashMap<>();
embConnPython.put("ollama", ResourceName.EmbeddingModel.Python.OLLAMA_CONNECTION);
embConnPython.put("openai", ResourceName.EmbeddingModel.Python.OPENAI_CONNECTION);
Expand All @@ -138,6 +139,7 @@ public final class Aliases {
Map<String, String> embJava = new HashMap<>();
embJava.put("ollama", ResourceName.EmbeddingModel.OLLAMA_SETUP);
embJava.put("bedrock", ResourceName.EmbeddingModel.BEDROCK_SETUP);
embJava.put("openai", ResourceName.EmbeddingModel.OPENAI_SETUP);
Map<String, String> embPython = new HashMap<>();
embPython.put("ollama", ResourceName.EmbeddingModel.Python.OLLAMA_SETUP);
embPython.put("openai", ResourceName.EmbeddingModel.Python.OPENAI_SETUP);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.flink.agents.api.vectorstores;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.HashMap;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

/** Tests for {@link VectorStoreQuery}. */
class VectorStoreQueryTest {

@Test
@DisplayName("Null limit is rejected with a message naming the parameter")
void testNullLimitRejected() {
assertThatThrownBy(() -> new VectorStoreQuery("flink", null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("limit");
}

@Test
@DisplayName("Negative limit is rejected with a message naming the parameter and its value")
void testNegativeLimitRejected() {
assertThatThrownBy(() -> new VectorStoreQuery("flink", -1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("limit")
.hasMessageContaining("-1");
}

@Test
@DisplayName("Negative limit is rejected through the fully specified constructor")
void testNegativeLimitRejectedWithAllArguments() {
assertThatThrownBy(
() ->
new VectorStoreQuery(
VectorStoreQueryMode.SEMANTIC,
"flink",
-5,
"collection",
null,
new HashMap<>()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("limit");
}

@Test
@DisplayName("Zero limit is rejected with a message naming the parameter and its value")
void testZeroLimitRejected() {
assertThatThrownBy(() -> new VectorStoreQuery("flink", 0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("limit")
.hasMessageContaining("0");
}

@Test
@DisplayName("Zero limit is rejected through the fully specified constructor")
void testZeroLimitRejectedWithAllArguments() {
assertThatThrownBy(
() ->
new VectorStoreQuery(
VectorStoreQueryMode.SEMANTIC,
"flink",
0,
"collection",
null,
new HashMap<>()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("limit")
.hasMessageContaining("0");
}

@Test
@DisplayName("Positive limits stay legal and are returned unchanged")
void testPositiveLimitsAccepted() {
assertThat(new VectorStoreQuery("flink", 5).getLimit()).isEqualTo(5);

assertThat(
new VectorStoreQuery(
VectorStoreQueryMode.SEMANTIC,
"flink",
10,
"collection",
null,
Collections.emptyMap())
.getLimit())
.isEqualTo(10);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,20 @@ void clazzAliasCoversChatModelJavaGeminiAndAzureOpenAI() {
assertThat(azureOpenAISetup).isEqualTo(ResourceName.ChatModel.AZURE_OPENAI_SETUP);
}

@Test
void clazzAliasCoversEmbeddingModelOpenAIInBothLanguages() {
assertThat(
Aliases.resolveClazz(
"openai", ResourceType.EMBEDDING_MODEL_CONNECTION, Language.JAVA))
.isEqualTo(ResourceName.EmbeddingModel.OPENAI_CONNECTION);
assertThat(Aliases.resolveClazz("openai", ResourceType.EMBEDDING_MODEL, Language.JAVA))
.isEqualTo(ResourceName.EmbeddingModel.OPENAI_SETUP);
assertThat(
Aliases.resolveClazz(
"openai", ResourceType.EMBEDDING_MODEL_CONNECTION, Language.PYTHON))
.isEqualTo(ResourceName.EmbeddingModel.Python.OPENAI_CONNECTION);
}

@Test
void clazzAliasCoversVectorStoreJavaAndPython() {
String opensearch =
Expand Down
5 changes: 5 additions & 0 deletions dist/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,11 @@ under the License.
<artifactId>flink-agents-integrations-embedding-models-bedrock</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-agents-integrations-embedding-models-openai</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-agents-integrations-vector-stores-elasticsearch</artifactId>
Expand Down
99 changes: 88 additions & 11 deletions docs/content/docs/development/embedding_models.md
Original file line number Diff line number Diff line change
Expand Up @@ -419,16 +419,15 @@ Model availability and specifications may change. Always check the official Olla

OpenAI provides cloud-based embedding models with state-of-the-art performance.

{{< hint info >}}
OpenAI embedding models are currently supported in the Python API only. To use OpenAI from Java agents, see [Using Cross-Language Providers](#using-cross-language-providers).
{{< /hint >}}

#### Prerequisites

1. Get an API key from [OpenAI Platform](https://platform.openai.com/)

#### Usage Example

{{< tabs "OpenAI Embedding Usage Example" >}}

{{< tab "Python" >}}
```python
class MyAgent(Agent):

Expand All @@ -453,28 +452,106 @@ class MyAgent(Agent):
encoding_format="float"
)
```
{{< /tab >}}

{{< tab "Java" >}}
```java
public class MyAgent extends Agent {

@EmbeddingModelConnection
public static ResourceDescriptor openaiConnection() {
return ResourceDescriptor.Builder.newBuilder(ResourceName.EmbeddingModel.OPENAI_CONNECTION)
.addInitialArgument("api_key", System.getenv("OPENAI_API_KEY"))
.addInitialArgument("request_timeout", 30)
.addInitialArgument("max_retries", 3)
.build();
}

@EmbeddingModelSetup
public static ResourceDescriptor openaiEmbedding() {
return ResourceDescriptor.Builder.newBuilder(ResourceName.EmbeddingModel.OPENAI_SETUP)
.addInitialArgument("connection", "openaiConnection")
.addInitialArgument("model", "text-embedding-3-small")
.addInitialArgument("dimensions", 512)
.build();
}

...
}
```
{{< /tab >}}

{{< /tabs >}}

#### OpenAIEmbeddingModelConnection Parameters

{{< tabs "OpenAIEmbeddingModelConnection Parameters" >}}

{{< tab "Python" >}}

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `api_key` | str | Required | OpenAI API key for authentication |
| `api_key` | str | Required | OpenAI API key for authentication; a blank key is passed through to the SDK for unauthenticated OpenAI-compatible servers (the Java connection rejects a blank key) |
| `base_url` | str | `"https://api.openai.com/v1"` | OpenAI API base URL |
| `request_timeout` | float | `30.0` | HTTP request timeout in seconds |
| `request_timeout` | float | `30.0` | HTTP request timeout in seconds; `0` disables the timeout |
| `max_retries` | int | `3` | Maximum number of retry attempts |
| `organization` | str | None | Optional organization ID |
| `project` | str | None | Optional project ID |
| `organization` | str | None | Optional organization ID; when unset or blank the Python SDK may read `OPENAI_ORG_ID` from the environment (the Java connection sends no organization) |
| `project` | str | None | Optional project ID; when unset or blank the Python SDK may read `OPENAI_PROJECT_ID` from the environment (the Java connection sends no project) |

{{< /tab >}}

{{< tab "Java" >}}

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `api_key` | String | Required | OpenAI API key for authentication |
| `base_url` | String | `"https://api.openai.com/v1"` | OpenAI API base URL |
| `request_timeout` | Number | `30` | HTTP request timeout in seconds; `0` disables the timeout |
| `max_retries` | Number | `3` | Maximum number of retry attempts, a non-negative integer |
| `organization` | String | None | Optional organization ID |
| `project` | String | None | Optional project ID |

{{< /tab >}}

{{< /tabs >}}

#### OpenAIEmbeddingModelSetup Parameters

{{< tabs "OpenAIEmbeddingModelSetup Parameters" >}}

{{< tab "Python" >}}

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `connection` | str | Required | Reference to connection method name |
| `model` | str | Required | OpenAI embedding model name |
| `encoding_format` | str | `"float"` | Return format ("float" or "base64") |
| `encoding_format` | str | `"float"` | Wire format, `"float"` or `"base64"`; base64 responses are decoded to floats |
| `dimensions` | int | None | Output dimensions (text-embedding-3 models only) |
| `user` | str | None | End-user identifier for monitoring |
| `additional_kwargs` | dict | `{}` | Additional parameters for the OpenAI embeddings API |
| `additional_kwargs` | dict | `{}` | Extra request body properties sent with every embeddings request; keys may not be `model`, `input`, `encoding_format`, `dimensions` or `user`. A per-call `additional_kwargs` replaces this map |

`additional_kwargs` entries are sent to the API as request body properties; an entry that repeats a typed field fails validation (set the typed argument instead), and `dimensions` must be an integer.

{{< /tab >}}

{{< tab "Java" >}}

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `connection` | String | Required | Reference to connection method name |
| `model` | String | Required | OpenAI embedding model name |
| `encoding_format` | String | `"float"` | Wire format, `"float"` or `"base64"`; base64 responses are decoded to floats |
| `dimensions` | Number | None | Output dimensions, a positive integer (text-embedding-3 models only) |
| `user` | String | None | End-user identifier for monitoring |
| `additional_kwargs` | Map | `{}` | Extra request body properties sent with every embeddings request; keys may not be `model`, `input`, `encoding_format`, `dimensions` or `user`. A per-call `additional_kwargs` replaces this map |


`additional_kwargs` entries that repeat a typed field fail validation instead of overriding it (set the typed argument instead), and `dimensions` must be a positive integer.
{{< /tab >}}

{{< /tabs >}}

A batch of texts is embedded in a single request, so it must stay within OpenAI's per-request limits (2048 inputs at the time of writing); split larger batches before calling. Token usage reported by the API is available through `embedWithUsage` in Java and `embed_with_usage` in Python.

#### Available Models

Expand Down Expand Up @@ -559,7 +636,7 @@ Model availability and specifications may change. Always check the official Dash

## Using Cross-Language Providers

Flink Agents supports cross-language embedding model integration, allowing you to use embedding models implemented in one language (Java or Python) from agents written in the other language. This is particularly useful when an embedding model provider is only available in one language (e.g., OpenAI embedding is currently Python-only).
Flink Agents supports cross-language embedding model integration, allowing you to use embedding models implemented in one language (Java or Python) from agents written in the other language. This is particularly useful when an embedding model provider is only available in one language (e.g., Tongyi embedding is currently Python-only).

{{< hint warning >}}
**Limitations:**
Expand Down
2 changes: 1 addition & 1 deletion docs/content/docs/development/yaml.md
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,7 @@ Embedding-model aliases (apply to both `embedding_model_connections` and `embedd
| Alias | `type: python` | `type: java` |
| --------- | -------------- | -------------- |
| `ollama` | Ollama | Ollama |
| `openai` | OpenAI | — |
| `openai` | OpenAI | OpenAI (Java) |
| `tongyi` | Tongyi | — |
| `bedrock` | — | Bedrock (Java) |

Expand Down
2 changes: 1 addition & 1 deletion docs/content/docs/faq/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ Flink Agents provides built-in integrations for many ecosystem providers. Some i
|---|---|---|
| [Amazon Bedrock]({{< ref "docs/development/embedding_models#amazon-bedrock" >}}) | ❌ | ✅ |
| [Ollama]({{< ref "docs/development/embedding_models#ollama" >}}) | ✅ | ✅ |
| [OpenAI]({{< ref "docs/development/embedding_models#openai" >}}) | ✅ | ❌ |
| [OpenAI]({{< ref "docs/development/embedding_models#openai" >}}) | ✅ | ✅ |
| [Tongyi (DashScope)]({{< ref "docs/development/embedding_models#tongyi-dashscope" >}}) | ✅ | ❌ |

**Vector Stores**
Expand Down
5 changes: 5 additions & 0 deletions e2e-test/flink-agents-end-to-end-tests-integration/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ under the License.
<artifactId>flink-agents-integrations-embedding-models-ollama</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-agents-integrations-embedding-models-openai</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-agents-integrations-vector-stores-elasticsearch</artifactId>
Expand Down
Loading
Loading