You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by wa...@apache.org on 2024/09/03 12:10:56 UTC
(seatunnel) branch dev updated: [Feature][Transform] Add embedding transform (#7534)
This is an automated email from the ASF dual-hosted git repository.
wanghailin pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
The following commit(s) were added to refs/heads/dev by this push:
new 3310cfcd34 [Feature][Transform] Add embedding transform (#7534)
3310cfcd34 is described below
commit 3310cfcd347a00fae2cb0906093c9e3c51c93212
Author: corgy-w <73...@users.noreply.github.com>
AuthorDate: Tue Sep 3 20:10:51 2024 +0800
[Feature][Transform] Add embedding transform (#7534)
---
docs/en/transform-v2/embedding.md | 392 +++++++++++++++++++++
docs/en/transform-v2/llm.md | 28 +-
docs/zh/transform-v2/embedding.md | 382 ++++++++++++++++++++
docs/zh/transform-v2/llm.md | 24 +-
plugin-mapping.properties | 1 +
.../seatunnel/api/table/type/SeaTunnelRow.java | 3 +
.../assertion/excecutor/AssertExecutor.java | 8 +
.../{TestLLMIT.java => TestEmbeddingIT.java} | 24 +-
.../apache/seatunnel/e2e/transform/TestLLMIT.java | 7 +
.../src/test/resources/embedding_transform.conf | 295 ++++++++++++++++
.../test/resources/embedding_transform_custom.conf | 152 ++++++++
.../src/test/resources/llm_transform_custom.conf | 91 +++++
.../src/test/resources/mock-embedding.json | 75 ++++
.../nlpmodel/CustomConfigPlaceholder.java | 56 +++
.../transform/nlpmodel/ModelProvider.java | 50 +++
.../transform/nlpmodel/ModelTransformConfig.java | 115 ++++++
.../nlpmodel/embadding/EmbeddingTransform.java | 205 +++++++++++
.../embadding/EmbeddingTransformConfig.java | 41 +++
.../embadding/EmbeddingTransformFactory.java} | 41 ++-
.../nlpmodel/embadding/remote/AbstractModel.java | 70 ++++
.../embadding/remote/Model.java} | 14 +-
.../embadding/remote/custom/CustomModel.java | 152 ++++++++
.../embadding/remote/doubao/DoubaoModel.java} | 74 ++--
.../embadding/remote}/openai/OpenAIModel.java | 72 ++--
.../embadding/remote/qianfan/QianfanModel.java | 173 +++++++++
.../transform/{ => nlpmodel}/llm/LLMTransform.java | 62 +++-
.../{ => nlpmodel}/llm/LLMTransformConfig.java | 35 +-
.../{ => nlpmodel}/llm/LLMTransformFactory.java | 26 +-
.../llm/remote}/AbstractModel.java | 2 +-
.../{llm/model => nlpmodel/llm/remote}/Model.java | 2 +-
.../nlpmodel/llm/remote/custom/CustomModel.java | 152 ++++++++
.../llm/remote}/openai/OpenAIModel.java | 4 +-
...est.java => EmbeddingTransformFactoryTest.java} | 8 +-
.../transform/LLMTransformFactoryTest.java | 2 +-
.../embedding/EmbeddingRequestJsonTest.java | 143 ++++++++
.../transform/llm/LLMRequestJsonTest.java | 53 ++-
36 files changed, 2861 insertions(+), 173 deletions(-)
diff --git a/docs/en/transform-v2/embedding.md b/docs/en/transform-v2/embedding.md
new file mode 100644
index 0000000000..680c691042
--- /dev/null
+++ b/docs/en/transform-v2/embedding.md
@@ -0,0 +1,392 @@
+# Embedding
+
+> Embedding Transform Plugin
+
+## Description
+
+The `Embedding` transform plugin leverages embedding models to convert text data into vectorized representations. This
+transformation can be applied to various fields. The plugin supports multiple model providers and can be integrated with
+different API endpoints.
+
+## Options
+
+| Name | Type | Required | Default Value | Description |
+|--------------------------------|--------|----------|---------------|-------------------------------------------------------------------------------------------------------------|
+| model_provider | enum | yes | - | The model provider for embedding. Options may include `QIANFAN`, `OPENAI`, etc. |
+| api_key | string | yes | - | The API key required to authenticate with the embedding service. |
+| secret_key | string | yes | - | The secret key required for additional authentication with the embedding service. |
+| single_vectorized_input_number | int | no | 1 | The number of inputs vectorized in one request. Default is 1. |
+| vectorization_fields | map | yes | - | A mapping between input fields and their corresponding output vector fields. |
+| model | string | yes | - | The specific model to use for embedding (e.g: `text-embedding-3-small` for OPENAI). |
+| api_path | string | no | - | The API endpoint for the embedding service. Typically provided by the model provider. |
+| oauth_path | string | no | - | The API endpoint for the oauth service. |
+| custom_config | map | no | | Custom configurations for the model. |
+| custom_response_parse | string | no | | Specifies how to parse the response from the model using JsonPath. Example: `$.choices[*].message.content`. |
+| custom_request_headers | map | no | | Custom headers for the request to the model. |
+| custom_request_body | map | no | | Custom body for the request. Supports placeholders like `${model}`, `${input}`. |
+
+### model_provider
+
+The providers for generating embeddings include common options such as `DOUBAO`, `QIANFAN`, and `OPENAI`. Additionally,
+you can choose `CUSTOM` to implement requests and retrievals for custom embedding models.
+
+### api_key
+
+The API key for authenticating requests to the embedding service. This is typically provided by the model provider when
+you register for their service.
+
+### secret_key
+
+The secret key used for additional authentication. Some providers may require this for secure API requests.
+
+### single_vectorized_input_number
+
+Specifies how many inputs are processed in a single vectorization request. The default is 1. Adjust based on your
+processing
+capacity and the model provider's API limitations.
+
+### vectorization_fields
+
+A mapping between input fields and their respective output vector fields. This allows the plugin to understand which
+text fields to vectorize and how to store the resulting vectors.
+
+```hocon
+vectorization_fields {
+ book_intro_vector = book_intro
+ author_biography_vector = author_biography
+}
+```
+
+### model
+
+The specific embedding model to use. This depends on the `embedding_model_provider`. For example, if using OPENAI, you
+might specify `text-embedding-3-small`.
+
+### api_path
+
+The API endpoint to use for making requests to the embedding service. This might vary based on the provider and model
+used. Generally, this is provided by the model provider.
+
+### oauth_path
+
+The API endpoint for the oauth service. Get certification information. This might vary based on the provider and model
+used. Generally, this is provided by the model provider.
+
+### custom_config
+
+The `custom_config` option allows you to provide additional custom configurations for the model. This is a map where you
+can define various settings that might be required by the specific model you're using.
+
+### custom_response_parse
+
+The `custom_response_parse` option allows you to specify how to parse the model's response. You can use JsonPath to
+extract the specific data you need from the response. For example, by using `$.data[*].embedding`, you can extract
+the `embedding` field values from the following JSON and obtain a `List` of nested `List` results. For more details on
+using JsonPath, please refer to
+the [JsonPath Getting Started guide](https://github.com/json-path/JsonPath?tab=readme-ov-file#getting-started).
+
+```json
+{
+ "object": "list",
+ "data": [
+ {
+ "object": "embedding",
+ "index": 0,
+ "embedding": [
+ -0.006929283495992422,
+ -0.005336422007530928,
+ -0.00004547132266452536,
+ -0.024047505110502243
+ ]
+ }
+ ],
+ "model": "text-embedding-3-small",
+ "usage": {
+ "prompt_tokens": 5,
+ "total_tokens": 5
+ }
+}
+```
+
+### custom_request_headers
+
+The `custom_request_headers` option allows you to define custom headers that should be included in the request sent to
+the model's API. This is useful if the API requires additional headers beyond the standard ones, such as authorization
+tokens, content types, etc.
+
+### custom_request_body
+
+The `custom_request_body` option supports placeholders:
+
+- `${model}`: Placeholder for the model name.
+- `${input}`: Placeholder to determine input value and define request body request type based on the type of body
+ value. Example: `["${input}"]` -> ["input"] (list)
+
+### common options
+
+Transform plugin common parameters, please refer to [Transform Plugin](common-options.md) for details.
+
+## Example Configuration
+
+```hocon
+env {
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ row.num = 5
+ schema = {
+ fields {
+ book_id = "int"
+ book_name = "string"
+ book_intro = "string"
+ author_biography = "string"
+ }
+ }
+ rows = [
+ {fields = [1, "To Kill a Mockingbird",
+ "Set in the American South during the 1930s, To Kill a Mockingbird tells the story of young Scout Finch and her brother, Jem, who are growing up in a world of racial inequality and injustice. Their father, Atticus Finch, is a lawyer who defends a black man falsely accused of raping a white woman, teaching his children valuable lessons about morality, courage, and empathy.",
+ "Harper Lee (1926–2016) was an American novelist best known for To Kill a Mockingbird, which won the Pulitzer Prize in 1961. Lee was born in Monroeville, Alabama, and the town served as inspiration for the fictional Maycomb in her novel. Despite the success of her book, Lee remained a private person and published only one other novel, Go Set a Watchman, which was written before To Kill a Mockingbird but released in 2015 as a sequel."
+ ], kind = INSERT}
+ {fields = [2, "1984",
+ "1984 is a dystopian novel set in a totalitarian society governed by Big Brother. The story follows Winston Smith, a man who works for the Party rewriting history. Winston begins to question the Party’s control and seeks truth and freedom in a society where individuality is crushed. The novel explores themes of surveillance, propaganda, and the loss of personal autonomy.",
+ "George Orwell (1903–1950) was the pen name of Eric Arthur Blair, an English novelist, essayist, journalist, and critic. Orwell is best known for his works 1984 and Animal Farm, both of which are critiques of totalitarian regimes. His writing is characterized by lucid prose, awareness of social injustice, opposition to totalitarianism, and support of democratic socialism. Orwell’s work remains influential, and his ideas have shaped contemporary discussions on politics and society."
+ ], kind = INSERT}
+ {fields = [3, "Pride and Prejudice",
+ "Pride and Prejudice is a romantic novel that explores the complex relationships between different social classes in early 19th century England. The story centers on Elizabeth Bennet, a young woman with strong opinions, and Mr. Darcy, a wealthy but reserved gentleman. The novel deals with themes of love, marriage, and societal expectations, offering keen insights into human behavior.",
+ "Jane Austen (1775–1817) was an English novelist known for her sharp social commentary and keen observations of the British landed gentry. Her works, including Sense and Sensibility, Emma, and Pride and Prejudice, are celebrated for their wit, realism, and biting critique of the social class structure of her time. Despite her relatively modest life, Austen’s novels have gained immense popularity, and she is considered one of the greatest novelists in the English language."
+ ], kind = INSERT}
+ {fields = [4, "The Great GatsbyThe Great Gatsby",
+ "The Great Gatsby is a novel about the American Dream and the disillusionment that can come with it. Set in the 1920s, the story follows Nick Carraway as he becomes entangled in the lives of his mysterious neighbor, Jay Gatsby, and the wealthy elite of Long Island. Gatsby's obsession with the beautiful Daisy Buchanan drives the narrative, exploring themes of wealth, love, and the decay of the American Dream.",
+ "F. Scott Fitzgerald (1896–1940) was an American novelist and short story writer, widely regarded as one of the greatest American writers of the 20th century. Born in St. Paul, Minnesota, Fitzgerald is best known for his novel The Great Gatsby, which is often considered the quintessential work of the Jazz Age. His works often explore themes of youth, wealth, and the American Dream, reflecting the turbulence and excesses of the 1920s."
+ ], kind = INSERT}
+ {fields = [5, "Moby-Dick",
+ "Moby-Dick is an epic tale of obsession and revenge. The novel follows the journey of Captain Ahab, who is on a relentless quest to kill the white whale, Moby Dick, that once maimed him. Narrated by Ishmael, a sailor aboard Ahab’s ship, the story delves into themes of fate, humanity, and the struggle between man and nature. The novel is also rich with symbolism and philosophical musings.",
+ "Herman Melville (1819–1891) was an American novelist, short story writer, and poet of the American Renaissance period. Born in New York City, Melville gained initial fame with novels such as Typee and Omoo, but it was Moby-Dick, published in 1851, that would later be recognized as his masterpiece. Melville’s work is known for its complexity, symbolism, and exploration of themes such as man’s place in the universe, the nature of evil, and the quest for meaning. Despite facing finan [...]
+ ], kind = INSERT}
+ ]
+ result_table_name = "fake"
+ }
+}
+
+transform {
+ Embedding {
+ source_table_name = "fake"
+ embedding_model_provider = QIANFAN
+ model = bge_large_en
+ api_key = xxxxxxxxxx
+ secret_key = xxxxxxxxxx
+ api_path = xxxxxxxxxx
+ vectorization_fields {
+ book_intro_vector = book_intro
+ author_biography_vector = author_biography
+ }
+ result_table_name = "embedding_output"
+ }
+}
+
+sink {
+ Assert {
+ source_table_name = "embedding_output"
+ rules =
+ {
+ field_rules = [
+ {
+ field_name = book_id
+ field_type = int
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_name
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ }
+ ]
+ }
+ }
+}
+```
+
+### Customize the embedding model
+
+```hocon
+
+env {
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ row.num = 5
+ schema = {
+ fields {
+ book_id = "int"
+ book_name = "string"
+ book_intro = "string"
+ author_biography = "string"
+ }
+ }
+ rows = [
+ {fields = [1, "To Kill a Mockingbird",
+ "Set in the American South during the 1930s, To Kill a Mockingbird tells the story of young Scout Finch and her brother, Jem, who are growing up in a world of racial inequality and injustice. Their father, Atticus Finch, is a lawyer who defends a black man falsely accused of raping a white woman, teaching his children valuable lessons about morality, courage, and empathy.",
+ "Harper Lee (1926–2016) was an American novelist best known for To Kill a Mockingbird, which won the Pulitzer Prize in 1961. Lee was born in Monroeville, Alabama, and the town served as inspiration for the fictional Maycomb in her novel. Despite the success of her book, Lee remained a private person and published only one other novel, Go Set a Watchman, which was written before To Kill a Mockingbird but released in 2015 as a sequel."
+ ], kind = INSERT}
+ {fields = [2, "1984",
+ "1984 is a dystopian novel set in a totalitarian society governed by Big Brother. The story follows Winston Smith, a man who works for the Party rewriting history. Winston begins to question the Party’s control and seeks truth and freedom in a society where individuality is crushed. The novel explores themes of surveillance, propaganda, and the loss of personal autonomy.",
+ "George Orwell (1903–1950) was the pen name of Eric Arthur Blair, an English novelist, essayist, journalist, and critic. Orwell is best known for his works 1984 and Animal Farm, both of which are critiques of totalitarian regimes. His writing is characterized by lucid prose, awareness of social injustice, opposition to totalitarianism, and support of democratic socialism. Orwell’s work remains influential, and his ideas have shaped contemporary discussions on politics and society."
+ ], kind = INSERT}
+ {fields = [3, "Pride and Prejudice",
+ "Pride and Prejudice is a romantic novel that explores the complex relationships between different social classes in early 19th century England. The story centers on Elizabeth Bennet, a young woman with strong opinions, and Mr. Darcy, a wealthy but reserved gentleman. The novel deals with themes of love, marriage, and societal expectations, offering keen insights into human behavior.",
+ "Jane Austen (1775–1817) was an English novelist known for her sharp social commentary and keen observations of the British landed gentry. Her works, including Sense and Sensibility, Emma, and Pride and Prejudice, are celebrated for their wit, realism, and biting critique of the social class structure of her time. Despite her relatively modest life, Austen’s novels have gained immense popularity, and she is considered one of the greatest novelists in the English language."
+ ], kind = INSERT}
+ {fields = [4, "The Great GatsbyThe Great Gatsby",
+ "The Great Gatsby is a novel about the American Dream and the disillusionment that can come with it. Set in the 1920s, the story follows Nick Carraway as he becomes entangled in the lives of his mysterious neighbor, Jay Gatsby, and the wealthy elite of Long Island. Gatsby's obsession with the beautiful Daisy Buchanan drives the narrative, exploring themes of wealth, love, and the decay of the American Dream.",
+ "F. Scott Fitzgerald (1896–1940) was an American novelist and short story writer, widely regarded as one of the greatest American writers of the 20th century. Born in St. Paul, Minnesota, Fitzgerald is best known for his novel The Great Gatsby, which is often considered the quintessential work of the Jazz Age. His works often explore themes of youth, wealth, and the American Dream, reflecting the turbulence and excesses of the 1920s."
+ ], kind = INSERT}
+ {fields = [5, "Moby-Dick",
+ "Moby-Dick is an epic tale of obsession and revenge. The novel follows the journey of Captain Ahab, who is on a relentless quest to kill the white whale, Moby Dick, that once maimed him. Narrated by Ishmael, a sailor aboard Ahab’s ship, the story delves into themes of fate, humanity, and the struggle between man and nature. The novel is also rich with symbolism and philosophical musings.",
+ "Herman Melville (1819–1891) was an American novelist, short story writer, and poet of the American Renaissance period. Born in New York City, Melville gained initial fame with novels such as Typee and Omoo, but it was Moby-Dick, published in 1851, that would later be recognized as his masterpiece. Melville’s work is known for its complexity, symbolism, and exploration of themes such as man’s place in the universe, the nature of evil, and the quest for meaning. Despite facing finan [...]
+ ], kind = INSERT}
+ ]
+ result_table_name = "fake"
+ }
+}
+
+transform {
+ Embedding {
+ source_table_name = "fake"
+ model_provider = CUSTOM
+ model = text-embedding-3-small
+ api_key = xxxxxxxx
+ api_path = "http://mockserver:1080/v1/doubao/embedding"
+ single_vectorized_input_number = 2
+ vectorization_fields {
+ book_intro_vector = book_intro
+ author_biography_vector = author_biography
+ }
+ custom_config={
+ custom_response_parse = "$.data[*].embedding"
+ custom_request_headers = {
+ "Content-Type"= "application/json"
+ "Authorization"= "Bearer xxxxxxx
+ }
+ custom_request_body ={
+ modelx = "${model}"
+ inputx = ["${input}"]
+ }
+ }
+ result_table_name = "embedding_output_3"
+ }
+}
+
+sink {
+ Assert {
+ source_table_name = "embedding_output_1"
+ rules =
+ {
+ field_rules = [
+ {
+ field_name = book_id
+ field_type = int
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_name
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ }
+ ]
+ }
+ }
+}
+
+```
diff --git a/docs/en/transform-v2/llm.md b/docs/en/transform-v2/llm.md
index d03b8226f0..b2142c4297 100644
--- a/docs/en/transform-v2/llm.md
+++ b/docs/en/transform-v2/llm.md
@@ -10,14 +10,14 @@ more.
## Options
-| name | type | required | default value |
-|------------------|--------|----------|--------------------------------------------|
-| model_provider | enum | yes | |
-| output_data_type | enum | no | String |
-| prompt | string | yes | |
-| model | string | yes | |
-| api_key | string | yes | |
-| openai.api_path | string | no | https://api.openai.com/v1/chat/completions |
+| name | type | required | default value |
+|------------------|--------|----------|---------------|
+| model_provider | enum | yes | |
+| output_data_type | enum | no | String |
+| prompt | string | yes | |
+| model | string | yes | |
+| api_key | string | yes | |
+| api_path | string | no | |
### model_provider
@@ -36,7 +36,7 @@ The prompt to send to the LLM. This parameter defines how LLM will process and r
The data read from source is a table like this:
-| name | age |
+| name | age |
|---------------|-----|
| Jia Fan | 20 |
| Hailin Wang | 20 |
@@ -51,7 +51,7 @@ Determine whether someone is Chinese or American by their name
The result will be:
-| name | age | llm_output |
+| name | age | llm_output |
|---------------|-----|------------|
| Jia Fan | 20 | Chinese |
| Hailin Wang | 20 | Chinese |
@@ -61,16 +61,18 @@ The result will be:
### model
The model to use. Different model providers have different models. For example, the OpenAI model can be `gpt-4o-mini`.
-If you use OpenAI model, please refer https://platform.openai.com/docs/models/model-endpoint-compatibility of `/v1/chat/completions` endpoint.
+If you use OpenAI model, please refer https://platform.openai.com/docs/models/model-endpoint-compatibility
+of `/v1/chat/completions` endpoint.
### api_key
The API key to use for the model provider.
If you use OpenAI model, please refer https://platform.openai.com/docs/api-reference/api-keys of how to get the API key.
-### openai.api_path
+### api_path
-The API path to use for the OpenAI model provider. In most cases, you do not need to change this configuration. If you are using an API agent's service, you may need to configure it to the agent's API address.
+The API path to use for the model provider. In most cases, you do not need to change this configuration. If you
+are using an API agent's service, you may need to configure it to the agent's API address.
### common options [string]
diff --git a/docs/zh/transform-v2/embedding.md b/docs/zh/transform-v2/embedding.md
new file mode 100644
index 0000000000..545641f47f
--- /dev/null
+++ b/docs/zh/transform-v2/embedding.md
@@ -0,0 +1,382 @@
+# Embedding
+
+> Embedding Transform Plugin
+
+## 描述
+
+`Embedding` 转换插件利用 embedding 模型将文本数据转换为向量化表示。此转换可以应用于各种字段。该插件支持多种模型提供商,并且可以与不同的API集成。
+
+## 配置选项
+
+| 名称 | 类型 | 是否必填 | 默认值 | 描述 |
+|--------------------------------|--------|------|-----|------------------------------------------------------------------|
+| model_provider | enum | 是 | - | embedding模型的提供商。可选项包括 `QIANFAN`、`OPENAI` 等。 |
+| api_key | string | 是 | - | 用于验证embedding服务的API密钥。 |
+| secret_key | string | 是 | - | 用于额外验证的密钥。一些提供商可能需要此密钥进行安全的API请求。 |
+| single_vectorized_input_number | int | 否 | 1 | 单次请求向量化的输入数量。默认值为1。 |
+| vectorization_fields | map | 是 | - | 输入字段和相应的输出向量字段之间的映射。 |
+| model | string | 是 | - | 要使用的具体embedding模型。例如,如果提供商为OPENAI,可以指定 `text-embedding-3-small`。 |
+| api_path | string | 否 | - | embedding服务的API。通常由模型提供商提供。 |
+| oauth_path | string | 否 | - | oauth 服务的 API 。 |
+| custom_config | map | 否 | | 模型的自定义配置。 |
+| custom_response_parse | string | 否 | | 使用 JsonPath 解析模型响应的方式。示例:`$.choices[*].message.content`。 |
+| custom_request_headers | map | 否 | | 发送到模型的请求的自定义头信息。 |
+| custom_request_body | map | 否 | | 请求体的自定义配置。支持占位符如 `${model}`、`${input}`。 |
+
+### embedding_model_provider
+
+用于生成 embedding 的模型提供商。常见选项包括 `DOUBAO`、`QIANFAN`、`OPENAI` 等,同时可选择 `CUSTOM` 实现自定义 embedding
+模型的请求以及获取。
+
+### api_key
+
+用于验证 embedding 服务请求的API密钥。通常由模型提供商在你注册他们的服务时提供。
+
+### secret_key
+
+用于额外验证的密钥。一些提供商可能要求此密钥以确保API请求的安全性。
+
+### single_vectorized_input_number
+
+指定单次请求向量化的输入数量。默认值为1。根据处理能力和模型提供商的API限制进行调整。
+
+### vectorization_fields
+
+输入字段和相应的输出向量字段之间的映射。这使得插件可以理解要向量化的文本字段以及如何存储生成的向量。
+
+```hocon
+vectorization_fields {
+ book_intro_vector = book_intro
+ author_biography_vector = author_biography
+}
+```
+
+### model
+
+要使用的具体 embedding 模型。这取决于`embedding_model_provider`。例如,如果使用 OPENAI ,可以指定 `text-embedding-3-small`。
+
+### api_path
+
+用于向 embedding 服务发送请求的API。根据提供商和所用模型的不同可能有所变化。通常由模型提供商提供。
+
+### oauth_path
+
+用于向oauth服务发送请求的API,获取对应的认证信息。根据提供商和所用模型的不同可能有所变化。通常由模型提供商提供。
+
+### custom_config
+
+`custom_config` 选项允许您为模型提供额外的自定义配置。这是一个映射,您可以在其中定义特定模型可能需要的各种设置。
+
+### custom_response_parse
+
+`custom_response_parse` 选项允许您指定如何解析模型的响应。您可以使用 JsonPath
+从响应中提取所需的特定数据。例如,使用 `$.data[*].embedding` 提取如下json中的 `embedding` 字段
+值,获取 `List` 嵌套 `List` 的结果。JsonPath
+的使用请参考 [JsonPath 快速入门](https://github.com/json-path/JsonPath?tab=readme-ov-file#getting-started)
+
+```json
+{
+ "object": "list",
+ "data": [
+ {
+ "object": "embedding",
+ "index": 0,
+ "embedding": [
+ -0.006929283495992422,
+ -0.005336422007530928,
+ -0.00004547132266452536,
+ -0.024047505110502243
+ ]
+ }
+ ],
+ "model": "text-embedding-3-small",
+ "usage": {
+ "prompt_tokens": 5,
+ "total_tokens": 5
+ }
+}
+```
+
+### custom_request_headers
+
+`custom_request_headers` 选项允许您定义应包含在发送到模型 API 的请求中的自定义头信息。如果 API
+需要标准头信息之外的额外头信息,例如授权令牌、内容类型等,这个选项会非常有用。
+
+### custom_request_body
+
+`custom_request_body` 选项支持占位符:
+
+- `${model}`:用于模型名称的占位符。
+- `${input}`:用于确定输入值的占位符,同时根据 body value 的类型定义请求体请求类型。例如:`["${input}"]` -> ["input"] (
+ list)。
+
+### common options
+
+转换插件的常见参数, 请参考 [Transform Plugin](common-options.md) 了解详情
+
+## 示例配置
+
+```hocon
+env {
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ row.num = 5
+ schema = {
+ fields {
+ book_id = "int"
+ book_name = "string"
+ book_intro = "string"
+ author_biography = "string"
+ }
+ }
+ rows = [
+ {fields = [1, "To Kill a Mockingbird",
+ "Set in the American South during the 1930s, To Kill a Mockingbird tells the story of young Scout Finch and her brother, Jem, who are growing up in a world of racial inequality and injustice. Their father, Atticus Finch, is a lawyer who defends a black man falsely accused of raping a white woman, teaching his children valuable lessons about morality, courage, and empathy.",
+ "Harper Lee (1926–2016) was an American novelist best known for To Kill a Mockingbird, which won the Pulitzer Prize in 1961. Lee was born in Monroeville, Alabama, and the town served as inspiration for the fictional Maycomb in her novel. Despite the success of her book, Lee remained a private person and published only one other novel, Go Set a Watchman, which was written before To Kill a Mockingbird but released in 2015 as a sequel."
+ ], kind = INSERT}
+ {fields = [2, "1984",
+ "1984 is a dystopian novel set in a totalitarian society governed by Big Brother. The story follows Winston Smith, a man who works for the Party rewriting history. Winston begins to question the Party’s control and seeks truth and freedom in a society where individuality is crushed. The novel explores themes of surveillance, propaganda, and the loss of personal autonomy.",
+ "George Orwell (1903–1950) was the pen name of Eric Arthur Blair, an English novelist, essayist, journalist, and critic. Orwell is best known for his works 1984 and Animal Farm, both of which are critiques of totalitarian regimes. His writing is characterized by lucid prose, awareness of social injustice, opposition to totalitarianism, and support of democratic socialism. Orwell’s work remains influential, and his ideas have shaped contemporary discussions on politics and society."
+ ], kind = INSERT}
+ {fields = [3, "Pride and Prejudice",
+ "Pride and Prejudice is a romantic novel that explores the complex relationships between different social classes in early 19th century England. The story centers on Elizabeth Bennet, a young woman with strong opinions, and Mr. Darcy, a wealthy but reserved gentleman. The novel deals with themes of love, marriage, and societal expectations, offering keen insights into human behavior.",
+ "Jane Austen (1775–1817) was an English novelist known for her sharp social commentary and keen observations of the British landed gentry. Her works, including Sense and Sensibility, Emma, and Pride and Prejudice, are celebrated for their wit, realism, and biting critique of the social class structure of her time. Despite her relatively modest life, Austen’s novels have gained immense popularity, and she is considered one of the greatest novelists in the English language."
+ ], kind = INSERT}
+ {fields = [4, "The Great GatsbyThe Great Gatsby",
+ "The Great Gatsby is a novel about the American Dream and the disillusionment that can come with it. Set in the 1920s, the story follows Nick Carraway as he becomes entangled in the lives of his mysterious neighbor, Jay Gatsby, and the wealthy elite of Long Island. Gatsby's obsession with the beautiful Daisy Buchanan drives the narrative, exploring themes of wealth, love, and the decay of the American Dream.",
+ "F. Scott Fitzgerald (1896–1940) was an American novelist and short story writer, widely regarded as one of the greatest American writers of the 20th century. Born in St. Paul, Minnesota, Fitzgerald is best known for his novel The Great Gatsby, which is often considered the quintessential work of the Jazz Age. His works often explore themes of youth, wealth, and the American Dream, reflecting the turbulence and excesses of the 1920s."
+ ], kind = INSERT}
+ {fields = [5, "Moby-Dick",
+ "Moby-Dick is an epic tale of obsession and revenge. The novel follows the journey of Captain Ahab, who is on a relentless quest to kill the white whale, Moby Dick, that once maimed him. Narrated by Ishmael, a sailor aboard Ahab’s ship, the story delves into themes of fate, humanity, and the struggle between man and nature. The novel is also rich with symbolism and philosophical musings.",
+ "Herman Melville (1819–1891) was an American novelist, short story writer, and poet of the American Renaissance period. Born in New York City, Melville gained initial fame with novels such as Typee and Omoo, but it was Moby-Dick, published in 1851, that would later be recognized as his masterpiece. Melville’s work is known for its complexity, symbolism, and exploration of themes such as man’s place in the universe, the nature of evil, and the quest for meaning. Despite facing finan [...]
+ ], kind = INSERT}
+ ]
+ result_table_name = "fake"
+ }
+}
+
+transform {
+ Embedding {
+ source_table_name = "fake"
+ embedding_model_provider = QIANFAN
+ model = bge_large_en
+ api_key = xxxxxxxxxx
+ secret_key = xxxxxxxxxx
+ api_path = xxxxxxxxxx
+ vectorization_fields {
+ book_intro_vector = book_intro
+ author_biography_vector = author_biography
+ }
+ result_table_name = "embedding_output"
+ }
+}
+
+sink {
+ Assert {
+ source_table_name = "embedding_output"
+
+
+ rules =
+ {
+ field_rules = [
+ {
+ field_name = book_id
+ field_type = int
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_name
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ }
+ ]
+ }
+ }
+}
+```
+
+### Customize the embedding model
+
+```hocon
+
+env {
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ row.num = 5
+ schema = {
+ fields {
+ book_id = "int"
+ book_name = "string"
+ book_intro = "string"
+ author_biography = "string"
+ }
+ }
+ rows = [
+ {fields = [1, "To Kill a Mockingbird",
+ "Set in the American South during the 1930s, To Kill a Mockingbird tells the story of young Scout Finch and her brother, Jem, who are growing up in a world of racial inequality and injustice. Their father, Atticus Finch, is a lawyer who defends a black man falsely accused of raping a white woman, teaching his children valuable lessons about morality, courage, and empathy.",
+ "Harper Lee (1926–2016) was an American novelist best known for To Kill a Mockingbird, which won the Pulitzer Prize in 1961. Lee was born in Monroeville, Alabama, and the town served as inspiration for the fictional Maycomb in her novel. Despite the success of her book, Lee remained a private person and published only one other novel, Go Set a Watchman, which was written before To Kill a Mockingbird but released in 2015 as a sequel."
+ ], kind = INSERT}
+ {fields = [2, "1984",
+ "1984 is a dystopian novel set in a totalitarian society governed by Big Brother. The story follows Winston Smith, a man who works for the Party rewriting history. Winston begins to question the Party’s control and seeks truth and freedom in a society where individuality is crushed. The novel explores themes of surveillance, propaganda, and the loss of personal autonomy.",
+ "George Orwell (1903–1950) was the pen name of Eric Arthur Blair, an English novelist, essayist, journalist, and critic. Orwell is best known for his works 1984 and Animal Farm, both of which are critiques of totalitarian regimes. His writing is characterized by lucid prose, awareness of social injustice, opposition to totalitarianism, and support of democratic socialism. Orwell’s work remains influential, and his ideas have shaped contemporary discussions on politics and society."
+ ], kind = INSERT}
+ {fields = [3, "Pride and Prejudice",
+ "Pride and Prejudice is a romantic novel that explores the complex relationships between different social classes in early 19th century England. The story centers on Elizabeth Bennet, a young woman with strong opinions, and Mr. Darcy, a wealthy but reserved gentleman. The novel deals with themes of love, marriage, and societal expectations, offering keen insights into human behavior.",
+ "Jane Austen (1775–1817) was an English novelist known for her sharp social commentary and keen observations of the British landed gentry. Her works, including Sense and Sensibility, Emma, and Pride and Prejudice, are celebrated for their wit, realism, and biting critique of the social class structure of her time. Despite her relatively modest life, Austen’s novels have gained immense popularity, and she is considered one of the greatest novelists in the English language."
+ ], kind = INSERT}
+ {fields = [4, "The Great GatsbyThe Great Gatsby",
+ "The Great Gatsby is a novel about the American Dream and the disillusionment that can come with it. Set in the 1920s, the story follows Nick Carraway as he becomes entangled in the lives of his mysterious neighbor, Jay Gatsby, and the wealthy elite of Long Island. Gatsby's obsession with the beautiful Daisy Buchanan drives the narrative, exploring themes of wealth, love, and the decay of the American Dream.",
+ "F. Scott Fitzgerald (1896–1940) was an American novelist and short story writer, widely regarded as one of the greatest American writers of the 20th century. Born in St. Paul, Minnesota, Fitzgerald is best known for his novel The Great Gatsby, which is often considered the quintessential work of the Jazz Age. His works often explore themes of youth, wealth, and the American Dream, reflecting the turbulence and excesses of the 1920s."
+ ], kind = INSERT}
+ {fields = [5, "Moby-Dick",
+ "Moby-Dick is an epic tale of obsession and revenge. The novel follows the journey of Captain Ahab, who is on a relentless quest to kill the white whale, Moby Dick, that once maimed him. Narrated by Ishmael, a sailor aboard Ahab’s ship, the story delves into themes of fate, humanity, and the struggle between man and nature. The novel is also rich with symbolism and philosophical musings.",
+ "Herman Melville (1819–1891) was an American novelist, short story writer, and poet of the American Renaissance period. Born in New York City, Melville gained initial fame with novels such as Typee and Omoo, but it was Moby-Dick, published in 1851, that would later be recognized as his masterpiece. Melville’s work is known for its complexity, symbolism, and exploration of themes such as man’s place in the universe, the nature of evil, and the quest for meaning. Despite facing finan [...]
+ ], kind = INSERT}
+ ]
+ result_table_name = "fake"
+ }
+}
+
+transform {
+ Embedding {
+ source_table_name = "fake"
+ model_provider = CUSTOM
+ model = text-embedding-3-small
+ api_key = xxxxxxxx
+ api_path = "http://mockserver:1080/v1/doubao/embedding"
+ single_vectorized_input_number = 2
+ vectorization_fields {
+ book_intro_vector = book_intro
+ author_biography_vector = author_biography
+ }
+ custom_config={
+ custom_response_parse = "$.data[*].embedding"
+ custom_request_headers = {
+ "Content-Type"= "application/json"
+ "Authorization"= "Bearer xxxxxxx
+ }
+ custom_request_body ={
+ modelx = "${model}"
+ inputx = ["${input}"]
+ }
+ }
+ result_table_name = "embedding_output_3"
+ }
+}
+
+sink {
+ Assert {
+ source_table_name = "embedding_output_1"
+ rules =
+ {
+ field_rules = [
+ {
+ field_name = book_id
+ field_type = int
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_name
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ }
+ ]
+ }
+ }
+}
+
+```
\ No newline at end of file
diff --git a/docs/zh/transform-v2/llm.md b/docs/zh/transform-v2/llm.md
index acd3245b8e..3a6904b667 100644
--- a/docs/zh/transform-v2/llm.md
+++ b/docs/zh/transform-v2/llm.md
@@ -8,14 +8,14 @@
## 属性
-| 名称 | 类型 | 是否必须 | 默认值 |
-|------------------|--------|------|--------------------------------------------|
-| model_provider | enum | yes | |
-| output_data_type | enum | no | String |
-| prompt | string | yes | |
-| model | string | yes | |
-| api_key | string | yes | |
-| openai.api_path | string | no | https://api.openai.com/v1/chat/completions |
+| 名称 | 类型 | 是否必须 | 默认值 |
+|------------------|--------|------|--------|
+| model_provider | enum | yes | |
+| output_data_type | enum | no | String |
+| prompt | string | yes | |
+| model | string | yes | |
+| api_key | string | yes | |
+| api_path | string | no | |
### model_provider
@@ -34,7 +34,7 @@ STRING,INT,BIGINT,DOUBLE,BOOLEAN.
从源读取的数据是这样的表格:
-| name | age |
+| name | age |
|---------------|-----|
| Jia Fan | 20 |
| Hailin Wang | 20 |
@@ -49,7 +49,7 @@ Determine whether someone is Chinese or American by their name
这将返回:
-| name | age | llm_output |
+| name | age | llm_output |
|---------------|-----|------------|
| Jia Fan | 20 | Chinese |
| Hailin Wang | 20 | Chinese |
@@ -66,9 +66,9 @@ Determine whether someone is Chinese or American by their name
用于模型提供者的 API 密钥。
如果使用 OpenAI 模型,请参考 https://platform.openai.com/docs/api-reference/api-keys 文档的如何获取 API 密钥。
-### openai.api_path
+### api_path
-用于 OpenAI 模型提供者的 API 路径。在大多数情况下,您不需要更改此配置。如果使用 API 代理的服务,您可能需要将其配置为代理的 API 地址。
+用于模型提供者的 API 路径。在大多数情况下,您不需要更改此配置。如果使用 API 代理的服务,您可能需要将其配置为代理的 API 地址。
### common options [string]
diff --git a/plugin-mapping.properties b/plugin-mapping.properties
index 1ddedd5ea8..630d56654d 100644
--- a/plugin-mapping.properties
+++ b/plugin-mapping.properties
@@ -147,4 +147,5 @@ seatunnel.transform.Split = seatunnel-transforms-v2
seatunnel.transform.Copy = seatunnel-transforms-v2
seatunnel.transform.DynamicCompile = seatunnel-transforms-v2
seatunnel.transform.LLM = seatunnel-transforms-v2
+seatunnel.transform.Embedding = seatunnel-transforms-v2
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/type/SeaTunnelRow.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/type/SeaTunnelRow.java
index 801f037b18..10a5b33a93 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/type/SeaTunnelRow.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/table/type/SeaTunnelRow.java
@@ -295,6 +295,9 @@ public final class SeaTunnelRow implements Serializable {
size += getBytesForValue(entry.getKey()) + getBytesForValue(entry.getValue());
}
return size;
+ case "HeapByteBuffer":
+ case "ByteBuffer":
+ return ((ByteBuffer) v).capacity();
case "SeaTunnelRow":
int rowSize = 0;
SeaTunnelRow row = (SeaTunnelRow) v;
diff --git a/seatunnel-connectors-v2/connector-assert/src/main/java/org/apache/seatunnel/connectors/seatunnel/assertion/excecutor/AssertExecutor.java b/seatunnel-connectors-v2/connector-assert/src/main/java/org/apache/seatunnel/connectors/seatunnel/assertion/excecutor/AssertExecutor.java
index d60fb46c8c..f6908b989d 100644
--- a/seatunnel-connectors-v2/connector-assert/src/main/java/org/apache/seatunnel/connectors/seatunnel/assertion/excecutor/AssertExecutor.java
+++ b/seatunnel-connectors-v2/connector-assert/src/main/java/org/apache/seatunnel/connectors/seatunnel/assertion/excecutor/AssertExecutor.java
@@ -36,6 +36,7 @@ import com.google.common.collect.Lists;
import java.io.IOException;
import java.math.BigDecimal;
+import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -307,6 +308,13 @@ public class AssertExecutor {
return checkDecimalType(value, fieldType);
}
+ if (fieldType.getSqlType() == SqlType.FLOAT_VECTOR
+ || fieldType.getSqlType() == SqlType.FLOAT16_VECTOR
+ || fieldType.getSqlType() == SqlType.BFLOAT16_VECTOR
+ || fieldType.getSqlType() == SqlType.BINARY_VECTOR) {
+ return value instanceof ByteBuffer;
+ }
+
return value.getClass().equals(fieldType.getTypeClass());
}
diff --git a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/java/org/apache/seatunnel/e2e/transform/TestLLMIT.java b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/java/org/apache/seatunnel/e2e/transform/TestEmbeddingIT.java
similarity index 80%
copy from seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/java/org/apache/seatunnel/e2e/transform/TestLLMIT.java
copy to seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/java/org/apache/seatunnel/e2e/transform/TestEmbeddingIT.java
index 6f17c5a94f..ae1df24eec 100644
--- a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/java/org/apache/seatunnel/e2e/transform/TestLLMIT.java
+++ b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/java/org/apache/seatunnel/e2e/transform/TestEmbeddingIT.java
@@ -18,7 +18,9 @@
package org.apache.seatunnel.e2e.transform;
import org.apache.seatunnel.e2e.common.TestResource;
+import org.apache.seatunnel.e2e.common.container.EngineType;
import org.apache.seatunnel.e2e.common.container.TestContainer;
+import org.apache.seatunnel.e2e.common.junit.DisabledOnContainer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
@@ -39,7 +41,11 @@ import java.net.URL;
import java.util.Optional;
import java.util.stream.Stream;
-public class TestLLMIT extends TestSuiteBase implements TestResource {
+@DisabledOnContainer(
+ value = {},
+ type = {EngineType.SPARK, EngineType.FLINK},
+ disabledReason = "Currently SPARK and FLINK not support adapt")
+public class TestEmbeddingIT extends TestSuiteBase implements TestResource {
private static final String TMP_DIR = "/tmp";
private GenericContainer<?> mockserverContainer;
private static final String IMAGE = "mockserver/mockserver:5.14.0";
@@ -48,7 +54,7 @@ public class TestLLMIT extends TestSuiteBase implements TestResource {
@Override
public void startUp() {
Optional<URL> resource =
- Optional.ofNullable(TestLLMIT.class.getResource("/mockserver-config.json"));
+ Optional.ofNullable(TestLLMIT.class.getResource("/mock-embedding.json"));
this.mockserverContainer =
new GenericContainer<>(DockerImageName.parse(IMAGE))
.withNetwork(NETWORK)
@@ -63,10 +69,10 @@ public class TestLLMIT extends TestSuiteBase implements TestResource {
"Can not get config file of mockServer"))
.getPath())
.getAbsolutePath()),
- TMP_DIR + "/mockserver-config.json")
+ TMP_DIR + "/mock-embedding.json")
.withEnv(
"MOCKSERVER_INITIALIZATION_JSON_PATH",
- TMP_DIR + "/mockserver-config.json")
+ TMP_DIR + "/mock-embedding.json")
.withEnv("MOCKSERVER_LOG_LEVEL", "WARN")
.withLogConsumer(new Slf4jLogConsumer(DockerLoggerFactory.getLogger(IMAGE)))
.waitingFor(new HttpWaitStrategy().forPath("/").forStatusCode(404));
@@ -82,9 +88,15 @@ public class TestLLMIT extends TestSuiteBase implements TestResource {
}
@TestTemplate
- public void testLLMWithOpenAI(TestContainer container)
+ public void testEmbedding(TestContainer container) throws IOException, InterruptedException {
+ Container.ExecResult execResult = container.executeJob("/embedding_transform.conf");
+ Assertions.assertEquals(0, execResult.getExitCode());
+ }
+
+ @TestTemplate
+ public void testEmbeddingWithCustomModel(TestContainer container)
throws IOException, InterruptedException {
- Container.ExecResult execResult = container.executeJob("/llm_openai_transform.conf");
+ Container.ExecResult execResult = container.executeJob("/embedding_transform_custom.conf");
Assertions.assertEquals(0, execResult.getExitCode());
}
}
diff --git a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/java/org/apache/seatunnel/e2e/transform/TestLLMIT.java b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/java/org/apache/seatunnel/e2e/transform/TestLLMIT.java
index 6f17c5a94f..5a4fa640e9 100644
--- a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/java/org/apache/seatunnel/e2e/transform/TestLLMIT.java
+++ b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/java/org/apache/seatunnel/e2e/transform/TestLLMIT.java
@@ -87,4 +87,11 @@ public class TestLLMIT extends TestSuiteBase implements TestResource {
Container.ExecResult execResult = container.executeJob("/llm_openai_transform.conf");
Assertions.assertEquals(0, execResult.getExitCode());
}
+
+ @TestTemplate
+ public void testLLMWithCustomModel(TestContainer container)
+ throws IOException, InterruptedException {
+ Container.ExecResult execResult = container.executeJob("/llm_transform_custom.conf");
+ Assertions.assertEquals(0, execResult.getExitCode());
+ }
}
diff --git a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/embedding_transform.conf b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/embedding_transform.conf
new file mode 100644
index 0000000000..aa0288a705
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/embedding_transform.conf
@@ -0,0 +1,295 @@
+#
+# 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.
+#
+######
+###### This config file is a demonstration of streaming processing in seatunnel config
+######
+
+env {
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ row.num = 5
+ schema = {
+ fields {
+ book_id = "int"
+ book_name = "string"
+ book_intro = "string"
+ author_biography = "string"
+ }
+ }
+ rows = [
+ {fields = [1, "To Kill a Mockingbird",
+ "Set in the American South during the 1930s, To Kill a Mockingbird tells the story of young Scout Finch and her brother, Jem, who are growing up in a world of racial inequality and injustice. Their father, Atticus Finch, is a lawyer who defends a black man falsely accused of raping a white woman, teaching his children valuable lessons about morality, courage, and empathy.",
+ "Harper Lee (1926–2016) was an American novelist best known for To Kill a Mockingbird, which won the Pulitzer Prize in 1961. Lee was born in Monroeville, Alabama, and the town served as inspiration for the fictional Maycomb in her novel. Despite the success of her book, Lee remained a private person and published only one other novel, Go Set a Watchman, which was written before To Kill a Mockingbird but released in 2015 as a sequel."
+ ], kind = INSERT}
+ {fields = [2, "1984",
+ "1984 is a dystopian novel set in a totalitarian society governed by Big Brother. The story follows Winston Smith, a man who works for the Party rewriting history. Winston begins to question the Party’s control and seeks truth and freedom in a society where individuality is crushed. The novel explores themes of surveillance, propaganda, and the loss of personal autonomy.",
+ "George Orwell (1903–1950) was the pen name of Eric Arthur Blair, an English novelist, essayist, journalist, and critic. Orwell is best known for his works 1984 and Animal Farm, both of which are critiques of totalitarian regimes. His writing is characterized by lucid prose, awareness of social injustice, opposition to totalitarianism, and support of democratic socialism. Orwell’s work remains influential, and his ideas have shaped contemporary discussions on politics and society."
+ ], kind = INSERT}
+ {fields = [3, "Pride and Prejudice",
+ "Pride and Prejudice is a romantic novel that explores the complex relationships between different social classes in early 19th century England. The story centers on Elizabeth Bennet, a young woman with strong opinions, and Mr. Darcy, a wealthy but reserved gentleman. The novel deals with themes of love, marriage, and societal expectations, offering keen insights into human behavior.",
+ "Jane Austen (1775–1817) was an English novelist known for her sharp social commentary and keen observations of the British landed gentry. Her works, including Sense and Sensibility, Emma, and Pride and Prejudice, are celebrated for their wit, realism, and biting critique of the social class structure of her time. Despite her relatively modest life, Austen’s novels have gained immense popularity, and she is considered one of the greatest novelists in the English language."
+ ], kind = INSERT}
+ {fields = [4, "The Great GatsbyThe Great Gatsby",
+ "The Great Gatsby is a novel about the American Dream and the disillusionment that can come with it. Set in the 1920s, the story follows Nick Carraway as he becomes entangled in the lives of his mysterious neighbor, Jay Gatsby, and the wealthy elite of Long Island. Gatsby's obsession with the beautiful Daisy Buchanan drives the narrative, exploring themes of wealth, love, and the decay of the American Dream.",
+ "F. Scott Fitzgerald (1896–1940) was an American novelist and short story writer, widely regarded as one of the greatest American writers of the 20th century. Born in St. Paul, Minnesota, Fitzgerald is best known for his novel The Great Gatsby, which is often considered the quintessential work of the Jazz Age. His works often explore themes of youth, wealth, and the American Dream, reflecting the turbulence and excesses of the 1920s."
+ ], kind = INSERT}
+ {fields = [5, "Moby-Dick",
+ "Moby-Dick is an epic tale of obsession and revenge. The novel follows the journey of Captain Ahab, who is on a relentless quest to kill the white whale, Moby Dick, that once maimed him. Narrated by Ishmael, a sailor aboard Ahab’s ship, the story delves into themes of fate, humanity, and the struggle between man and nature. The novel is also rich with symbolism and philosophical musings.",
+ "Herman Melville (1819–1891) was an American novelist, short story writer, and poet of the American Renaissance period. Born in New York City, Melville gained initial fame with novels such as Typee and Omoo, but it was Moby-Dick, published in 1851, that would later be recognized as his masterpiece. Melville’s work is known for its complexity, symbolism, and exploration of themes such as man’s place in the universe, the nature of evil, and the quest for meaning. Despite facing finan [...]
+ ], kind = INSERT}
+ ]
+ result_table_name = "fake"
+ }
+}
+
+transform {
+ Embedding {
+ source_table_name = "fake"
+ model_provider = QIANFAN
+ model = bge_large_en
+ api_key = xxxxxxxx
+ secret_key = xxxxxxxx
+ api_path = "http://mockserver:1080/v1/qianfan/embedding"
+ oauth_path = "http://mockserver:1080/v1/qianfan/token"
+ single_vectorized_input_number = 2
+ vectorization_fields {
+ book_intro_vector = book_intro
+ author_biography_vector = author_biography
+ }
+ result_table_name = "embedding_output_1"
+ }
+
+ Embedding {
+ source_table_name = "fake"
+ model_provider = DOUBAO
+ model = ep-20240830113341-wwwqd
+ api_key = xxxxxxxx
+ api_path = "http://mockserver:1080/v1/doubao/embedding"
+ single_vectorized_input_number = 2
+ vectorization_fields {
+ book_intro_vector = book_intro
+ author_biography_vector = author_biography
+ }
+ result_table_name = "embedding_output_2"
+ }
+
+
+ Embedding {
+ source_table_name = "fake"
+ model_provider = OPENAI
+ model = text-embedding-3-small
+ api_key = xxxxxxxx
+ api_path = "http://mockserver:1080/v1/openai/embedding"
+ vectorization_fields {
+ book_intro_vector = book_intro
+ author_biography_vector = author_biography
+ }
+ result_table_name = "embedding_output_3"
+ }
+}
+
+sink {
+ Assert {
+ source_table_name = "embedding_output_1"
+ rules =
+ {
+ field_rules = [
+ {
+ field_name = book_id
+ field_type = int
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_name
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ }
+ ]
+ }
+ }
+ Assert {
+ source_table_name = "embedding_output_2"
+ rules =
+ {
+ field_rules = [
+ {
+ field_name = book_id
+ field_type = int
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_name
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ }
+ ]
+ }
+ }
+ Assert {
+ source_table_name = "embedding_output_3"
+ rules =
+ {
+ field_rules = [
+ {
+ field_name = book_id
+ field_type = int
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_name
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/embedding_transform_custom.conf b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/embedding_transform_custom.conf
new file mode 100644
index 0000000000..4e9a30c4d9
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/embedding_transform_custom.conf
@@ -0,0 +1,152 @@
+#
+# 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.
+#
+######
+###### This config file is a demonstration of streaming processing in seatunnel config
+######
+
+env {
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ row.num = 5
+ schema = {
+ fields {
+ book_id = "int"
+ book_name = "string"
+ book_intro = "string"
+ author_biography = "string"
+ }
+ }
+ rows = [
+ {fields = [1, "To Kill a Mockingbird",
+ "Set in the American South during the 1930s, To Kill a Mockingbird tells the story of young Scout Finch and her brother, Jem, who are growing up in a world of racial inequality and injustice. Their father, Atticus Finch, is a lawyer who defends a black man falsely accused of raping a white woman, teaching his children valuable lessons about morality, courage, and empathy.",
+ "Harper Lee (1926–2016) was an American novelist best known for To Kill a Mockingbird, which won the Pulitzer Prize in 1961. Lee was born in Monroeville, Alabama, and the town served as inspiration for the fictional Maycomb in her novel. Despite the success of her book, Lee remained a private person and published only one other novel, Go Set a Watchman, which was written before To Kill a Mockingbird but released in 2015 as a sequel."
+ ], kind = INSERT}
+ {fields = [2, "1984",
+ "1984 is a dystopian novel set in a totalitarian society governed by Big Brother. The story follows Winston Smith, a man who works for the Party rewriting history. Winston begins to question the Party’s control and seeks truth and freedom in a society where individuality is crushed. The novel explores themes of surveillance, propaganda, and the loss of personal autonomy.",
+ "George Orwell (1903–1950) was the pen name of Eric Arthur Blair, an English novelist, essayist, journalist, and critic. Orwell is best known for his works 1984 and Animal Farm, both of which are critiques of totalitarian regimes. His writing is characterized by lucid prose, awareness of social injustice, opposition to totalitarianism, and support of democratic socialism. Orwell’s work remains influential, and his ideas have shaped contemporary discussions on politics and society."
+ ], kind = INSERT}
+ {fields = [3, "Pride and Prejudice",
+ "Pride and Prejudice is a romantic novel that explores the complex relationships between different social classes in early 19th century England. The story centers on Elizabeth Bennet, a young woman with strong opinions, and Mr. Darcy, a wealthy but reserved gentleman. The novel deals with themes of love, marriage, and societal expectations, offering keen insights into human behavior.",
+ "Jane Austen (1775–1817) was an English novelist known for her sharp social commentary and keen observations of the British landed gentry. Her works, including Sense and Sensibility, Emma, and Pride and Prejudice, are celebrated for their wit, realism, and biting critique of the social class structure of her time. Despite her relatively modest life, Austen’s novels have gained immense popularity, and she is considered one of the greatest novelists in the English language."
+ ], kind = INSERT}
+ {fields = [4, "The Great GatsbyThe Great Gatsby",
+ "The Great Gatsby is a novel about the American Dream and the disillusionment that can come with it. Set in the 1920s, the story follows Nick Carraway as he becomes entangled in the lives of his mysterious neighbor, Jay Gatsby, and the wealthy elite of Long Island. Gatsby's obsession with the beautiful Daisy Buchanan drives the narrative, exploring themes of wealth, love, and the decay of the American Dream.",
+ "F. Scott Fitzgerald (1896–1940) was an American novelist and short story writer, widely regarded as one of the greatest American writers of the 20th century. Born in St. Paul, Minnesota, Fitzgerald is best known for his novel The Great Gatsby, which is often considered the quintessential work of the Jazz Age. His works often explore themes of youth, wealth, and the American Dream, reflecting the turbulence and excesses of the 1920s."
+ ], kind = INSERT}
+ {fields = [5, "Moby-Dick",
+ "Moby-Dick is an epic tale of obsession and revenge. The novel follows the journey of Captain Ahab, who is on a relentless quest to kill the white whale, Moby Dick, that once maimed him. Narrated by Ishmael, a sailor aboard Ahab’s ship, the story delves into themes of fate, humanity, and the struggle between man and nature. The novel is also rich with symbolism and philosophical musings.",
+ "Herman Melville (1819–1891) was an American novelist, short story writer, and poet of the American Renaissance period. Born in New York City, Melville gained initial fame with novels such as Typee and Omoo, but it was Moby-Dick, published in 1851, that would later be recognized as his masterpiece. Melville’s work is known for its complexity, symbolism, and exploration of themes such as man’s place in the universe, the nature of evil, and the quest for meaning. Despite facing finan [...]
+ ], kind = INSERT}
+ ]
+ result_table_name = "fake"
+ }
+}
+
+transform {
+ Embedding {
+ source_table_name = "fake"
+ model_provider = CUSTOM
+ model = text-embedding-3-small
+ api_key = xxxxxxxx
+ api_path = "http://mockserver:1080/v1/custom/embedding"
+ single_vectorized_input_number = 2
+ vectorization_fields {
+ book_intro_vector = book_intro
+ author_biography_vector = author_biography
+ }
+ custom_config={
+ custom_response_parse = "$.data[*].embedding"
+ custom_request_headers = {
+ # refer to mockserver config
+ Authorization = "Bearer xxxxxxxx"
+ }
+ custom_request_body ={
+ modelx = "${model}"
+ inputx = ["${input}","${input}"]
+ }
+ }
+ result_table_name = "embedding_output_3"
+ }
+}
+
+sink {
+ Assert {
+ source_table_name = "embedding_output_1"
+ rules =
+ {
+ field_rules = [
+ {
+ field_name = book_id
+ field_type = int
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_name
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = book_intro_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ },
+ {
+ field_name = author_biography_vector
+ field_type = float_vector
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/llm_transform_custom.conf b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/llm_transform_custom.conf
new file mode 100644
index 0000000000..ac9e58addb
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/llm_transform_custom.conf
@@ -0,0 +1,91 @@
+#
+# 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.
+#
+######
+###### This config file is a demonstration of streaming processing in seatunnel config
+######
+
+env {
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ row.num = 5
+ schema = {
+ fields {
+ id = "int"
+ name = "string"
+ }
+ }
+ rows = [
+ {fields = [1, "Jia Fan"], kind = INSERT}
+ {fields = [2, "Hailin Wang"], kind = INSERT}
+ {fields = [3, "Tomas"], kind = INSERT}
+ {fields = [4, "Eric"], kind = INSERT}
+ {fields = [5, "Guangdong Liu"], kind = INSERT}
+ ]
+ result_table_name = "fake"
+ }
+}
+
+transform {
+ LLM {
+ source_table_name = "fake"
+ model_provider = CUSTOM
+ model = gpt-4o-mini
+ api_key = sk-xxx
+ prompt = "Determine whether someone is Chinese or American by their name"
+ openai.api_path = "http://mockserver:1080/v1/chat/completions"
+ custom_config={
+ custom_response_parse = "$.choices[*].message.content"
+ custom_request_headers = {
+ 111 = 222
+ }
+ custom_request_body ={
+ model = "${model}"
+ messages = [{
+ role = "system"
+ content = "${prompt}"
+ },{
+ role = "user"
+ content = "${input}"
+ }]
+ }
+ }
+ result_table_name = "llm_output"
+ }
+}
+
+sink {
+ Assert {
+ source_table_name = "llm_output"
+ rules =
+ {
+ field_rules = [
+ {
+ field_name = llm_output
+ field_type = string
+ field_value = [
+ {
+ rule_type = NOT_NULL
+ }
+ ]
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/mock-embedding.json b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/mock-embedding.json
new file mode 100644
index 0000000000..1688d3b2e2
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-1/src/test/resources/mock-embedding.json
@@ -0,0 +1,75 @@
+// https://www.mock-server.com/mock_server/getting_started.html#request_matchers
+
+[
+ {
+ "httpRequest": {
+ "method": "POST",
+ "path": "/v1/qianfan/embedding/.*",
+ "queryStringParameters": {
+ "access_token": ["^.*$"]
+ }
+ },
+ "httpResponse": {
+ "body":{"id":"as-7bd1tetvey","object":"embedding_list","created":1724948271,"data":[{"object":"embedding","embedding":[-0.00021059511345811188,-0.027767932042479515,-0.01854688860476017,0.032603006809949875,-0.00508118188008666,-0.0278035756200552,-0.009797265753149986,0.0006566192023456097,0.002196578774601221,0.03303470090031624,-0.0032474317122250795,0.0023599115666002035,0.045467741787433624,-0.009151561185717583,-0.016853950917720795,0.006868097465485334,0.007051482331007719,- [...]
+ "headers": {
+ "Content-Type": "application/json"
+ }
+ }
+ },
+ {
+ "httpRequest": {
+ "method": "GET",
+ "path": "/v1/qianfan/token/*"
+ },
+ "httpResponse": {
+ "body": {"refresh_token":"25.739889c11bd3da5314feb915f7a2fbb9.315360000.2040272418.282335-111798018","expires_in":2592000,"session_key":"9mzdDAf85Y5boZ09O03b02PJ4A8E3TsMKj7vdOtV37xs\/jC6CN9MpEIvHlgjfpybyPOM7xNj86XLqFkQPLxBDxQ7LRXFm0c=","access_token":"24.7214280a4e58a8bc2550e8527fe93058.2592000.1727504418.282335-111798018","scope":"public ai_custom_qianfan_bloomz_7b_compressed ai_custom_yiyan_com ai_custom_yiyan_com_128k ai_custom_yiyan_com_adv_pro ai_custom_yiyan_com_ai_apaas ai_c [...]
+ "headers": {
+ "Content-Type": "application/json"
+ }
+ }
+ },
+ {
+ "httpRequest": {
+ "method": "POST",
+ "path": "/v1/doubao/embedding"
+ },
+ "httpResponse": {
+ "body": {"created":1725001256,"id":"02172500125677376580aba8475a41c550bbf05104842f0405ef5","data":[{"embedding":[-1.625,0.07958984375,-1.5703125,-3.03125,-1.4609375,3.46875,-0.73046875,-2.578125,-0.66796875,1.71875,0.361328125,2,5.125,2.25,4.6875,1.4921875,-0.77734375,-0.466796875,0.0439453125,-2.46875,3.59375,4.96875,2.34375,-5.34375,0.11083984375,-5.875,3.0625,4.09375,3.4375,0.2265625,9,-1.9296875,2.25,0.765625,3.671875,-2.484375,-1.171875,-1.6171875,4.1875,2.390625,-6.90625,0.36 [...]
+ "headers": {
+ "Content-Type": "application/json"
+ }
+ }
+ },
+ {
+ "httpRequest": {
+ "method": "POST",
+ "path": "/v1/openai/embedding"
+ },
+ "httpResponse": {
+ "body": {"object":"list","data":[{"object":"embedding","index":0,"embedding":[-0.006929283495992422,-0.005336422007530928,-4.547132266452536e-05,-0.024047505110502243]}],"model":"text-embedding-3-small","usage":{"prompt_tokens":5,"total_tokens":5}},
+ "headers": {
+ "Content-Type": "application/json"
+ }
+ }
+ },
+ {
+ "httpRequest": {
+ "method": "POST",
+ "path": "/v1/custom/embedding",
+ "headers": {
+ "Authorization": [
+ "Bearer xxxxxxxx"
+ ]
+ }
+ },
+ "httpResponse": {
+ "body": {"created":1725001256,"id":"02172500125677376580aba8475a41c550bbf05104842f0405ef5","data":[{"embedding":[-1.625,0.07958984375,-1.5703125,-3.03125,-1.4609375,3.46875,-0.73046875,-2.578125,-0.66796875,1.71875,0.361328125,2,5.125,2.25,4.6875,1.4921875,-0.77734375,-0.466796875,0.0439453125,-2.46875,3.59375,4.96875,2.34375,-5.34375,0.11083984375,-5.875,3.0625,4.09375,3.4375,0.2265625,9,-1.9296875,2.25,0.765625,3.671875,-2.484375,-1.171875,-1.6171875,4.1875,2.390625,-6.90625,0.36 [...]
+ "headers": {
+ "Content-Type": "application/json"
+ }
+ }
+ }
+]
+
+
+
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/CustomConfigPlaceholder.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/CustomConfigPlaceholder.java
new file mode 100644
index 0000000000..287dd90352
--- /dev/null
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/CustomConfigPlaceholder.java
@@ -0,0 +1,56 @@
+/*
+ * 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.seatunnel.transform.nlpmodel;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class CustomConfigPlaceholder {
+
+ // Placeholder ${model}
+ public static final String REPLACE_PLACEHOLDER_MODEL = "model";
+ // Placeholder ${input}
+ public static final String REPLACE_PLACEHOLDER_INPUT = "input";
+ // Placeholder ${prompt}
+ public static final String REPLACE_PLACEHOLDER_PROMPT = "prompt";
+
+ public static String replacePlaceholders(
+ String input, String placeholderName, String value, String defaultValue) {
+ String placeholderRegex = "\\$\\{" + Pattern.quote(placeholderName) + "(:[^}]*)?\\}";
+ Pattern pattern = Pattern.compile(placeholderRegex);
+ Matcher matcher = pattern.matcher(input);
+
+ StringBuffer result = new StringBuffer();
+ while (matcher.find()) {
+ String replacement =
+ value != null && !value.isEmpty()
+ ? value
+ : (matcher.group(1) != null
+ ? matcher.group(1).substring(1).trim()
+ : defaultValue);
+ if (replacement == null) {
+ continue;
+ }
+ matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
+ }
+ matcher.appendTail(result);
+ return result.toString();
+ }
+
+ public static Boolean findPlaceholder(String input, String placeholderName) {
+ String placeholderRegex = "\\$\\{" + Pattern.quote(placeholderName) + "(:[^}]*)?\\}";
+ Pattern pattern = Pattern.compile(placeholderRegex);
+ Matcher matcher = pattern.matcher(input);
+ return matcher.find();
+ }
+}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/ModelProvider.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/ModelProvider.java
new file mode 100644
index 0000000000..a5ab4dc84a
--- /dev/null
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/ModelProvider.java
@@ -0,0 +1,50 @@
+/*
+ * 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.seatunnel.transform.nlpmodel;
+
+import org.apache.commons.lang3.StringUtils;
+
+public enum ModelProvider {
+ OPENAI("https://api.openai.com/v1/chat/completions", "https://api.openai.com/v1/embeddings"),
+ DOUBAO("", "https://ark.cn-beijing.volces.com/api/v3/embeddings"),
+ QIANFAN("", "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/embeddings"),
+ CUSTOM("", ""),
+ LOCAL("", "");
+
+ private final String LLMProviderPath;
+ private final String EmbeddingProviderPath;
+
+ ModelProvider(String llmProviderPath, String embeddingProviderPath) {
+ LLMProviderPath = llmProviderPath;
+ EmbeddingProviderPath = embeddingProviderPath;
+ }
+
+ public String usedLLMPath(String path) {
+ if (StringUtils.isBlank(path)) {
+ return LLMProviderPath;
+ }
+ return path;
+ }
+
+ public String usedEmbeddingPath(String path) {
+ if (StringUtils.isBlank(path)) {
+ return EmbeddingProviderPath;
+ }
+ return path;
+ }
+}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/ModelTransformConfig.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/ModelTransformConfig.java
new file mode 100644
index 0000000000..b123459750
--- /dev/null
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/ModelTransformConfig.java
@@ -0,0 +1,115 @@
+/*
+ * 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.seatunnel.transform.nlpmodel;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.core.type.TypeReference;
+
+import org.apache.seatunnel.api.configuration.Option;
+import org.apache.seatunnel.api.configuration.Options;
+import org.apache.seatunnel.api.table.type.SqlType;
+
+import java.io.Serializable;
+import java.util.Map;
+
+public class ModelTransformConfig implements Serializable {
+
+ public static final Option<ModelProvider> MODEL_PROVIDER =
+ Options.key("model_provider")
+ .enumType(ModelProvider.class)
+ .noDefaultValue()
+ .withDescription("The model provider of LLM/Embedding");
+
+ public static final Option<SqlType> OUTPUT_DATA_TYPE =
+ Options.key("output_data_type")
+ .enumType(SqlType.class)
+ .defaultValue(SqlType.STRING)
+ .withDescription("The output data type of LLM");
+
+ public static final Option<String> MODEL =
+ Options.key("model")
+ .stringType()
+ .noDefaultValue()
+ .withDescription(
+ "The model of LLM/Embedding, eg: if the model provider is OpenAI LLM, the model should be gpt-3.5-turbo/gpt-4o-mini, etc.");
+
+ public static final Option<String> API_KEY =
+ Options.key("api_key")
+ .stringType()
+ .noDefaultValue()
+ .withDescription("The API key of LLM/Embedding");
+
+ public static final Option<String> SECRET_KEY =
+ Options.key("secret_key")
+ .stringType()
+ .noDefaultValue()
+ .withDescription("The Secret key of LLM/Embedding");
+
+ public static final Option<String> API_PATH =
+ Options.key("api_path")
+ .stringType()
+ .noDefaultValue()
+ .withFallbackKeys("openai.api_path")
+ .withDescription("The API of LLM/Embedding");
+
+ public static final Option<String> OAUTH_PATH =
+ Options.key("oauth_path")
+ .stringType()
+ .noDefaultValue()
+ .withDescription("The Oauth path of LLM/Embedding");
+
+ public static final Option<Integer> PROCESS_BATCH_SIZE =
+ Options.key("process_batch_size")
+ .intType()
+ .defaultValue(100)
+ .withFallbackKeys("inference_batch_size")
+ .withDescription("The row batch size of each process");
+
+ public static class CustomRequestConfig {
+
+ // Custom response parsing
+ public static final Option<Map<String, Object>> CUSTOM_CONFIG =
+ Options.key("custom_config")
+ .type(new TypeReference<Map<String, Object>>() {})
+ .noDefaultValue()
+ .withDescription("The custom config of the custom model.");
+
+ public static final Option<String> CUSTOM_RESPONSE_PARSE =
+ Options.key("custom_response_parse")
+ .stringType()
+ .noDefaultValue()
+ .withDescription(
+ "The response parse of the custom model. You can use Jsonpath to parse the return object you want to parse. eg: $.choices[*].message.content");
+
+ public static final Option<Map<String, String>> CUSTOM_REQUEST_HEADERS =
+ Options.key("custom_request_headers")
+ .mapType()
+ .noDefaultValue()
+ .withDescription("The custom request headers of the custom model.");
+
+ public static final Option<Map<String, Object>> CUSTOM_REQUEST_BODY =
+ Options.key("custom_request_body")
+ .type(new TypeReference<Map<String, Object>>() {})
+ .noDefaultValue()
+ .withDescription(
+ "The custom request body of the custom model."
+ + "1. ${model} placeholder for selecting model name."
+ + "2. ${input} placeholder for Determine input type. eg: [\"${input}\"]"
+ + "3. ${prompt} placeholder for LLM model "
+ + "4. ...");
+ }
+}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/EmbeddingTransform.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/EmbeddingTransform.java
new file mode 100644
index 0000000000..0758c310b5
--- /dev/null
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/EmbeddingTransform.java
@@ -0,0 +1,205 @@
+/*
+ * 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.seatunnel.transform.nlpmodel.embadding;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.Column;
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.api.table.type.VectorType;
+import org.apache.seatunnel.transform.common.MultipleFieldOutputTransform;
+import org.apache.seatunnel.transform.common.SeaTunnelRowAccessor;
+import org.apache.seatunnel.transform.exception.TransformCommonError;
+import org.apache.seatunnel.transform.nlpmodel.ModelProvider;
+import org.apache.seatunnel.transform.nlpmodel.ModelTransformConfig;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.Model;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.custom.CustomModel;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.doubao.DoubaoModel;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.openai.OpenAIModel;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.qianfan.QianfanModel;
+import org.apache.seatunnel.transform.nlpmodel.llm.LLMTransformConfig;
+
+import lombok.NonNull;
+import lombok.SneakyThrows;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class EmbeddingTransform extends MultipleFieldOutputTransform {
+
+ private final ReadonlyConfig config;
+ private List<String> fieldNames;
+ private List<Integer> fieldOriginalIndexes;
+ private Model model;
+ private Integer dimension;
+
+ public EmbeddingTransform(
+ @NonNull ReadonlyConfig config, @NonNull CatalogTable inputCatalogTable) {
+ super(inputCatalogTable);
+ this.config = config;
+ initOutputFields(
+ inputCatalogTable.getTableSchema().toPhysicalRowDataType(),
+ config.get(EmbeddingTransformConfig.VECTORIZATION_FIELDS));
+ }
+
+ @Override
+ public void open() {
+ // Initialize model
+ ModelProvider provider = config.get(ModelTransformConfig.MODEL_PROVIDER);
+ try {
+ switch (provider) {
+ case CUSTOM:
+ // load custom_config from the configuration
+ ReadonlyConfig customConfig =
+ config.getOptional(
+ ModelTransformConfig.CustomRequestConfig.CUSTOM_CONFIG)
+ .map(ReadonlyConfig::fromMap)
+ .orElseThrow(
+ () ->
+ new IllegalArgumentException(
+ "Custom config can't be null"));
+ model =
+ new CustomModel(
+ config.get(ModelTransformConfig.MODEL),
+ provider.usedEmbeddingPath(
+ config.get(ModelTransformConfig.API_PATH)),
+ customConfig.get(
+ LLMTransformConfig.CustomRequestConfig
+ .CUSTOM_REQUEST_HEADERS),
+ customConfig.get(
+ ModelTransformConfig.CustomRequestConfig
+ .CUSTOM_REQUEST_BODY),
+ customConfig.get(
+ LLMTransformConfig.CustomRequestConfig
+ .CUSTOM_RESPONSE_PARSE),
+ config.get(
+ EmbeddingTransformConfig
+ .SINGLE_VECTORIZED_INPUT_NUMBER));
+ break;
+ case OPENAI:
+ model =
+ new OpenAIModel(
+ config.get(ModelTransformConfig.API_KEY),
+ config.get(ModelTransformConfig.MODEL),
+ provider.usedEmbeddingPath(
+ config.get(ModelTransformConfig.API_PATH)),
+ config.get(
+ EmbeddingTransformConfig
+ .SINGLE_VECTORIZED_INPUT_NUMBER));
+ break;
+ case DOUBAO:
+ model =
+ new DoubaoModel(
+ config.get(ModelTransformConfig.API_KEY),
+ config.get(ModelTransformConfig.MODEL),
+ provider.usedEmbeddingPath(
+ config.get(ModelTransformConfig.API_PATH)),
+ config.get(
+ EmbeddingTransformConfig
+ .SINGLE_VECTORIZED_INPUT_NUMBER));
+ break;
+ case QIANFAN:
+ model =
+ new QianfanModel(
+ config.get(ModelTransformConfig.API_KEY),
+ config.get(ModelTransformConfig.SECRET_KEY),
+ config.get(ModelTransformConfig.MODEL),
+ provider.usedEmbeddingPath(
+ config.get(ModelTransformConfig.API_PATH)),
+ config.get(ModelTransformConfig.OAUTH_PATH),
+ config.get(
+ EmbeddingTransformConfig
+ .SINGLE_VECTORIZED_INPUT_NUMBER));
+ break;
+ case LOCAL:
+ default:
+ throw new IllegalArgumentException("Unsupported model provider: " + provider);
+ }
+ // Initialize dimension
+ dimension = model.dimension();
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to initialize model", e);
+ }
+ }
+
+ private void initOutputFields(SeaTunnelRowType inputRowType, Map<String, String> fields) {
+ List<String> fieldNames = new ArrayList<>();
+ List<Integer> fieldOriginalIndexes = new ArrayList<>();
+ for (Map.Entry<String, String> field : fields.entrySet()) {
+ String srcField = field.getValue();
+ int srcFieldIndex;
+ try {
+ srcFieldIndex = inputRowType.indexOf(srcField);
+ } catch (IllegalArgumentException e) {
+ throw TransformCommonError.cannotFindInputFieldError(getPluginName(), srcField);
+ }
+ fieldNames.add(field.getKey());
+ fieldOriginalIndexes.add(srcFieldIndex);
+ }
+ this.fieldNames = fieldNames;
+ this.fieldOriginalIndexes = fieldOriginalIndexes;
+ }
+
+ @Override
+ protected Object[] getOutputFieldValues(SeaTunnelRowAccessor inputRow) {
+ try {
+ Object[] fieldArray = new Object[fieldOriginalIndexes.size()];
+ for (int i = 0; i < fieldOriginalIndexes.size(); i++) {
+ fieldArray[i] = inputRow.getField(fieldOriginalIndexes.get(i));
+ }
+ List<ByteBuffer> vectorization = model.vectorization(fieldArray);
+ return vectorization.toArray();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to data vectorization", e);
+ }
+ }
+
+ @Override
+ protected Column[] getOutputColumns() {
+ Column[] columns = new Column[fieldNames.size()];
+ for (int i = 0; i < fieldNames.size(); i++) {
+ columns[i] =
+ PhysicalColumn.of(
+ fieldNames.get(i),
+ VectorType.VECTOR_FLOAT_TYPE,
+ null,
+ dimension,
+ true,
+ "",
+ "");
+ }
+ return columns;
+ }
+
+ @Override
+ public String getPluginName() {
+ return "Embedding";
+ }
+
+ @SneakyThrows
+ @Override
+ public void close() {
+ if (model != null) {
+ model.close();
+ }
+ }
+}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/EmbeddingTransformConfig.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/EmbeddingTransformConfig.java
new file mode 100644
index 0000000000..0309363abd
--- /dev/null
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/EmbeddingTransformConfig.java
@@ -0,0 +1,41 @@
+/*
+ * 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.seatunnel.transform.nlpmodel.embadding;
+
+import org.apache.seatunnel.api.configuration.Option;
+import org.apache.seatunnel.api.configuration.Options;
+import org.apache.seatunnel.transform.nlpmodel.ModelTransformConfig;
+
+import java.util.Map;
+
+public class EmbeddingTransformConfig extends ModelTransformConfig {
+
+ public static final Option<Integer> SINGLE_VECTORIZED_INPUT_NUMBER =
+ Options.key("single_vectorized_input_number")
+ .intType()
+ .defaultValue(1)
+ .withDescription(
+ "The number of single vectorized inputs, default is 1 , which means 1 inputs will be vectorized in one request , eg: qianfan only allows a maximum of 16 simultaneous messages, depending on your own settings, etc");
+
+ public static final Option<Map<String, String>> VECTORIZATION_FIELDS =
+ Options.key("vectorization_fields")
+ .mapType()
+ .noDefaultValue()
+ .withDescription(
+ "Specify the field vectorization relationship between input and output");
+}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransformFactory.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/EmbeddingTransformFactory.java
similarity index 51%
copy from seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransformFactory.java
copy to seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/EmbeddingTransformFactory.java
index 6fe5d53fe5..db3464e929 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransformFactory.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/EmbeddingTransformFactory.java
@@ -15,45 +15,58 @@
* limitations under the License.
*/
-package org.apache.seatunnel.transform.llm;
+package org.apache.seatunnel.transform.nlpmodel.embadding;
+
+import org.apache.seatunnel.shade.com.google.common.collect.Lists;
import org.apache.seatunnel.api.configuration.util.OptionRule;
-import org.apache.seatunnel.api.table.catalog.CatalogTable;
import org.apache.seatunnel.api.table.connector.TableTransform;
import org.apache.seatunnel.api.table.factory.Factory;
import org.apache.seatunnel.api.table.factory.TableTransformFactory;
import org.apache.seatunnel.api.table.factory.TableTransformFactoryContext;
+import org.apache.seatunnel.transform.nlpmodel.ModelProvider;
+import org.apache.seatunnel.transform.nlpmodel.llm.LLMTransformConfig;
import com.google.auto.service.AutoService;
@AutoService(Factory.class)
-public class LLMTransformFactory implements TableTransformFactory {
+public class EmbeddingTransformFactory implements TableTransformFactory {
@Override
public String factoryIdentifier() {
- return "LLM";
+ return "Embedding";
}
@Override
public OptionRule optionRule() {
return OptionRule.builder()
.required(
- LLMTransformConfig.MODEL_PROVIDER,
- LLMTransformConfig.MODEL,
- LLMTransformConfig.PROMPT,
- LLMTransformConfig.API_KEY)
+ EmbeddingTransformConfig.MODEL_PROVIDER,
+ EmbeddingTransformConfig.MODEL,
+ EmbeddingTransformConfig.VECTORIZATION_FIELDS)
.optional(
- LLMTransformConfig.OUTPUT_DATA_TYPE,
- LLMTransformConfig.INFERENCE_BATCH_SIZE)
+ EmbeddingTransformConfig.API_PATH,
+ EmbeddingTransformConfig.SINGLE_VECTORIZED_INPUT_NUMBER,
+ EmbeddingTransformConfig.PROCESS_BATCH_SIZE)
+ .conditional(
+ EmbeddingTransformConfig.MODEL_PROVIDER,
+ Lists.newArrayList(ModelProvider.OPENAI, ModelProvider.DOUBAO),
+ EmbeddingTransformConfig.API_KEY)
+ .conditional(
+ EmbeddingTransformConfig.MODEL_PROVIDER,
+ ModelProvider.QIANFAN,
+ EmbeddingTransformConfig.API_KEY,
+ EmbeddingTransformConfig.SECRET_KEY,
+ EmbeddingTransformConfig.OAUTH_PATH)
.conditional(
LLMTransformConfig.MODEL_PROVIDER,
- ModelProvider.OPENAI,
- LLMTransformConfig.OPENAI_API_PATH)
+ ModelProvider.CUSTOM,
+ LLMTransformConfig.CustomRequestConfig.CUSTOM_CONFIG)
.build();
}
@Override
public TableTransform createTransform(TableTransformFactoryContext context) {
- CatalogTable catalogTable = context.getCatalogTables().get(0);
- return () -> new LLMTransform(context.getOptions(), catalogTable);
+ return () ->
+ new EmbeddingTransform(context.getOptions(), context.getCatalogTables().get(0));
}
}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/AbstractModel.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/AbstractModel.java
new file mode 100644
index 0000000000..2e8665559b
--- /dev/null
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/AbstractModel.java
@@ -0,0 +1,70 @@
+/*
+ * 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.seatunnel.transform.nlpmodel.embadding.remote;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.seatunnel.common.utils.BufferUtils;
+
+import org.apache.commons.lang3.ArrayUtils;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+
+public abstract class AbstractModel implements Model {
+
+ protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+ protected static final String DIMENSION_EXAMPLE = "dimension example";
+ private final Integer singleVectorizedInputNumber;
+
+ protected AbstractModel(Integer singleVectorizedInputNumber) {
+ this.singleVectorizedInputNumber = singleVectorizedInputNumber;
+ }
+
+ @Override
+ public List<ByteBuffer> vectorization(Object[] fields) throws IOException {
+ List<ByteBuffer> result = new ArrayList<>();
+
+ List<List<Float>> vectors = batchProcess(fields, singleVectorizedInputNumber);
+ for (List<Float> vector : vectors) {
+ result.add(BufferUtils.toByteBuffer(vector.toArray(new Float[0])));
+ }
+ return result;
+ }
+
+ protected abstract List<List<Float>> vector(Object[] fields) throws IOException;
+
+ public List<List<Float>> batchProcess(Object[] array, int batchSize) throws IOException {
+ List<List<Float>> merged = new ArrayList<>();
+ if (array == null || array.length == 0) {
+ return merged;
+ }
+ for (int i = 0; i < array.length; i += batchSize) {
+ Object[] batch = ArrayUtils.subarray(array, i, i + batchSize);
+ List<List<Float>> vector = vector(batch);
+ merged.addAll(vector);
+ }
+ if (array.length != merged.size()) {
+ throw new RuntimeException(
+ "The number of vectors is not equal to the number of inputs, Please verify the configuration of the input field and the result returned.");
+ }
+ return merged;
+ }
+}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/ModelProvider.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/Model.java
similarity index 70%
rename from seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/ModelProvider.java
rename to seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/Model.java
index a55d706c09..d02dec7718 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/ModelProvider.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/Model.java
@@ -15,8 +15,16 @@
* limitations under the License.
*/
-package org.apache.seatunnel.transform.llm;
+package org.apache.seatunnel.transform.nlpmodel.embadding.remote;
-public enum ModelProvider {
- OPENAI
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.List;
+
+public interface Model extends Closeable {
+
+ List<ByteBuffer> vectorization(Object[] fields) throws IOException;
+
+ Integer dimension() throws IOException;
}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/custom/CustomModel.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/custom/CustomModel.java
new file mode 100644
index 0000000000..532d89bbd6
--- /dev/null
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/custom/CustomModel.java
@@ -0,0 +1,152 @@
+/*
+ * 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.seatunnel.transform.nlpmodel.embadding.remote.custom;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.core.type.TypeReference;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode;
+
+import org.apache.seatunnel.transform.nlpmodel.CustomConfigPlaceholder;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.AbstractModel;
+
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.jayway.jsonpath.JsonPath;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+public class CustomModel extends AbstractModel {
+
+ private final CloseableHttpClient client;
+ private final String model;
+ private final String apiPath;
+ private final Map<String, String> header;
+ private final Map<String, Object> body;
+ private final String parse;
+
+ public CustomModel(
+ String model,
+ String apiPath,
+ Map<String, String> header,
+ Map<String, Object> body,
+ String parse,
+ Integer vectorizedNumber) {
+ super(vectorizedNumber);
+ this.apiPath = apiPath;
+ this.model = model;
+ this.header = header;
+ this.body = body;
+ this.parse = parse;
+ this.client = HttpClients.createDefault();
+ }
+
+ @Override
+ protected List<List<Float>> vector(Object[] fields) throws IOException {
+ return vectorGeneration(fields);
+ }
+
+ @Override
+ public Integer dimension() throws IOException {
+ return vectorGeneration(new Object[] {DIMENSION_EXAMPLE}).size();
+ }
+
+ private List<List<Float>> vectorGeneration(Object[] fields) throws IOException {
+ HttpPost post = new HttpPost(apiPath);
+ // Construct a request with custom parameters
+ for (Map.Entry<String, String> entry : header.entrySet()) {
+ post.setHeader(entry.getKey(), entry.getValue());
+ }
+
+ post.setEntity(
+ new StringEntity(
+ OBJECT_MAPPER.writeValueAsString(createJsonNodeFromData(fields)), "UTF-8"));
+
+ CloseableHttpResponse response = client.execute(post);
+
+ String responseStr = EntityUtils.toString(response.getEntity());
+
+ if (response.getStatusLine().getStatusCode() != 200) {
+ throw new IOException("Failed to get vector from custom, response: " + responseStr);
+ }
+
+ return OBJECT_MAPPER.convertValue(
+ parseResponse(responseStr), new TypeReference<List<List<Float>>>() {});
+ }
+
+ @VisibleForTesting
+ public Object parseResponse(String responseStr) {
+ return JsonPath.parse(responseStr).read(parse);
+ }
+
+ @VisibleForTesting
+ public ObjectNode createJsonNodeFromData(Object[] fields) throws IOException {
+ JsonNode rootNode = OBJECT_MAPPER.readTree(OBJECT_MAPPER.writeValueAsString(body));
+ Iterator<Map.Entry<String, JsonNode>> bodyFields = rootNode.fields();
+ while (bodyFields.hasNext()) {
+ Map.Entry<String, JsonNode> field = bodyFields.next();
+ String fieldName = field.getKey();
+ JsonNode fieldValue = field.getValue();
+ if (fieldValue.isTextual()) {
+ String value = fieldValue.asText();
+ if (CustomConfigPlaceholder.findPlaceholder(
+ value, CustomConfigPlaceholder.REPLACE_PLACEHOLDER_MODEL)) {
+ ((ObjectNode) rootNode)
+ .put(
+ fieldName,
+ CustomConfigPlaceholder.replacePlaceholders(
+ value,
+ CustomConfigPlaceholder.REPLACE_PLACEHOLDER_MODEL,
+ model,
+ null));
+ } else if (CustomConfigPlaceholder.findPlaceholder(
+ value, CustomConfigPlaceholder.REPLACE_PLACEHOLDER_INPUT)) {
+ ((ObjectNode) rootNode)
+ .put(
+ fieldName,
+ CustomConfigPlaceholder.replacePlaceholders(
+ value,
+ CustomConfigPlaceholder.REPLACE_PLACEHOLDER_INPUT,
+ fields[0].toString(),
+ null));
+ }
+ } else if (fieldValue.isArray()) {
+ ArrayNode arrayNode = OBJECT_MAPPER.valueToTree(Arrays.asList(fields));
+ ((ObjectNode) rootNode).set(fieldName, arrayNode);
+ }
+ }
+ return ((ObjectNode) rootNode);
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (client != null) {
+ client.close();
+ }
+ }
+}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/openai/OpenAIModel.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/doubao/DoubaoModel.java
similarity index 59%
copy from seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/openai/OpenAIModel.java
copy to seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/doubao/DoubaoModel.java
index 9477b87320..945767d832 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/openai/OpenAIModel.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/doubao/DoubaoModel.java
@@ -15,16 +15,14 @@
* limitations under the License.
*/
-package org.apache.seatunnel.transform.llm.model.openai;
+package org.apache.seatunnel.transform.nlpmodel.embadding.remote.doubao;
import org.apache.seatunnel.shade.com.fasterxml.jackson.core.type.TypeReference;
import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ArrayNode;
import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode;
-import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
-import org.apache.seatunnel.api.table.type.SqlType;
-import org.apache.seatunnel.transform.llm.model.AbstractModel;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.AbstractModel;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
@@ -35,64 +33,74 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.google.common.annotations.VisibleForTesting;
-import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
-/**
- * OpenAI model. Refer <a href="https://platform.openai.com/docs/api-reference/chat">chat api </a>
- */
-@Slf4j
-public class OpenAIModel extends AbstractModel {
+public class DoubaoModel extends AbstractModel {
private final CloseableHttpClient client;
private final String apiKey;
private final String model;
private final String apiPath;
- public OpenAIModel(
- SeaTunnelRowType rowType,
- SqlType outputType,
- String prompt,
- String model,
- String apiKey,
- String apiPath) {
- super(rowType, outputType, prompt);
+ public DoubaoModel(String apiKey, String model, String apiPath, Integer vectorizedNumber) {
+ super(vectorizedNumber);
this.apiKey = apiKey;
- this.apiPath = apiPath;
this.model = model;
+ this.apiPath = apiPath;
this.client = HttpClients.createDefault();
}
@Override
- protected List<String> chatWithModel(String prompt, String data) throws IOException {
+ protected List<List<Float>> vector(Object[] fields) throws IOException {
+ return vectorGeneration(fields);
+ }
+
+ @Override
+ public Integer dimension() throws IOException {
+ return vectorGeneration(new Object[] {DIMENSION_EXAMPLE}).size();
+ }
+
+ private List<List<Float>> vectorGeneration(Object[] fields) throws IOException {
HttpPost post = new HttpPost(apiPath);
post.setHeader("Authorization", "Bearer " + apiKey);
post.setHeader("Content-Type", "application/json");
- ObjectNode objectNode = createJsonNodeFromData(prompt, data);
- post.setEntity(new StringEntity(OBJECT_MAPPER.writeValueAsString(objectNode), "UTF-8"));
post.setConfig(
RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(20000).build());
+
+ post.setEntity(
+ new StringEntity(
+ OBJECT_MAPPER.writeValueAsString(createJsonNodeFromData(fields)), "UTF-8"));
+
CloseableHttpResponse response = client.execute(post);
String responseStr = EntityUtils.toString(response.getEntity());
+
if (response.getStatusLine().getStatusCode() != 200) {
- throw new IOException("Failed to chat with model, response: " + responseStr);
+ throw new IOException("Failed to get vector from doubao, response: " + responseStr);
}
- JsonNode result = OBJECT_MAPPER.readTree(responseStr);
- String resultData = result.get("choices").get(0).get("message").get("content").asText();
- return OBJECT_MAPPER.readValue(resultData, new TypeReference<List<String>>() {});
+ JsonNode data = OBJECT_MAPPER.readTree(responseStr).get("data");
+ List<List<Float>> embeddings = new ArrayList<>();
+
+ if (data.isArray()) {
+ for (JsonNode node : data) {
+ JsonNode embeddingNode = node.get("embedding");
+ List<Float> embedding =
+ OBJECT_MAPPER.readValue(
+ embeddingNode.traverse(), new TypeReference<List<Float>>() {});
+ embeddings.add(embedding);
+ }
+ }
+ return embeddings;
}
@VisibleForTesting
- public ObjectNode createJsonNodeFromData(String prompt, String data) {
- ObjectNode objectNode = OBJECT_MAPPER.createObjectNode();
- objectNode.put("model", model);
- ArrayNode messages = objectNode.putArray("messages");
- messages.addObject().put("role", "system").put("content", prompt);
- messages.addObject().put("role", "user").put("content", data);
- return objectNode;
+ public ObjectNode createJsonNodeFromData(Object[] fields) {
+ ArrayNode arrayNode = OBJECT_MAPPER.valueToTree(Arrays.asList(fields));
+ return OBJECT_MAPPER.createObjectNode().put("model", model).set("input", arrayNode);
}
@Override
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/openai/OpenAIModel.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/openai/OpenAIModel.java
similarity index 59%
copy from seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/openai/OpenAIModel.java
copy to seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/openai/OpenAIModel.java
index 9477b87320..62a81cc097 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/openai/OpenAIModel.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/openai/OpenAIModel.java
@@ -15,16 +15,14 @@
* limitations under the License.
*/
-package org.apache.seatunnel.transform.llm.model.openai;
+package org.apache.seatunnel.transform.nlpmodel.embadding.remote.openai;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.seatunnel.shade.com.fasterxml.jackson.core.type.TypeReference;
import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
-import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ArrayNode;
import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode;
-import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
-import org.apache.seatunnel.api.table.type.SqlType;
-import org.apache.seatunnel.transform.llm.model.AbstractModel;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.AbstractModel;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
@@ -35,15 +33,11 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.google.common.annotations.VisibleForTesting;
-import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.List;
-/**
- * OpenAI model. Refer <a href="https://platform.openai.com/docs/api-reference/chat">chat api </a>
- */
-@Slf4j
public class OpenAIModel extends AbstractModel {
private final CloseableHttpClient client;
@@ -51,47 +45,65 @@ public class OpenAIModel extends AbstractModel {
private final String model;
private final String apiPath;
- public OpenAIModel(
- SeaTunnelRowType rowType,
- SqlType outputType,
- String prompt,
- String model,
- String apiKey,
- String apiPath) {
- super(rowType, outputType, prompt);
+ public OpenAIModel(String apiKey, String model, String apiPath, Integer vectorizedNumber) {
+ super(vectorizedNumber);
this.apiKey = apiKey;
- this.apiPath = apiPath;
this.model = model;
+ this.apiPath = apiPath;
this.client = HttpClients.createDefault();
}
@Override
- protected List<String> chatWithModel(String prompt, String data) throws IOException {
+ protected List<List<Float>> vector(Object[] fields) throws IOException {
+ if (fields.length > 1) {
+ throw new IllegalArgumentException("OpenAI model only supports single input");
+ }
+ return vectorGeneration(fields);
+ }
+
+ @Override
+ public Integer dimension() throws IOException {
+ return vectorGeneration(new Object[] {DIMENSION_EXAMPLE}).size();
+ }
+
+ private List<List<Float>> vectorGeneration(Object[] fields) throws IOException {
HttpPost post = new HttpPost(apiPath);
post.setHeader("Authorization", "Bearer " + apiKey);
post.setHeader("Content-Type", "application/json");
- ObjectNode objectNode = createJsonNodeFromData(prompt, data);
- post.setEntity(new StringEntity(OBJECT_MAPPER.writeValueAsString(objectNode), "UTF-8"));
post.setConfig(
RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(20000).build());
+
+ post.setEntity(
+ new StringEntity(
+ OBJECT_MAPPER.writeValueAsString(createJsonNodeFromData(fields)), "UTF-8"));
+
CloseableHttpResponse response = client.execute(post);
String responseStr = EntityUtils.toString(response.getEntity());
+
if (response.getStatusLine().getStatusCode() != 200) {
- throw new IOException("Failed to chat with model, response: " + responseStr);
+ throw new IOException("Failed to get vector from openai, response: " + responseStr);
}
- JsonNode result = OBJECT_MAPPER.readTree(responseStr);
- String resultData = result.get("choices").get(0).get("message").get("content").asText();
- return OBJECT_MAPPER.readValue(resultData, new TypeReference<List<String>>() {});
+ JsonNode data = OBJECT_MAPPER.readTree(responseStr).get("data");
+ List<List<Float>> embeddings = new ArrayList<>();
+
+ if (data.isArray()) {
+ for (JsonNode node : data) {
+ JsonNode embeddingNode = node.get("embedding");
+ List<Float> embedding =
+ OBJECT_MAPPER.readValue(
+ embeddingNode.traverse(), new TypeReference<List<Float>>() {});
+ embeddings.add(embedding);
+ }
+ }
+ return embeddings;
}
@VisibleForTesting
- public ObjectNode createJsonNodeFromData(String prompt, String data) {
+ public ObjectNode createJsonNodeFromData(Object[] data) throws JsonProcessingException {
ObjectNode objectNode = OBJECT_MAPPER.createObjectNode();
objectNode.put("model", model);
- ArrayNode messages = objectNode.putArray("messages");
- messages.addObject().put("role", "system").put("content", prompt);
- messages.addObject().put("role", "user").put("content", data);
+ objectNode.put("input", data[0].toString());
return objectNode;
}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/qianfan/QianfanModel.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/qianfan/QianfanModel.java
new file mode 100644
index 0000000000..081377e3de
--- /dev/null
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embadding/remote/qianfan/QianfanModel.java
@@ -0,0 +1,173 @@
+/*
+ * 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.seatunnel.transform.nlpmodel.embadding.remote.qianfan;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.core.type.TypeReference;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode;
+
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.AbstractModel;
+
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+import com.google.common.annotations.VisibleForTesting;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class QianfanModel extends AbstractModel {
+
+ private final CloseableHttpClient client;
+ private final String apiKey;
+ private final String secretKey;
+ private final String model;
+ private final String apiPath;
+ private final String oauthPath;
+ private final String oauthSuffixPath =
+ "?grant_type=client_credentials&client_id=%s&client_secret=%s";
+ private String accessToken;
+
+ public QianfanModel(
+ String apiKey,
+ String secretKey,
+ String model,
+ String apiPath,
+ String oauthPath,
+ Integer vectorizedNumber)
+ throws IOException {
+ super(vectorizedNumber);
+ this.apiKey = apiKey;
+ this.secretKey = secretKey;
+ this.model = model;
+ this.apiPath = apiPath;
+ this.oauthPath = oauthPath;
+ this.client = HttpClients.createDefault();
+ this.accessToken = getAccessToken();
+ }
+
+ public QianfanModel(
+ String apiKey,
+ String secretKey,
+ String model,
+ String apiPath,
+ Integer vectorizedNumber,
+ String oauthPath,
+ String accessToken)
+ throws IOException {
+ super(vectorizedNumber);
+ this.apiKey = apiKey;
+ this.secretKey = secretKey;
+ this.model = model;
+ this.apiPath = apiPath;
+ this.oauthPath = oauthPath;
+ this.client = HttpClients.createDefault();
+ this.accessToken = accessToken;
+ }
+
+ private String getAccessToken() throws IOException {
+ HttpGet get = new HttpGet(String.format(oauthPath + oauthSuffixPath, apiKey, secretKey));
+ CloseableHttpResponse response = client.execute(get);
+ String responseStr = EntityUtils.toString(response.getEntity());
+ if (response.getStatusLine().getStatusCode() != 200) {
+ throw new IOException("Failed to Oauth for qianfan, response: " + responseStr);
+ }
+ JsonNode result = OBJECT_MAPPER.readTree(responseStr);
+ return result.get("access_token").asText();
+ }
+
+ @Override
+ public List<List<Float>> vector(Object[] fields) throws IOException {
+ return vectorGeneration(fields);
+ }
+
+ @Override
+ public Integer dimension() throws IOException {
+ return vectorGeneration(new Object[] {DIMENSION_EXAMPLE}).get(0).size();
+ }
+
+ private List<List<Float>> vectorGeneration(Object[] fields) throws IOException {
+ String formattedApiPath =
+ String.format(
+ (apiPath.endsWith("/") ? apiPath : apiPath + "/") + "%s?access_token=%s",
+ model,
+ accessToken);
+ HttpPost post = new HttpPost(formattedApiPath);
+ post.setHeader("Content-Type", "application/json");
+ post.setConfig(
+ RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(20000).build());
+
+ post.setEntity(
+ new StringEntity(
+ OBJECT_MAPPER.writeValueAsString(createJsonNodeFromData(fields)), "UTF-8"));
+
+ CloseableHttpResponse response = client.execute(post);
+ String responseStr = EntityUtils.toString(response.getEntity());
+
+ if (response.getStatusLine().getStatusCode() != 200) {
+ throw new IOException("Failed to get vector from qianfan, response: " + responseStr);
+ }
+
+ JsonNode result = OBJECT_MAPPER.readTree(responseStr);
+ JsonNode errorCode = result.get("error_code");
+
+ if (errorCode != null) {
+ // Handle access token expiration
+ if (errorCode.asInt() == 110) {
+ this.accessToken = getAccessToken();
+ }
+ throw new IOException(
+ "Failed to get vector from qianfan, response: " + result.get("error_msg"));
+ }
+
+ List<List<Float>> embeddings = new ArrayList<>();
+ JsonNode data = result.get("data");
+ if (data.isArray()) {
+ for (JsonNode node : data) {
+ List<Float> embedding =
+ OBJECT_MAPPER.readValue(
+ node.get("embedding").traverse(),
+ new TypeReference<List<Float>>() {});
+ embeddings.add(embedding);
+ }
+ }
+ return embeddings;
+ }
+
+ @VisibleForTesting
+ public ObjectNode createJsonNodeFromData(Object[] data) {
+ ArrayNode arrayNode = OBJECT_MAPPER.valueToTree(Arrays.asList(data));
+ return OBJECT_MAPPER.createObjectNode().set("input", arrayNode);
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (client != null) {
+ client.close();
+ }
+ }
+}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransform.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/LLMTransform.java
similarity index 57%
rename from seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransform.java
rename to seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/LLMTransform.java
index d19960044f..10bde8df51 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransform.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/LLMTransform.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.seatunnel.transform.llm;
+package org.apache.seatunnel.transform.nlpmodel.llm;
import org.apache.seatunnel.api.configuration.ReadonlyConfig;
import org.apache.seatunnel.api.table.catalog.CatalogTable;
@@ -26,8 +26,11 @@ import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
import org.apache.seatunnel.transform.common.SeaTunnelRowAccessor;
import org.apache.seatunnel.transform.common.SingleFieldOutputTransform;
-import org.apache.seatunnel.transform.llm.model.Model;
-import org.apache.seatunnel.transform.llm.model.openai.OpenAIModel;
+import org.apache.seatunnel.transform.nlpmodel.ModelProvider;
+import org.apache.seatunnel.transform.nlpmodel.ModelTransformConfig;
+import org.apache.seatunnel.transform.nlpmodel.llm.remote.Model;
+import org.apache.seatunnel.transform.nlpmodel.llm.remote.custom.CustomModel;
+import org.apache.seatunnel.transform.nlpmodel.llm.remote.openai.OpenAIModel;
import lombok.NonNull;
import lombok.SneakyThrows;
@@ -61,18 +64,47 @@ public class LLMTransform extends SingleFieldOutputTransform {
@Override
public void open() {
- ModelProvider provider = config.get(LLMTransformConfig.MODEL_PROVIDER);
- if (provider.equals(ModelProvider.OPENAI)) {
- model =
- new OpenAIModel(
- inputCatalogTable.getSeaTunnelRowType(),
- outputDataType.getSqlType(),
- config.get(LLMTransformConfig.PROMPT),
- config.get(LLMTransformConfig.MODEL),
- config.get(LLMTransformConfig.API_KEY),
- config.get(LLMTransformConfig.OPENAI_API_PATH));
- } else {
- throw new IllegalArgumentException("Unsupported model provider: " + provider);
+ ModelProvider provider = config.get(ModelTransformConfig.MODEL_PROVIDER);
+ switch (provider) {
+ case CUSTOM:
+ // load custom_config from the configuration
+ ReadonlyConfig customConfig =
+ config.getOptional(ModelTransformConfig.CustomRequestConfig.CUSTOM_CONFIG)
+ .map(ReadonlyConfig::fromMap)
+ .orElseThrow(
+ () ->
+ new IllegalArgumentException(
+ "Custom config can't be null"));
+ model =
+ new CustomModel(
+ inputCatalogTable.getSeaTunnelRowType(),
+ outputDataType.getSqlType(),
+ config.get(LLMTransformConfig.PROMPT),
+ config.get(LLMTransformConfig.MODEL),
+ provider.usedLLMPath(config.get(LLMTransformConfig.API_PATH)),
+ customConfig.get(
+ LLMTransformConfig.CustomRequestConfig
+ .CUSTOM_REQUEST_HEADERS),
+ customConfig.get(
+ LLMTransformConfig.CustomRequestConfig.CUSTOM_REQUEST_BODY),
+ customConfig.get(
+ LLMTransformConfig.CustomRequestConfig
+ .CUSTOM_RESPONSE_PARSE));
+ break;
+ case OPENAI:
+ model =
+ new OpenAIModel(
+ inputCatalogTable.getSeaTunnelRowType(),
+ outputDataType.getSqlType(),
+ config.get(LLMTransformConfig.PROMPT),
+ config.get(LLMTransformConfig.MODEL),
+ config.get(LLMTransformConfig.API_KEY),
+ provider.usedLLMPath(config.get(LLMTransformConfig.API_PATH)));
+ break;
+ case QIANFAN:
+ case DOUBAO:
+ default:
+ throw new IllegalArgumentException("Unsupported model provider: " + provider);
}
}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransformConfig.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/LLMTransformConfig.java
similarity index 55%
rename from seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransformConfig.java
rename to seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/LLMTransformConfig.java
index ca3da7e670..8800f061db 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransformConfig.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/LLMTransformConfig.java
@@ -15,27 +15,13 @@
* limitations under the License.
*/
-package org.apache.seatunnel.transform.llm;
+package org.apache.seatunnel.transform.nlpmodel.llm;
import org.apache.seatunnel.api.configuration.Option;
import org.apache.seatunnel.api.configuration.Options;
-import org.apache.seatunnel.api.table.type.SqlType;
+import org.apache.seatunnel.transform.nlpmodel.ModelTransformConfig;
-import java.io.Serializable;
-
-public class LLMTransformConfig implements Serializable {
-
- public static final Option<ModelProvider> MODEL_PROVIDER =
- Options.key("model_provider")
- .enumType(ModelProvider.class)
- .noDefaultValue()
- .withDescription("The model provider of LLM");
-
- public static final Option<SqlType> OUTPUT_DATA_TYPE =
- Options.key("output_data_type")
- .enumType(SqlType.class)
- .defaultValue(SqlType.STRING)
- .withDescription("The output data type of LLM");
+public class LLMTransformConfig extends ModelTransformConfig {
public static final Option<String> PROMPT =
Options.key("prompt")
@@ -43,19 +29,6 @@ public class LLMTransformConfig implements Serializable {
.noDefaultValue()
.withDescription("The prompt of LLM");
- public static final Option<String> MODEL =
- Options.key("model")
- .stringType()
- .noDefaultValue()
- .withDescription(
- "The model of LLM, eg: if the model provider is OpenAI, the model should be gpt-3.5-turbo/gpt-4o-mini, etc.");
-
- public static final Option<String> API_KEY =
- Options.key("api_key")
- .stringType()
- .noDefaultValue()
- .withDescription("The API key of LLM");
-
public static final Option<Integer> INFERENCE_BATCH_SIZE =
Options.key("inference_batch_size")
.intType()
@@ -67,5 +40,5 @@ public class LLMTransformConfig implements Serializable {
Options.key("openai.api_path")
.stringType()
.defaultValue("https://api.openai.com/v1/chat/completions")
- .withDescription("The API path of OpenAI");
+ .withDescription("The API path of OpenAI LLM");
}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransformFactory.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/LLMTransformFactory.java
similarity index 67%
rename from seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransformFactory.java
rename to seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/LLMTransformFactory.java
index 6fe5d53fe5..eda57e1275 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/LLMTransformFactory.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/LLMTransformFactory.java
@@ -15,7 +15,9 @@
* limitations under the License.
*/
-package org.apache.seatunnel.transform.llm;
+package org.apache.seatunnel.transform.nlpmodel.llm;
+
+import org.apache.seatunnel.shade.com.google.common.collect.Lists;
import org.apache.seatunnel.api.configuration.util.OptionRule;
import org.apache.seatunnel.api.table.catalog.CatalogTable;
@@ -23,6 +25,8 @@ import org.apache.seatunnel.api.table.connector.TableTransform;
import org.apache.seatunnel.api.table.factory.Factory;
import org.apache.seatunnel.api.table.factory.TableTransformFactory;
import org.apache.seatunnel.api.table.factory.TableTransformFactoryContext;
+import org.apache.seatunnel.transform.nlpmodel.ModelProvider;
+import org.apache.seatunnel.transform.nlpmodel.ModelTransformConfig;
import com.google.auto.service.AutoService;
@@ -39,15 +43,25 @@ public class LLMTransformFactory implements TableTransformFactory {
.required(
LLMTransformConfig.MODEL_PROVIDER,
LLMTransformConfig.MODEL,
- LLMTransformConfig.PROMPT,
- LLMTransformConfig.API_KEY)
+ LLMTransformConfig.PROMPT)
.optional(
+ LLMTransformConfig.API_PATH,
LLMTransformConfig.OUTPUT_DATA_TYPE,
- LLMTransformConfig.INFERENCE_BATCH_SIZE)
+ LLMTransformConfig.PROCESS_BATCH_SIZE)
+ .conditional(
+ LLMTransformConfig.MODEL_PROVIDER,
+ Lists.newArrayList(ModelProvider.OPENAI, ModelProvider.DOUBAO),
+ LLMTransformConfig.API_KEY)
+ .conditional(
+ LLMTransformConfig.MODEL_PROVIDER,
+ ModelProvider.QIANFAN,
+ LLMTransformConfig.API_KEY,
+ LLMTransformConfig.SECRET_KEY,
+ ModelTransformConfig.OAUTH_PATH)
.conditional(
LLMTransformConfig.MODEL_PROVIDER,
- ModelProvider.OPENAI,
- LLMTransformConfig.OPENAI_API_PATH)
+ ModelProvider.CUSTOM,
+ LLMTransformConfig.CustomRequestConfig.CUSTOM_CONFIG)
.build();
}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/AbstractModel.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/AbstractModel.java
similarity index 98%
rename from seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/AbstractModel.java
rename to seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/AbstractModel.java
index 51d674c0ad..e658e51459 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/AbstractModel.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/AbstractModel.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.seatunnel.transform.llm.model;
+package org.apache.seatunnel.transform.nlpmodel.llm.remote;
import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ArrayNode;
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/Model.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/Model.java
similarity index 94%
rename from seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/Model.java
rename to seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/Model.java
index 77a8da6328..d055ac8b9e 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/Model.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/Model.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.seatunnel.transform.llm.model;
+package org.apache.seatunnel.transform.nlpmodel.llm.remote;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/custom/CustomModel.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/custom/CustomModel.java
new file mode 100644
index 0000000000..af893e92dd
--- /dev/null
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/custom/CustomModel.java
@@ -0,0 +1,152 @@
+/*
+ * 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.seatunnel.transform.nlpmodel.llm.remote.custom;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.core.type.TypeReference;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.TextNode;
+
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.api.table.type.SqlType;
+import org.apache.seatunnel.transform.nlpmodel.CustomConfigPlaceholder;
+import org.apache.seatunnel.transform.nlpmodel.llm.remote.AbstractModel;
+
+import org.apache.groovy.util.Maps;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.jayway.jsonpath.JsonPath;
+
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+public class CustomModel extends AbstractModel {
+
+ private final CloseableHttpClient client;
+ private final String model;
+ private final String apiPath;
+ private final Map<String, String> header;
+ private final Map<String, Object> body;
+ private final String parse;
+
+ public CustomModel(
+ SeaTunnelRowType rowType,
+ SqlType outputType,
+ String prompt,
+ String model,
+ String apiPath,
+ Map<String, String> header,
+ Map<String, Object> body,
+ String parse) {
+ super(rowType, outputType, prompt);
+ this.apiPath = apiPath;
+ this.model = model;
+ this.header = header;
+ this.body = body;
+ this.parse = parse;
+ this.client = HttpClients.createDefault();
+ }
+
+ @Override
+ protected List<String> chatWithModel(String promptWithLimit, String rowsJson)
+ throws IOException {
+ HttpPost post = new HttpPost(apiPath);
+ // Construct a request with custom parameters
+ for (Map.Entry<String, String> entry : header.entrySet()) {
+ post.setHeader(entry.getKey(), entry.getValue());
+ }
+
+ post.setEntity(
+ new StringEntity(
+ OBJECT_MAPPER.writeValueAsString(
+ createJsonNodeFromData(promptWithLimit, rowsJson)),
+ "UTF-8"));
+
+ CloseableHttpResponse response = client.execute(post);
+
+ String responseStr = EntityUtils.toString(response.getEntity());
+
+ if (response.getStatusLine().getStatusCode() != 200) {
+ throw new IOException("Failed to get vector from custom, response: " + responseStr);
+ }
+ return OBJECT_MAPPER.convertValue(
+ parseResponse(responseStr), new TypeReference<List<String>>() {});
+ }
+
+ @VisibleForTesting
+ public Object parseResponse(String responseStr) {
+ return JsonPath.parse(responseStr).read(parse);
+ }
+
+ @VisibleForTesting
+ public ObjectNode createJsonNodeFromData(String prompt, String data) throws IOException {
+ JsonNode jsonNode = OBJECT_MAPPER.readTree(OBJECT_MAPPER.writeValueAsString(body));
+ Map<String, String> placeholderValues =
+ Maps.of(
+ CustomConfigPlaceholder.REPLACE_PLACEHOLDER_INPUT, data,
+ CustomConfigPlaceholder.REPLACE_PLACEHOLDER_PROMPT, prompt,
+ CustomConfigPlaceholder.REPLACE_PLACEHOLDER_MODEL, model);
+
+ return (ObjectNode) replacePlaceholders(jsonNode, placeholderValues);
+ }
+
+ private static JsonNode replacePlaceholders(
+ JsonNode node, Map<String, String> placeholderValues) {
+ if (node.isObject()) {
+ ObjectNode objectNode = (ObjectNode) node;
+ Iterator<Map.Entry<String, JsonNode>> fields = objectNode.fields();
+ while (fields.hasNext()) {
+ Map.Entry<String, JsonNode> field = fields.next();
+ objectNode.set(
+ field.getKey(), replacePlaceholders(field.getValue(), placeholderValues));
+ }
+ } else if (node.isArray()) {
+ ArrayNode arrayNode = (ArrayNode) node;
+ for (int i = 0; i < arrayNode.size(); i++) {
+ arrayNode.set(i, replacePlaceholders(arrayNode.get(i), placeholderValues));
+ }
+ } else if (node.isTextual()) {
+ String textValue = node.asText();
+ for (Map.Entry<String, String> entry : placeholderValues.entrySet()) {
+ if (CustomConfigPlaceholder.findPlaceholder(textValue, entry.getKey())) {
+ textValue =
+ CustomConfigPlaceholder.replacePlaceholders(
+ textValue, entry.getKey(), entry.getValue(), null);
+ }
+ }
+ return new TextNode(textValue);
+ }
+ return node;
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (client != null) {
+ client.close();
+ }
+ }
+}
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/openai/OpenAIModel.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/openai/OpenAIModel.java
similarity index 96%
rename from seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/openai/OpenAIModel.java
rename to seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/openai/OpenAIModel.java
index 9477b87320..1424eed9e4 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/llm/model/openai/OpenAIModel.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/llm/remote/openai/OpenAIModel.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.seatunnel.transform.llm.model.openai;
+package org.apache.seatunnel.transform.nlpmodel.llm.remote.openai;
import org.apache.seatunnel.shade.com.fasterxml.jackson.core.type.TypeReference;
import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
@@ -24,7 +24,7 @@ import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode
import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
import org.apache.seatunnel.api.table.type.SqlType;
-import org.apache.seatunnel.transform.llm.model.AbstractModel;
+import org.apache.seatunnel.transform.nlpmodel.llm.remote.AbstractModel;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
diff --git a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/LLMTransformFactoryTest.java b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/EmbeddingTransformFactoryTest.java
similarity index 76%
copy from seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/LLMTransformFactoryTest.java
copy to seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/EmbeddingTransformFactoryTest.java
index 39b2769480..4d05432906 100644
--- a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/LLMTransformFactoryTest.java
+++ b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/EmbeddingTransformFactoryTest.java
@@ -17,16 +17,16 @@
package org.apache.seatunnel.transform;
-import org.apache.seatunnel.transform.llm.LLMTransformFactory;
+import org.apache.seatunnel.transform.nlpmodel.embadding.EmbeddingTransformFactory;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
-public class LLMTransformFactoryTest {
+public class EmbeddingTransformFactoryTest {
@Test
public void testOptionRule() throws Exception {
- LLMTransformFactory replaceTransformFactory = new LLMTransformFactory();
- Assertions.assertNotNull(replaceTransformFactory.optionRule());
+ EmbeddingTransformFactory embeddingTransformFactory = new EmbeddingTransformFactory();
+ Assertions.assertNotNull(embeddingTransformFactory.optionRule());
}
}
diff --git a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/LLMTransformFactoryTest.java b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/LLMTransformFactoryTest.java
index 39b2769480..85cad8e799 100644
--- a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/LLMTransformFactoryTest.java
+++ b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/LLMTransformFactoryTest.java
@@ -17,7 +17,7 @@
package org.apache.seatunnel.transform;
-import org.apache.seatunnel.transform.llm.LLMTransformFactory;
+import org.apache.seatunnel.transform.nlpmodel.llm.LLMTransformFactory;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
diff --git a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/embedding/EmbeddingRequestJsonTest.java b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/embedding/EmbeddingRequestJsonTest.java
new file mode 100644
index 0000000000..56e37f5021
--- /dev/null
+++ b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/embedding/EmbeddingRequestJsonTest.java
@@ -0,0 +1,143 @@
+/*
+ * 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.seatunnel.transform.embedding;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.core.type.TypeReference;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode;
+
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.custom.CustomModel;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.doubao.DoubaoModel;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.openai.OpenAIModel;
+import org.apache.seatunnel.transform.nlpmodel.embadding.remote.qianfan.QianfanModel;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import com.google.common.collect.Lists;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class EmbeddingRequestJsonTest {
+
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ @Test
+ void testOpenAIRequestJson() throws IOException {
+ OpenAIModel model =
+ new OpenAIModel(
+ "apikey", "modelName", "https://api.openai.com/v1/chat/completions", 1);
+ ObjectNode node =
+ model.createJsonNodeFromData(
+ new Object[] {
+ "Determine whether someone is Chinese or American by their name"
+ });
+ Assertions.assertEquals(
+ "{\"model\":\"modelName\",\"input\":\"Determine whether someone is Chinese or American by their name\"}",
+ OBJECT_MAPPER.writeValueAsString(node));
+ model.close();
+ }
+
+ @Test
+ void testDoubaoRequestJson() throws IOException {
+ DoubaoModel model =
+ new DoubaoModel(
+ "apikey", "modelName", "https://api.doubao.io/v1/chat/completions", 1);
+ ObjectNode node =
+ model.createJsonNodeFromData(
+ new Object[] {
+ "Determine whether someone is Chinese or American by their name"
+ });
+ Assertions.assertEquals(
+ "{\"model\":\"modelName\",\"input\":[\"Determine whether someone is Chinese or American by their name\"]}",
+ OBJECT_MAPPER.writeValueAsString(node));
+ model.close();
+ }
+
+ @Test
+ void testQianfanRequestJson() throws IOException {
+ QianfanModel model =
+ new QianfanModel(
+ "apikey",
+ "secretKey",
+ "modelName",
+ "https://api.qianfan.io/v1/chat/completions",
+ 1,
+ "xxxx",
+ "xxxxxxx");
+ ObjectNode node =
+ model.createJsonNodeFromData(
+ new Object[] {
+ "Determine whether someone is Chinese or American by their name"
+ });
+ Assertions.assertEquals(
+ "{\"input\":[\"Determine whether someone is Chinese or American by their name\"]}",
+ OBJECT_MAPPER.writeValueAsString(node));
+ model.close();
+ }
+
+ @Test
+ void testCustomRequestJson() throws IOException {
+ Map<String, String> header = new HashMap<>();
+ header.put("Content-Type", "application/json");
+ header.put("Authorization", "Bearer " + "apikey");
+ Map<String, Object> body = new HashMap<>();
+ body.put("model1", "${model}");
+ body.put("input1", Lists.newArrayList("${input}", "${input}"));
+
+ CustomModel model =
+ new CustomModel(
+ "modelName",
+ "https://api.custom.com/v1/chat/completions",
+ header,
+ body,
+ "$.data[*].embedding",
+ 1);
+ ObjectNode node =
+ model.createJsonNodeFromData(
+ new Object[] {
+ "Determine whether someone is Chinese or American by their name"
+ });
+ Assertions.assertEquals(
+ "{\"model1\":\"modelName\",\"input1\":[\"Determine whether someone is Chinese or American by their name\"]}",
+ OBJECT_MAPPER.writeValueAsString(node));
+ model.close();
+ }
+
+ @Test
+ void testCustomParseResponse() {
+ CustomModel customModel =
+ new CustomModel(
+ "modelName",
+ "https://api.custom.com/v1/chat/completions",
+ new HashMap<>(),
+ new HashMap<>(),
+ "$.data[*].embedding",
+ 1);
+ List<List<Float>> lists =
+ OBJECT_MAPPER.convertValue(
+ customModel.parseResponse(
+ "{\"created\":1725001256,\"id\":\"02172500125677376580aba8475a41c550bbf05104842f0405ef5\",\"data\":[{\"embedding\":[-1.625,0.07958984375,-1.5703125,-3.03125,-1.4609375,3.46875,-0.73046875,-2.578125,-0.66796875,1.71875,0.361328125,2,5.125,2.25,4.6875,1.4921875,-0.77734375,-0.466796875,0.0439453125,-2.46875,3.59375,4.96875,2.34375,-5.34375,0.11083984375,-5.875,3.0625,4.09375,3.4375,0.2265625,9,-1.9296875,2.25,0.765625,3.671875,-2.484375,-1.171875,-1.6171875, [...]
+ new TypeReference<List<List<Float>>>() {});
+ Assertions.assertEquals(2, lists.size());
+ Assertions.assertEquals(2560, lists.get(0).size());
+ }
+}
diff --git a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/llm/LLMRequestJsonTest.java b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/llm/LLMRequestJsonTest.java
index f32cc87055..2de785a1a8 100644
--- a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/llm/LLMRequestJsonTest.java
+++ b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/llm/LLMRequestJsonTest.java
@@ -24,12 +24,17 @@ import org.apache.seatunnel.api.table.type.BasicType;
import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
import org.apache.seatunnel.api.table.type.SqlType;
-import org.apache.seatunnel.transform.llm.model.openai.OpenAIModel;
+import org.apache.seatunnel.transform.nlpmodel.llm.remote.custom.CustomModel;
+import org.apache.seatunnel.transform.nlpmodel.llm.remote.openai.OpenAIModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class LLMRequestJsonTest {
@@ -58,4 +63,50 @@ public class LLMRequestJsonTest {
OBJECT_MAPPER.writeValueAsString(node));
model.close();
}
+
+ @Test
+ void testCustomRequestJson() throws IOException {
+ SeaTunnelRowType rowType =
+ new SeaTunnelRowType(
+ new String[] {"id", "name"},
+ new SeaTunnelDataType[] {BasicType.INT_TYPE, BasicType.STRING_TYPE});
+
+ Map<String, String> header = new HashMap<>();
+ header.put("Content-Type", "application/json");
+ header.put("Authorization", "Bearer " + "apikey");
+
+ List<Map<String, String>> messagesList = new ArrayList<>();
+
+ Map<String, String> systemMessage = new HashMap<>();
+ systemMessage.put("role", "system");
+ systemMessage.put("content", "${prompt}");
+ messagesList.add(systemMessage);
+
+ Map<String, String> userMessage = new HashMap<>();
+ userMessage.put("role", "user");
+ userMessage.put("content", "${input}");
+ messagesList.add(userMessage);
+
+ Map<String, Object> resultMap = new HashMap<>();
+ resultMap.put("model", "${model}");
+ resultMap.put("messages", messagesList);
+
+ CustomModel model =
+ new CustomModel(
+ rowType,
+ SqlType.STRING,
+ "Determine whether someone is Chinese or American by their name",
+ "custom-model",
+ "https://api.custom.com/v1/chat/completions",
+ header,
+ resultMap,
+ "{\"model\":\"${model}\",\"messages\":[{\"role\":\"system\",\"content\":\"${prompt}\"},{\"role\":\"user\",\"content\":\"${data}\"}]}");
+ ObjectNode node =
+ model.createJsonNodeFromData(
+ "Determine whether someone is Chinese or American by their name",
+ "{\"id\":1, \"name\":\"John\"}");
+ Assertions.assertEquals(
+ "{\"messages\":[{\"role\":\"system\",\"content\":\"Determine whether someone is Chinese or American by their name\"},{\"role\":\"user\",\"content\":\"{\\\"id\\\":1, \\\"name\\\":\\\"John\\\"}\"}],\"model\":\"custom-model\"}",
+ OBJECT_MAPPER.writeValueAsString(node));
+ }
}