This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 1211bb1e33a7 CAMEL-26553: camel-spring-ai-embeddings,
camel-langchain4j-embeddings - embed bodies that have a real converter to
String (#30766)
1211bb1e33a7 is described below
commit 1211bb1e33a7546b0e57b7c72bea0c2f34a2067b
Author: Karol Krawczyk <[email protected]>
AuthorDate: Thu Nov 26 21:07:31 2026 +0100
CAMEL-26553: camel-spring-ai-embeddings, camel-langchain4j-embeddings -
embed bodies that have a real converter to String (#30766)
* CAMEL-26553: camel-spring-ai-embeddings, camel-langchain4j-embeddings -
embed bodies that have a real converter to String
* CAMEL-26553: camel-support - share the toString() rule as
BodyFacts.isOnlyToString
* CAMEL-26553: camel-langchain4j-embeddings - review: clearer sentence on
the values embedded as their text
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../catalog/components/langchain4j-embeddings.json | 2 +-
.../catalog/components/spring-ai-embeddings.json | 2 +-
.../docs/langchain4j-embeddings-component.adoc | 10 +-
.../docs/spring-ai-embeddings-component.adoc | 15 ++-
.../embeddings/langchain4j-embeddings.json | 2 +-
.../docs/langchain4j-embeddings-component.adoc | 10 +-
.../embeddings/LangChain4jEmbeddingsEndpoint.java | 9 +-
.../embeddings/LangChain4jEmbeddingsProducer.java | 55 ++++-----
.../embeddings/LangChain4jEmbeddingsBodyTest.java | 119 ++++++++++++++++++-
.../camel/component/alibaba/kms/KMSUtils.java | 21 +---
.../ai/handler/AbstractWatsonxAiHandler.java | 30 +----
.../springai/embeddings/spring-ai-embeddings.json | 2 +-
.../main/docs/spring-ai-embeddings-component.adoc | 15 ++-
.../embeddings/SpringAiEmbeddingsEndpoint.java | 11 +-
.../embeddings/SpringAiEmbeddingsProducer.java | 40 +++----
.../SpringAiEmbeddingsComponentTest.java | 132 +++++++++++++++++----
.../org/apache/camel/support/BodyFactsTest.java | 27 +++++
.../java/org/apache/camel/support/BodyFacts.java | 33 ++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 20 ++--
19 files changed, 386 insertions(+), 169 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/langchain4j-embeddings.json
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/langchain4j-embeddings.json
index db07352dbb1b..8b7bd019ce0a 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/langchain4j-embeddings.json
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/langchain4j-embeddings.json
@@ -51,7 +51,7 @@
"CamelLangChain4jEmbeddingsTextSegments": { "index": 10, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.List<dev.langchain4j.data.segment.TextSegment>",
"deprecated": false, "autowired": false, "secret": false, "description": "List
of text segments from a batch embedAll operation", "constantName":
"org.apache.camel.component.langchain4j.embeddings.LangChain4jEmbeddingsHeaders#TEXT_SEGMENTS"
}
},
"bodyTypes": {
- "producerIn": { "carriers": [ "text", "bytes", "stream", "file", "list" ],
"description": "The text to embed: a String, bytes, a stream or a file read as
text, or a LangChain4j TextSegment; or a non-empty List of them to embed in one
batch. Another body or List element, such as a Map or a POJO, fails, as does no
body: convert it to text first" },
+ "producerIn": { "carriers": [ "text", "bytes", "stream", "file", "list" ],
"description": "The text to embed: a String, bytes, a stream, a file or another
value Camel converts to its text, such as a char[], or a LangChain4j
TextSegment; or a non-empty List of them to embed in one batch. A body or List
element Camel reads only as its toString(), such as a Map or a POJO, fails, as
does no body: marshal it first" },
"producerOut": { "carriers": [ "unchanged" ], "description": "The body is
kept. The vector goes in the CamelLangChain4jEmbeddingsVector header as a float
array, with the Embedding and the TextSegment in the
CamelLangChain4jEmbeddingsEmbedding and CamelLangChain4jEmbeddingsTextSegment
headers; a List body gives Lists of them in the
CamelLangChain4jEmbeddingsEmbeddings and CamelLangChain4jEmbeddingsTextSegments
headers instead" }
},
"properties": {
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/spring-ai-embeddings.json
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/spring-ai-embeddings.json
index 4c2815e8c576..7ad672a23558 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/spring-ai-embeddings.json
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/spring-ai-embeddings.json
@@ -38,7 +38,7 @@
"CamelSpringAiEmbeddingInputTexts": { "index": 5, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.List<String>", "deprecated": false, "autowired": false,
"secret": false, "description": "List of input texts that were embedded",
"constantName":
"org.apache.camel.component.springai.embeddings.SpringAiEmbeddingsHeaders#INPUT_TEXTS"
}
},
"bodyTypes": {
- "producerIn": { "carriers": [ "text", "bytes", "stream", "file", "list" ],
"description": "The text to embed: a String, bytes, a stream or a file read as
text, or a Spring AI Document as its text; or a java.util.List of them for a
batch (a Set or an array of them fails). Another body or List element, such as
a Map or a POJO, fails, as do no body and a null element: convert it to text
first" },
+ "producerIn": { "carriers": [ "text", "bytes", "stream", "file", "list" ],
"description": "The text to embed: a String, bytes, a stream, a file or another
value Camel converts to its text, such as a char[], or a Spring AI Document as
its text; or a java.util.List of them for a batch (a Set or an array of them
fails). A body or List element Camel reads only as its toString(), such as a
Map or a POJO, fails, as do no body and a null element: marshal it first" },
"producerOut": { "carriers": [ "list" ], "description": "The vector as a
float[] for one text, and a List of float[] for a List of texts, also for a
List with one text or none. The Embedding and the input text are in headers,
which spring-ai-vector-store reads" }
},
"properties": {
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/langchain4j-embeddings-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/langchain4j-embeddings-component.adoc
index e77f65e70de6..827dce2e1255 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/langchain4j-embeddings-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/langchain4j-embeddings-component.adoc
@@ -229,11 +229,15 @@ YAML::
The body is the text to embed: a `String` or a LangChain4j `TextSegment`.
Bytes, a stream and a file (such as the
body of a `file` consumer) are read as text, so a `from("file:...")` route
needs no `convertBodyTo(String.class)`.
-A non-empty `List` of them is embedded in one batch.
+So is any other value Camel converts to its text, such as a `char[]`, a
`ByteBuffer`, a Netty `ByteBuf`, a number, or a
+type with its own type converter to `String`. A `UUID`, a `URI`, a `URL`, a
`java.time` value or a `Date` is also
+embedded, as its `toString()` is its text. A non-empty `List` of them is
embedded in one batch.
Any other body, or element of a `List` body, such as a `Map` or a POJO, fails
the exchange with an
-`InvalidPayloadException` instead of being embedded as its `toString()`: turn
it into text first, with
-`convertBodyTo(String.class)` or a marshal to JSON, say. No body fails too.
+`InvalidPayloadException` instead of being embedded as its `toString()`, since
that is all Camel reads of it. The rule
+is the text itself: a value fails when the text Camel gives for it is no more
than its `toString()`. Marshal such a
+body first, to JSON, say, or, when its `toString()` is the text to embed,
convert it with
+`convertBodyTo(String.class)`. No body fails too.
The body is kept. A single text sets the
`CamelLangChain4jEmbeddingsEmbedding`, `CamelLangChain4jEmbeddingsVector`
and `CamelLangChain4jEmbeddingsTextSegment` headers, and a `List` the
`CamelLangChain4jEmbeddingsEmbeddings` and
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-ai-embeddings-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-ai-embeddings-component.adoc
index a2036cd24c7f..8dc3b5b2d381 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-ai-embeddings-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-ai-embeddings-component.adoc
@@ -50,11 +50,16 @@ The component accepts two types of input:
* **Single text**: A String containing the text to embed
* **Batch processing**: A List<String> containing multiple texts to embed at
once
-Bytes, a stream, a `Reader` or a file is read as text, and a Spring AI
`Document` is embedded as its text, as a body
-and as an element of a List. Any other body or List element, such as a `Map`,
a POJO or a number, fails the exchange
-with an `InvalidPayloadException` instead of being embedded as its
`toString()`: turn it into text first, with
-`convertBodyTo(String.class)` or a marshal to JSON, say. No body, or a `null`
element in a List, fails the exchange
-with an `IllegalArgumentException`.
+Bytes, a stream, a `Reader` or a file is read as text, and so is any other
value Camel converts to its text, such as
+a `char[]`, a `ByteBuffer`, a Netty `ByteBuf`, a number or a type with its own
type converter to `String`. A `UUID`, a
+`URI`, a `URL`, a `java.time` value or a `Date` is embedded as its
`toString()`, which is its text, and a Spring AI
+`Document` as its text. This holds for the body and for each element of a List.
+
+Any other body or List element, such as a `Map` or a POJO, fails the exchange
with an `InvalidPayloadException`
+instead of being embedded as its `toString()`, since that is all Camel reads
of it. The rule is the text itself: a
+value fails when the text Camel gives for it is no more than its `toString()`.
Marshal such a body first, to JSON, say,
+or, when its `toString()` is the text to embed, convert it with
`convertBodyTo(String.class)`. No body, or a `null`
+element in a List, fails the exchange with an `IllegalArgumentException`.
The embedding vectors are returned in the message body, with additional
metadata available in headers.
diff --git
a/components/camel-ai/camel-langchain4j-embeddings/src/generated/resources/META-INF/org/apache/camel/component/langchain4j/embeddings/langchain4j-embeddings.json
b/components/camel-ai/camel-langchain4j-embeddings/src/generated/resources/META-INF/org/apache/camel/component/langchain4j/embeddings/langchain4j-embeddings.json
index db07352dbb1b..8b7bd019ce0a 100644
---
a/components/camel-ai/camel-langchain4j-embeddings/src/generated/resources/META-INF/org/apache/camel/component/langchain4j/embeddings/langchain4j-embeddings.json
+++
b/components/camel-ai/camel-langchain4j-embeddings/src/generated/resources/META-INF/org/apache/camel/component/langchain4j/embeddings/langchain4j-embeddings.json
@@ -51,7 +51,7 @@
"CamelLangChain4jEmbeddingsTextSegments": { "index": 10, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.List<dev.langchain4j.data.segment.TextSegment>",
"deprecated": false, "autowired": false, "secret": false, "description": "List
of text segments from a batch embedAll operation", "constantName":
"org.apache.camel.component.langchain4j.embeddings.LangChain4jEmbeddingsHeaders#TEXT_SEGMENTS"
}
},
"bodyTypes": {
- "producerIn": { "carriers": [ "text", "bytes", "stream", "file", "list" ],
"description": "The text to embed: a String, bytes, a stream or a file read as
text, or a LangChain4j TextSegment; or a non-empty List of them to embed in one
batch. Another body or List element, such as a Map or a POJO, fails, as does no
body: convert it to text first" },
+ "producerIn": { "carriers": [ "text", "bytes", "stream", "file", "list" ],
"description": "The text to embed: a String, bytes, a stream, a file or another
value Camel converts to its text, such as a char[], or a LangChain4j
TextSegment; or a non-empty List of them to embed in one batch. A body or List
element Camel reads only as its toString(), such as a Map or a POJO, fails, as
does no body: marshal it first" },
"producerOut": { "carriers": [ "unchanged" ], "description": "The body is
kept. The vector goes in the CamelLangChain4jEmbeddingsVector header as a float
array, with the Embedding and the TextSegment in the
CamelLangChain4jEmbeddingsEmbedding and CamelLangChain4jEmbeddingsTextSegment
headers; a List body gives Lists of them in the
CamelLangChain4jEmbeddingsEmbeddings and CamelLangChain4jEmbeddingsTextSegments
headers instead" }
},
"properties": {
diff --git
a/components/camel-ai/camel-langchain4j-embeddings/src/main/docs/langchain4j-embeddings-component.adoc
b/components/camel-ai/camel-langchain4j-embeddings/src/main/docs/langchain4j-embeddings-component.adoc
index e77f65e70de6..827dce2e1255 100644
---
a/components/camel-ai/camel-langchain4j-embeddings/src/main/docs/langchain4j-embeddings-component.adoc
+++
b/components/camel-ai/camel-langchain4j-embeddings/src/main/docs/langchain4j-embeddings-component.adoc
@@ -229,11 +229,15 @@ YAML::
The body is the text to embed: a `String` or a LangChain4j `TextSegment`.
Bytes, a stream and a file (such as the
body of a `file` consumer) are read as text, so a `from("file:...")` route
needs no `convertBodyTo(String.class)`.
-A non-empty `List` of them is embedded in one batch.
+So is any other value Camel converts to its text, such as a `char[]`, a
`ByteBuffer`, a Netty `ByteBuf`, a number, or a
+type with its own type converter to `String`. A `UUID`, a `URI`, a `URL`, a
`java.time` value or a `Date` is also
+embedded, as its `toString()` is its text. A non-empty `List` of them is
embedded in one batch.
Any other body, or element of a `List` body, such as a `Map` or a POJO, fails
the exchange with an
-`InvalidPayloadException` instead of being embedded as its `toString()`: turn
it into text first, with
-`convertBodyTo(String.class)` or a marshal to JSON, say. No body fails too.
+`InvalidPayloadException` instead of being embedded as its `toString()`, since
that is all Camel reads of it. The rule
+is the text itself: a value fails when the text Camel gives for it is no more
than its `toString()`. Marshal such a
+body first, to JSON, say, or, when its `toString()` is the text to embed,
convert it with
+`convertBodyTo(String.class)`. No body fails too.
The body is kept. A single text sets the
`CamelLangChain4jEmbeddingsEmbedding`, `CamelLangChain4jEmbeddingsVector`
and `CamelLangChain4jEmbeddingsTextSegment` headers, and a `List` the
`CamelLangChain4jEmbeddingsEmbeddings` and
diff --git
a/components/camel-ai/camel-langchain4j-embeddings/src/main/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsEndpoint.java
b/components/camel-ai/camel-langchain4j-embeddings/src/main/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsEndpoint.java
index d6ed9610c61e..ec6edd074f6d 100644
---
a/components/camel-ai/camel-langchain4j-embeddings/src/main/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsEndpoint.java
+++
b/components/camel-ai/camel-langchain4j-embeddings/src/main/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsEndpoint.java
@@ -38,10 +38,11 @@ import org.apache.camel.support.DefaultEndpoint;
Category.AI
}, headersClass = LangChain4jEmbeddingsHeaders.class)
@BodyTypes(producerIn = @BodyType(value = { Carrier.TEXT, Carrier.BYTES,
Carrier.STREAM, Carrier.FILE, Carrier.LIST },
- description = "The text to embed: a String,
bytes, a stream or a file read as text, or a"
- + " LangChain4j TextSegment;
or a non-empty List of them to embed in one batch."
- + " Another body or List
element, such as a Map or a POJO, fails, as does no"
- + " body: convert it to text
first"),
+ description = "The text to embed: a String,
bytes, a stream, a file or another value"
+ + " Camel converts to its
text, such as a char[], or a LangChain4j"
+ + " TextSegment; or a
non-empty List of them to embed in one batch. A body or"
+ + " List element Camel reads
only as its toString(), such as a Map or a POJO,"
+ + " fails, as does no body:
marshal it first"),
producerOut = @BodyType(value = Carrier.UNCHANGED,
description = "The body is kept. The vector
goes in the CamelLangChain4jEmbeddingsVector"
+ " header as a float array,
with the Embedding and the TextSegment in the"
diff --git
a/components/camel-ai/camel-langchain4j-embeddings/src/main/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsProducer.java
b/components/camel-ai/camel-langchain4j-embeddings/src/main/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsProducer.java
index a27ef413a814..7756a0af757e 100644
---
a/components/camel-ai/camel-langchain4j-embeddings/src/main/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsProducer.java
+++
b/components/camel-ai/camel-langchain4j-embeddings/src/main/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsProducer.java
@@ -16,12 +16,6 @@
*/
package org.apache.camel.component.langchain4j.embeddings;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.io.Reader;
-import java.nio.ByteBuffer;
-import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -34,9 +28,7 @@ import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
import org.apache.camel.NoTypeConversionAvailableException;
-import org.apache.camel.StreamCache;
import org.apache.camel.TypeConverter;
-import org.apache.camel.WrappedFile;
import org.apache.camel.component.ai.observability.GenAiErrorSupport;
import org.apache.camel.component.ai.observability.GenAiModelResolver;
import org.apache.camel.component.ai.observability.GenAiObservability;
@@ -44,6 +36,7 @@ import
org.apache.camel.component.ai.observability.GenAiObservation;
import org.apache.camel.component.ai.observability.GenAiObservationContext;
import org.apache.camel.component.ai.observability.GenAiOperationName;
import org.apache.camel.component.ai.observability.GenAiUsage;
+import org.apache.camel.support.BodyFacts;
import org.apache.camel.support.DefaultProducer;
public class LangChain4jEmbeddingsProducer extends DefaultProducer {
@@ -138,9 +131,10 @@ public class LangChain4jEmbeddingsProducer extends
DefaultProducer {
/**
* Converts a body, or an element of a List body, to the TextSegment to
embed. A TextSegment is used as is, a type
- * converter to TextSegment is used when there is one, and text, bytes, a
stream, a Reader or a file is read as
- * text. Any other value, such as a Map or a POJO, fails as an
InvalidPayloadException instead of being embedded as
- * its toString().
+ * converter to TextSegment is used when there is one, and any other value
is embedded as the text Camel converts it
+ * to, such as text, bytes, a stream, a file, a char[] or a Netty ByteBuf.
A value Camel reads only as its
+ * toString(), such as a Map or a POJO, fails as an
InvalidPayloadException instead of being embedded as that
+ * toString() (CAMEL-26205, CAMEL-26553).
*
* @param index the index of the element in a List body, or -1 for the
body itself
*/
@@ -149,34 +143,33 @@ public class LangChain4jEmbeddingsProducer extends
DefaultProducer {
if (value instanceof TextSegment segment) {
return segment;
}
+ if (value == null) {
+ // only an element of a List body can be null: the body itself is
read with getMandatoryBody()
+ throw new InvalidPayloadException(
+ exchange, TextSegment.class, exchange.getMessage(),
+ "the element at index " + index + " of the List body is
null");
+ }
TypeConverter tc = exchange.getContext().getTypeConverter();
- TextSegment segment = value != null ?
tc.tryConvertTo(TextSegment.class, exchange, value) : null;
+ TextSegment segment = tc.tryConvertTo(TextSegment.class, exchange,
value);
if (segment != null) {
return segment;
}
- if (!isReadableAsText(value)) {
+ String text = tc.mandatoryConvertTo(String.class, exchange, value);
+ if (BodyFacts.isOnlyToString(value, text)) {
String what = index < 0
- ? "" : "the element at index " + index + " of the List
body is " + typeOf(value) + "; ";
+ ? "" : "the element at index " + index + " of the List
body is " + value.getClass().getName() + "; ";
throw new InvalidPayloadException(
exchange, TextSegment.class, exchange.getMessage(),
- what + "langchain4j-embeddings embeds text, bytes, a
stream, a Reader, a file or a TextSegment;"
- + "
convert the body to text before the endpoint,"
- + "
such as with convertBodyTo(String) or a marshal"
- + " to
JSON");
+ what + "langchain4j-embeddings embeds text, bytes, a
stream, a file, a TextSegment or another value"
+ + "
Camel converts to its text, such as a char[],"
+ + "
but Camel reads this value only as its"
+ + "
toString(); marshal it first, such as with"
+ + "
marshal().json(), or, when its toString() is"
+ + "
the text to embed, convert the body to text"
+ + "
before the endpoint with"
+ + "
convertBodyTo(String.class)");
}
- return TextSegment.from(tc.mandatoryConvertTo(String.class, exchange,
value));
- }
-
- /** A value Camel converts to its text, rather than to the toString() of
an object. */
- private static boolean isReadableAsText(Object value) {
- return value instanceof CharSequence || value instanceof byte[] ||
value instanceof ByteBuffer
- || value instanceof InputStream || value instanceof Reader ||
value instanceof StreamCache
- || value instanceof ByteArrayOutputStream
- || value instanceof File || value instanceof Path || value
instanceof WrappedFile;
- }
-
- private static String typeOf(Object value) {
- return value == null ? "null" : value.getClass().getName();
+ return TextSegment.from(text);
}
/**
diff --git
a/components/camel-ai/camel-langchain4j-embeddings/src/test/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsBodyTest.java
b/components/camel-ai/camel-langchain4j-embeddings/src/test/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsBodyTest.java
index 0dc0f48d281d..b903bfcbfd10 100644
---
a/components/camel-ai/camel-langchain4j-embeddings/src/test/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsBodyTest.java
+++
b/components/camel-ai/camel-langchain4j-embeddings/src/test/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddingsBodyTest.java
@@ -17,10 +17,14 @@
package org.apache.camel.component.langchain4j.embeddings;
import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.InputStream;
+import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
@@ -30,8 +34,10 @@ import org.apache.camel.CamelExecutionException;
import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
+import org.apache.camel.TypeConversionException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.support.TypeConverterSupport;
import org.apache.camel.test.junit6.CamelTestSupport;
import org.apache.camel.util.IOHelper;
import org.junit.jupiter.api.Test;
@@ -57,6 +63,13 @@ class LangChain4jEmbeddingsBodyTest extends CamelTestSupport
{
= context.getComponent(LangChain4jEmbeddings.SCHEME,
LangChain4jEmbeddingsComponent.class);
component.getConfiguration().setEmbeddingModel(new
AllMiniLmL6V2EmbeddingModel());
+ context.getTypeConverterRegistry().addTypeConverter(String.class,
Headline.class, new TypeConverterSupport() {
+ @Override
+ public <T> T convertTo(Class<T> type, Exchange exchange, Object
value) throws TypeConversionException {
+ return type.cast(((Headline) value).text());
+ }
+ });
+
return context;
}
@@ -137,6 +150,84 @@ class LangChain4jEmbeddingsBodyTest extends
CamelTestSupport {
assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.EMBEDDINGS,
List.class)).hasSize(3);
}
+ @Test
+ void charArrayBodyIsEmbeddedAsText() {
+ Message result = embed("hello chars".toCharArray());
+
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENT,
TextSegment.class).text())
+ .isEqualTo("hello chars");
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.EMBEDDING,
Embedding.class)).isNotNull();
+ }
+
+ @Test
+ void byteBufferBodyIsEmbeddedAsText() {
+ Message result = embed(ByteBuffer.wrap("hello
buffer".getBytes(StandardCharsets.UTF_8)));
+
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENT,
TextSegment.class).text())
+ .isEqualTo("hello buffer");
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.EMBEDDING,
Embedding.class)).isNotNull();
+ }
+
+ @Test
+ void byteArrayOutputStreamBodyIsEmbeddedAsText() {
+ Message result = embed(outputStreamOf("parsed by tika"));
+
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENT,
TextSegment.class).text())
+ .isEqualTo("parsed by tika");
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.EMBEDDING,
Embedding.class)).isNotNull();
+ }
+
+ @Test
+ void batchWithAByteArrayOutputStreamElementIsEmbeddedAsText() {
+ Message result = embed(List.of("from a string", outputStreamOf("from
an output stream")));
+
+ List<TextSegment> segments =
result.getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENTS, List.class);
+
assertThat(segments).extracting(TextSegment::text).containsExactly("from a
string", "from an output stream");
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.EMBEDDINGS,
List.class)).hasSize(2);
+ }
+
+ @Test
+ void bodyWithItsOwnConverterToStringIsEmbeddedAsText() {
+ Message result = embed(new Headline("Camel 4.24 released"));
+
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENT,
TextSegment.class).text())
+ .isEqualTo("Camel 4.24 released");
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.EMBEDDING,
Embedding.class)).isNotNull();
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void batchWithACharArrayElementIsEmbeddedAsText() {
+ Message result = embed(List.of("from a string", "from
chars".toCharArray()));
+
+ List<TextSegment> segments =
result.getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENTS, List.class);
+
assertThat(segments).extracting(TextSegment::text).containsExactly("from a
string", "from chars");
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.EMBEDDINGS,
List.class)).hasSize(2);
+ }
+
+ @Test
+ void uuidBodyIsEmbeddedAsItsText() {
+ UUID uuid = UUID.randomUUID();
+
+ Message result = embed(uuid);
+
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENT,
TextSegment.class).text())
+ .isEqualTo(uuid.toString());
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void numberBodyAndNumberElementAreEmbeddedAsText() {
+ Message result = embed(42);
+
+ assertThat(result.getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENT,
TextSegment.class).text()).isEqualTo("42");
+
+ result = embed(List.of("hello", 42));
+
+ List<TextSegment> segments =
result.getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENTS, List.class);
+
assertThat(segments).extracting(TextSegment::text).containsExactly("hello",
"42");
+ }
+
@Test
void noBodyFails() {
assertThatThrownBy(() ->
template.requestBody("langchain4j-embeddings:test", (Object) null))
@@ -149,7 +240,9 @@ class LangChain4jEmbeddingsBodyTest extends
CamelTestSupport {
Exchange exchange = send(Map.of("text", "hello map"));
assertThat(exchange.getException()).isInstanceOf(InvalidPayloadException.class)
- .hasMessageContaining("convert the body to text");
+ .hasMessageContaining("Camel reads this value only as its
toString()")
+ .hasMessageContaining("marshal it first")
+ .hasMessageContaining("convertBodyTo(String.class)");
assertThat(exchange.getMessage().getHeader(LangChain4jEmbeddingsHeaders.EMBEDDING)).isNull();
assertThat(exchange.getMessage().getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENT)).isNull();
}
@@ -159,7 +252,9 @@ class LangChain4jEmbeddingsBodyTest extends
CamelTestSupport {
Exchange exchange = send(new Note("hello pojo"));
assertThat(exchange.getException()).isInstanceOf(InvalidPayloadException.class)
- .hasMessageContaining("convert the body to text");
+ .hasMessageContaining("Camel reads this value only as its
toString()")
+ .hasMessageContaining("marshal it first")
+ .hasMessageContaining("convertBodyTo(String.class)");
assertThat(exchange.getMessage().getHeader(LangChain4jEmbeddingsHeaders.EMBEDDING)).isNull();
assertThat(exchange.getMessage().getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENT)).isNull();
}
@@ -175,6 +270,16 @@ class LangChain4jEmbeddingsBodyTest extends
CamelTestSupport {
assertThat(exchange.getMessage().getHeader(LangChain4jEmbeddingsHeaders.TEXT_SEGMENTS)).isNull();
}
+ @Test
+ void batchWithANullElementFails() {
+ Exchange exchange = send(Arrays.asList("hello", null));
+
+
assertThat(exchange.getException()).isInstanceOf(InvalidPayloadException.class)
+ .hasMessageContaining("the element at index 1 of the List body
is null")
+ .hasMessageNotContaining("marshal it first");
+
assertThat(exchange.getMessage().getHeader(LangChain4jEmbeddingsHeaders.EMBEDDINGS)).isNull();
+ }
+
@Test
void singleAfterBatchRemovesTheBatchHeaders() {
Message result = fluentTemplate.to("direct:batchThenSingle")
@@ -220,9 +325,19 @@ class LangChain4jEmbeddingsBodyTest extends
CamelTestSupport {
private record Note(String text) {
}
+ /** A type with its own converter to String, registered on the context,
whose toString() is not its text. */
+ private record Headline(String text) {
+ }
+
private Message embed(Object body) {
return fluentTemplate.to("langchain4j-embeddings:test")
.withBody(body)
.request(Message.class);
}
+
+ private static ByteArrayOutputStream outputStreamOf(String text) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ out.writeBytes(text.getBytes(StandardCharsets.UTF_8));
+ return out;
+ }
}
diff --git
a/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSUtils.java
b/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSUtils.java
index 71817a953024..404565b5eaf1 100644
---
a/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSUtils.java
+++
b/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSUtils.java
@@ -16,16 +16,10 @@
*/
package org.apache.camel.component.alibaba.kms;
-import java.net.URI;
-import java.net.URL;
import java.nio.charset.StandardCharsets;
-import java.time.temporal.Temporal;
-import java.time.temporal.TemporalAmount;
import java.util.Base64;
-import java.util.Date;
import java.util.HashMap;
import java.util.Map;
-import java.util.UUID;
import com.aliyun.kms20160120.Client;
import com.aliyun.kms20160120.models.DecryptResponse;
@@ -41,7 +35,6 @@ import
org.apache.camel.component.alibaba.common.models.ServiceKeys;
import org.apache.camel.component.alibaba.kms.constants.KMSOperations;
import org.apache.camel.component.alibaba.kms.constants.KMSProperties;
import org.apache.camel.component.alibaba.kms.models.ClientConfigurations;
-import org.apache.camel.spi.BodyTypeRegistry;
import org.apache.camel.support.BodyFacts;
import org.apache.camel.util.ObjectHelper;
@@ -116,8 +109,7 @@ public final class KMSUtils {
return null;
}
String text =
exchange.getContext().getTypeConverter().convertTo(String.class, exchange,
value);
- if (text != null && BodyFacts.kindOf(value) !=
BodyTypeRegistry.Kind.PAYLOAD && !isTextValue(value)
- && text.equals(value.toString())) {
+ if (text != null && BodyFacts.isOnlyToString(value, text)) {
throw new IllegalArgumentException(
"The " + KMSProperties.PLAINTEXT + " " + where + " must be
the plaintext as text, but it is a "
+ value.getClass().getName()
@@ -127,17 +119,6 @@ public final class KMSUtils {
return text;
}
- /**
- * A value whose toString() is its text, rather than a dump of its fields:
an id, an address or a point in time.
- * BodyFacts counts text, a number, a boolean and an enum as a payload,
but not these, and the type converter has
- * nothing for them either, so they would otherwise be read as only a
toString() (raised in the review of
- * CAMEL-26521, which uses the same rule).
- */
- private static boolean isTextValue(Object value) {
- return value instanceof UUID || value instanceof URI || value
instanceof URL || value instanceof Temporal
- || value instanceof TemporalAmount || value instanceof Date;
- }
-
/**
* The number of bytes of the numberOfBytes header, of the exchange
property of the same name, or of the
* numberOfBytes option, in that order. Only generateDataKey calls this,
so a value that no other operation reads
diff --git
a/components/camel-ibm/camel-ibm-watsonx-ai/src/main/java/org/apache/camel/component/ibm/watsonx/ai/handler/AbstractWatsonxAiHandler.java
b/components/camel-ibm/camel-ibm-watsonx-ai/src/main/java/org/apache/camel/component/ibm/watsonx/ai/handler/AbstractWatsonxAiHandler.java
index 0fcedc232edc..bfc570ac1be7 100644
---
a/components/camel-ibm/camel-ibm-watsonx-ai/src/main/java/org/apache/camel/component/ibm/watsonx/ai/handler/AbstractWatsonxAiHandler.java
+++
b/components/camel-ibm/camel-ibm-watsonx-ai/src/main/java/org/apache/camel/component/ibm/watsonx/ai/handler/AbstractWatsonxAiHandler.java
@@ -18,14 +18,8 @@ package org.apache.camel.component.ibm.watsonx.ai.handler;
import java.io.File;
import java.io.InputStream;
-import java.net.URI;
-import java.net.URL;
-import java.time.temporal.Temporal;
-import java.time.temporal.TemporalAmount;
import java.util.ArrayList;
-import java.util.Date;
import java.util.List;
-import java.util.UUID;
import com.ibm.watsonx.ai.chat.model.ChatMessage;
import com.ibm.watsonx.ai.chat.model.ChatParameters;
@@ -39,7 +33,6 @@ import
org.apache.camel.component.ibm.watsonx.ai.WatsonxAiConfiguration;
import org.apache.camel.component.ibm.watsonx.ai.WatsonxAiConstants;
import org.apache.camel.component.ibm.watsonx.ai.WatsonxAiEndpoint;
import org.apache.camel.component.ibm.watsonx.ai.support.FileInput;
-import org.apache.camel.spi.BodyTypeRegistry;
import org.apache.camel.support.BodyFacts;
/**
@@ -232,7 +225,7 @@ public abstract class AbstractWatsonxAiHandler implements
WatsonxAiOperationHand
protected static String readAsText(Message in, String what) {
Object body = in.getBody();
String text = in.getBody(String.class);
- if (text != null && isOnlyToString(body, text)) {
+ if (text != null && BodyFacts.isOnlyToString(body, text)) {
throw new IllegalArgumentException(
"The message body must be " + what + " as text (a String,
bytes, a stream or a file), but it is a "
+ body.getClass().getName()
@@ -244,27 +237,6 @@ public abstract class AbstractWatsonxAiHandler implements
WatsonxAiOperationHand
return text;
}
- /**
- * Whether the text is no more than the {@code toString()} of the body,
which {@code ToStringTypeConverter} gives
- * for an object no type converter reads as text. A payload (text, bytes,
a stream, a file) or a single value (a
- * number, a boolean) is text by itself, whatever its {@code toString()}.
- */
- private static boolean isOnlyToString(Object body, String text) {
- return BodyFacts.kindOf(body) != BodyTypeRegistry.Kind.PAYLOAD &&
!isTextValue(body)
- && text.equals(body.toString());
- }
-
- /**
- * A value whose {@code toString()} is its text, rather than a dump of its
fields: an id, an address or a point in
- * time. {@link BodyFacts} counts text, a number, a boolean and an enum as
a payload, but not these, and the type
- * converter has nothing for them either, so they would otherwise be read
as only a {@code toString()} (raised in
- * the review of CAMEL-26521).
- */
- private static boolean isTextValue(Object body) {
- return body instanceof UUID || body instanceof URI || body instanceof
URL || body instanceof Temporal
- || body instanceof TemporalAmount || body instanceof Date;
- }
-
/**
* Extracts file/stream from message body, supporting Camel file
components.
*/
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/generated/resources/META-INF/org/apache/camel/component/springai/embeddings/spring-ai-embeddings.json
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/generated/resources/META-INF/org/apache/camel/component/springai/embeddings/spring-ai-embeddings.json
index 4c2815e8c576..7ad672a23558 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/generated/resources/META-INF/org/apache/camel/component/springai/embeddings/spring-ai-embeddings.json
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/generated/resources/META-INF/org/apache/camel/component/springai/embeddings/spring-ai-embeddings.json
@@ -38,7 +38,7 @@
"CamelSpringAiEmbeddingInputTexts": { "index": 5, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.List<String>", "deprecated": false, "autowired": false,
"secret": false, "description": "List of input texts that were embedded",
"constantName":
"org.apache.camel.component.springai.embeddings.SpringAiEmbeddingsHeaders#INPUT_TEXTS"
}
},
"bodyTypes": {
- "producerIn": { "carriers": [ "text", "bytes", "stream", "file", "list" ],
"description": "The text to embed: a String, bytes, a stream or a file read as
text, or a Spring AI Document as its text; or a java.util.List of them for a
batch (a Set or an array of them fails). Another body or List element, such as
a Map or a POJO, fails, as do no body and a null element: convert it to text
first" },
+ "producerIn": { "carriers": [ "text", "bytes", "stream", "file", "list" ],
"description": "The text to embed: a String, bytes, a stream, a file or another
value Camel converts to its text, such as a char[], or a Spring AI Document as
its text; or a java.util.List of them for a batch (a Set or an array of them
fails). A body or List element Camel reads only as its toString(), such as a
Map or a POJO, fails, as do no body and a null element: marshal it first" },
"producerOut": { "carriers": [ "list" ], "description": "The vector as a
float[] for one text, and a List of float[] for a List of texts, also for a
List with one text or none. The Embedding and the input text are in headers,
which spring-ai-vector-store reads" }
},
"properties": {
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/docs/spring-ai-embeddings-component.adoc
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/docs/spring-ai-embeddings-component.adoc
index a2036cd24c7f..8dc3b5b2d381 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/docs/spring-ai-embeddings-component.adoc
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/docs/spring-ai-embeddings-component.adoc
@@ -50,11 +50,16 @@ The component accepts two types of input:
* **Single text**: A String containing the text to embed
* **Batch processing**: A List<String> containing multiple texts to embed at
once
-Bytes, a stream, a `Reader` or a file is read as text, and a Spring AI
`Document` is embedded as its text, as a body
-and as an element of a List. Any other body or List element, such as a `Map`,
a POJO or a number, fails the exchange
-with an `InvalidPayloadException` instead of being embedded as its
`toString()`: turn it into text first, with
-`convertBodyTo(String.class)` or a marshal to JSON, say. No body, or a `null`
element in a List, fails the exchange
-with an `IllegalArgumentException`.
+Bytes, a stream, a `Reader` or a file is read as text, and so is any other
value Camel converts to its text, such as
+a `char[]`, a `ByteBuffer`, a Netty `ByteBuf`, a number or a type with its own
type converter to `String`. A `UUID`, a
+`URI`, a `URL`, a `java.time` value or a `Date` is embedded as its
`toString()`, which is its text, and a Spring AI
+`Document` as its text. This holds for the body and for each element of a List.
+
+Any other body or List element, such as a `Map` or a POJO, fails the exchange
with an `InvalidPayloadException`
+instead of being embedded as its `toString()`, since that is all Camel reads
of it. The rule is the text itself: a
+value fails when the text Camel gives for it is no more than its `toString()`.
Marshal such a body first, to JSON, say,
+or, when its `toString()` is the text to embed, convert it with
`convertBodyTo(String.class)`. No body, or a `null`
+element in a List, fails the exchange with an `IllegalArgumentException`.
The embedding vectors are returned in the message body, with additional
metadata available in headers.
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsEndpoint.java
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsEndpoint.java
index 3276d8b93391..26255a479f74 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsEndpoint.java
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsEndpoint.java
@@ -38,11 +38,12 @@ import org.apache.camel.support.DefaultEndpoint;
Category.AI
}, headersClass = SpringAiEmbeddingsHeaders.class)
@BodyTypes(producerIn = @BodyType(value = { Carrier.TEXT, Carrier.BYTES,
Carrier.STREAM, Carrier.FILE, Carrier.LIST },
- description = "The text to embed: a String,
bytes, a stream or a file read as text, or a"
- + " Spring AI Document as its
text; or a java.util.List of them for a batch (a"
- + " Set or an array of them
fails). Another body or List element, such as a"
- + " Map or a POJO, fails, as
do no body and a null element: convert it to"
- + " text first"),
+ description = "The text to embed: a String,
bytes, a stream, a file or another value"
+ + " Camel converts to its
text, such as a char[], or a Spring AI Document as"
+ + " its text; or a
java.util.List of them for a batch (a Set or an array of"
+ + " them fails). A body or
List element Camel reads only as its toString(),"
+ + " such as a Map or a POJO,
fails, as do no body and a null element:"
+ + " marshal it first"),
producerOut = @BodyType(value = Carrier.LIST,
description = "The vector as a float[] for
one text, and a List of float[] for a List"
+ " of texts, also for a List
with one text or none. The Embedding and"
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsProducer.java
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsProducer.java
index 4f9d1bbda7d6..a5a54dff29e3 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsProducer.java
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsProducer.java
@@ -16,12 +16,6 @@
*/
package org.apache.camel.component.springai.embeddings;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.io.Reader;
-import java.nio.ByteBuffer;
-import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -29,8 +23,7 @@ import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
import org.apache.camel.NoTypeConversionAvailableException;
-import org.apache.camel.StreamCache;
-import org.apache.camel.WrappedFile;
+import org.apache.camel.support.BodyFacts;
import org.apache.camel.support.DefaultProducer;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.Embedding;
@@ -114,9 +107,10 @@ public class SpringAiEmbeddingsProducer extends
DefaultProducer {
}
/**
- * The text to embed of a body, or of an element of a List body: a Spring
AI Document as its text, and text, bytes,
- * a stream, a Reader or a file read as text. Any other value, such as a
Map or a POJO, fails as an
- * InvalidPayloadException instead of being embedded as its toString().
+ * The text to embed of a body, or of an element of a List body: a Spring
AI Document as its text, and any other
+ * value as the text Camel converts it to, such as text, bytes, a stream,
a file, a char[] or a Netty ByteBuf. A
+ * value Camel reads only as its toString(), such as a Map or a POJO,
fails as an InvalidPayloadException instead of
+ * being embedded as that toString() (CAMEL-26512, CAMEL-26553).
*
* @param index the index of the element in a List body, or -1 for the
body itself
*/
@@ -131,23 +125,19 @@ public class SpringAiEmbeddingsProducer extends
DefaultProducer {
}
return document.getText();
}
- if (!isReadableAsText(value)) {
+ String text =
exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class,
exchange, value);
+ if (BodyFacts.isOnlyToString(value, text)) {
throw new InvalidPayloadException(
exchange, String.class, exchange.getMessage(),
- listElement(value,
- index) + "spring-ai-embeddings embeds text, bytes,
a stream, a Reader, a file or a Spring AI Document;"
- + " convert
the body to text before the endpoint, such"
- + " as with
convertBodyTo(String) or a marshal to JSON");
+ listElement(value, index) + "spring-ai-embeddings embeds
text, bytes, a stream, a file, a Spring AI"
+ + "
Document or another value Camel converts to its text,"
+ + " such as
a char[], but Camel reads this value only as its"
+ + "
toString(); marshal it first, such as with"
+ + "
marshal().json(), or, when its toString() is the text to"
+ + " embed,
convert the body to text before the endpoint with"
+ + "
convertBodyTo(String.class)");
}
- return
exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class,
exchange, value);
- }
-
- /** A value Camel converts to its text, rather than to the toString() of
an object. */
- private static boolean isReadableAsText(Object value) {
- return value instanceof CharSequence || value instanceof byte[] ||
value instanceof ByteBuffer
- || value instanceof InputStream || value instanceof Reader ||
value instanceof StreamCache
- || value instanceof ByteArrayOutputStream
- || value instanceof File || value instanceof Path || value
instanceof WrappedFile;
+ return text;
}
/**
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/test/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsComponentTest.java
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/test/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsComponentTest.java
index aa4222f0117f..7582cb017cb5 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/test/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsComponentTest.java
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/test/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsComponentTest.java
@@ -17,20 +17,25 @@
package org.apache.camel.component.springai.embeddings;
import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.net.URI;
+import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
+import org.apache.camel.TypeConversionException;
import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.support.TypeConverterSupport;
import org.apache.camel.test.junit6.CamelTestSupport;
import org.junit.jupiter.api.Test;
import org.springframework.ai.content.Media;
@@ -91,6 +96,13 @@ public class SpringAiEmbeddingsComponentTest extends
CamelTestSupport {
component.getConfiguration().setEmbeddingModel(embeddingModel);
+ context.getTypeConverterRegistry().addTypeConverter(String.class,
Headline.class, new TypeConverterSupport() {
+ @Override
+ public <T> T convertTo(Class<T> type, Exchange exchange, Object
value) throws TypeConversionException {
+ return type.cast(((Headline) value).text());
+ }
+ });
+
return context;
}
@@ -238,7 +250,9 @@ public class SpringAiEmbeddingsComponentTest extends
CamelTestSupport {
assertThat(exchange.getException())
.isInstanceOf(InvalidPayloadException.class)
- .hasMessageContaining("convert the body to text before the
endpoint");
+ .hasMessageContaining("Camel reads this value only as its
toString()")
+ .hasMessageContaining("marshal it first")
+ .hasMessageContaining("convertBodyTo(String.class)");
assertThat(requests).isEmpty();
}
@@ -249,7 +263,9 @@ public class SpringAiEmbeddingsComponentTest extends
CamelTestSupport {
assertThat(exchange.getException())
.isInstanceOf(InvalidPayloadException.class)
- .hasMessageContaining("convert the body to text before the
endpoint");
+ .hasMessageContaining("Camel reads this value only as its
toString()")
+ .hasMessageContaining("marshal it first")
+ .hasMessageContaining("convertBodyTo(String.class)");
assertThat(requests).isEmpty();
}
@@ -266,41 +282,101 @@ public class SpringAiEmbeddingsComponentTest extends
CamelTestSupport {
}
@Test
- public void testListWithNumberElementFails() {
- Exchange exchange = template.send("spring-ai-embeddings:listnumber",
- e -> e.getMessage().setBody(List.of("hello", 42)));
+ public void testListWithNumberElementIsEmbeddedAsText() {
+ fluentTemplate.to("spring-ai-embeddings:listnumber")
+ .withBody(List.of("hello", 42))
+ .request(Message.class);
- assertThat(exchange.getException())
- .isInstanceOf(InvalidPayloadException.class)
- .hasMessageContaining("the element at index 1 of the List body
is java.lang.Integer");
- assertThat(requests).isEmpty();
+ assertThat(requests).containsExactly(List.of("hello", "42"));
}
@Test
- public void testCharArrayBodyFailsAndConvertBodyToStringEmbedsIt() throws
Exception {
- // the upgrade guide: a body Camel converts to text but that is not
text, bytes, a stream or a file, such as a
- // char[], fails; convertBodyTo(String.class) before the endpoint
embeds its text
- Exchange exchange = template.send("spring-ai-embeddings:chars",
- e -> e.getMessage().setBody("hello".toCharArray()));
+ public void testCharArrayBodyIsEmbeddedAsText() {
+ Message result = fluentTemplate.to("spring-ai-embeddings:chars")
+ .withBody("hello".toCharArray())
+ .request(Message.class);
- assertThat(exchange.getException())
- .isInstanceOf(InvalidPayloadException.class)
- .hasMessageContaining("convert the body to text before the
endpoint");
- assertThat(requests).isEmpty();
+ assertThat(requests).containsExactly(List.of("hello"));
+
assertThat(result.getHeader(SpringAiEmbeddingsHeaders.INPUT_TEXT)).isEqualTo("hello");
+ }
+
+ @Test
+ public void testByteBufferBodyIsEmbeddedAsText() {
+ Message result = fluentTemplate.to("spring-ai-embeddings:buffer")
+ .withBody(ByteBuffer.wrap("buffered
text".getBytes(StandardCharsets.UTF_8)))
+ .request(Message.class);
+
+ assertThat(requests).containsExactly(List.of("buffered text"));
+
assertThat(result.getHeader(SpringAiEmbeddingsHeaders.INPUT_TEXT)).isEqualTo("buffered
text");
+ }
+
+ @Test
+ public void testByteArrayOutputStreamBodyIsEmbeddedAsText() {
+ Message result = fluentTemplate.to("spring-ai-embeddings:baos")
+ .withBody(outputStreamOf("parsed by tika"))
+ .request(Message.class);
+
+ assertThat(requests).containsExactly(List.of("parsed by tika"));
+
assertThat(result.getHeader(SpringAiEmbeddingsHeaders.INPUT_TEXT)).isEqualTo("parsed
by tika");
+ }
+ @Test
+ public void testListWithByteArrayOutputStreamElementIsEmbeddedAsText() {
+ Message result = fluentTemplate.to("spring-ai-embeddings:listbaos")
+ .withBody(List.of("hello", outputStreamOf("world")))
+ .request(Message.class);
+
+ assertThat(requests).containsExactly(List.of("hello", "world"));
+ assertThat(result.getBody(List.class)).hasSize(2);
+ }
+
+ @Test
+ public void testBodyWithItsOwnConverterToStringIsEmbeddedAsText() {
+ Message result = fluentTemplate.to("spring-ai-embeddings:headline")
+ .withBody(new Headline("Camel 4.24 released"))
+ .request(Message.class);
+
+ assertThat(requests).containsExactly(List.of("Camel 4.24 released"));
+
assertThat(result.getHeader(SpringAiEmbeddingsHeaders.INPUT_TEXT)).isEqualTo("Camel
4.24 released");
+ }
+
+ @Test
+ public void testListWithCharArrayElementIsEmbeddedAsText() {
+ Message result = fluentTemplate.to("spring-ai-embeddings:listchars")
+ .withBody(List.of("hello", "world".toCharArray()))
+ .request(Message.class);
+
+ assertThat(requests).containsExactly(List.of("hello", "world"));
+ assertThat(result.getBody(List.class)).hasSize(2);
+ }
+
+ @Test
+ public void testUuidBodyIsEmbeddedAsItsText() {
+ UUID uuid = UUID.randomUUID();
+
+ Message result = fluentTemplate.to("spring-ai-embeddings:uuid")
+ .withBody(uuid)
+ .request(Message.class);
+
+ assertThat(requests).containsExactly(List.of(uuid.toString()));
+
assertThat(result.getHeader(SpringAiEmbeddingsHeaders.INPUT_TEXT)).isEqualTo(uuid.toString());
+ }
+
+ @Test
+ public void testConvertBodyToStringEmbedsThePojoToString() throws
Exception {
+ // the way out the message of a POJO body gives, when its toString()
is the text to embed
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
- from("direct:chars")
+ from("direct:pojo")
.convertBodyTo(String.class)
- .to("spring-ai-embeddings:chars");
+ .to("spring-ai-embeddings:pojo");
}
});
- Message result =
fluentTemplate.to("direct:chars").withBody("hello".toCharArray()).request(Message.class);
+ fluentTemplate.to("direct:pojo").withBody(new
Pojo("hello")).request(Message.class);
- assertThat(requests).containsExactly(List.of("hello"));
-
assertThat(result.getHeader(SpringAiEmbeddingsHeaders.INPUT_TEXT)).isEqualTo("hello");
+ assertThat(requests).containsExactly(List.of("Pojo[text=hello]"));
}
@Test
@@ -349,6 +425,10 @@ public class SpringAiEmbeddingsComponentTest extends
CamelTestSupport {
assertThat(requests).isEmpty();
}
+ /** A type with its own converter to String, registered on the context,
whose toString() is not its text. */
+ private record Headline(String text) {
+ }
+
private static final class Pojo {
private final String text;
@@ -361,4 +441,10 @@ public class SpringAiEmbeddingsComponentTest extends
CamelTestSupport {
return "Pojo[text=" + text + "]";
}
}
+
+ private static ByteArrayOutputStream outputStreamOf(String text) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ out.writeBytes(text.getBytes(StandardCharsets.UTF_8));
+ return out;
+ }
}
diff --git
a/core/camel-core/src/test/java/org/apache/camel/support/BodyFactsTest.java
b/core/camel-core/src/test/java/org/apache/camel/support/BodyFactsTest.java
index ed4a9e34834b..bda4dff8014a 100644
--- a/core/camel-core/src/test/java/org/apache/camel/support/BodyFactsTest.java
+++ b/core/camel-core/src/test/java/org/apache/camel/support/BodyFactsTest.java
@@ -20,7 +20,9 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
+import java.net.URI;
import java.nio.charset.StandardCharsets;
+import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -31,6 +33,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
+import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.camel.CamelContext;
@@ -44,6 +47,7 @@ import org.apache.camel.support.service.ServiceSupport;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -256,6 +260,29 @@ public class BodyFactsTest extends ContextTestSupport {
assertEquals("data.json", BodyFacts.dataFile(null));
}
+ @Test
+ public void testOnlyTheToStringOfAValue() {
+ // the text ToStringTypeConverter gives for a Map or an object
+ Map<String, Object> map = new LinkedHashMap<>(Map.of("id", 1));
+ assertTrue(BodyFacts.isOnlyToString(map, map.toString()));
+ Object object = new Object();
+ assertTrue(BodyFacts.isOnlyToString(object, object.toString()));
+ // a payload or a single value is text by itself
+ assertFalse(BodyFacts.isOnlyToString("text", "text"));
+ assertFalse(BodyFacts.isOnlyToString(42, "42"));
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ bytes.writeBytes("parsed".getBytes(StandardCharsets.UTF_8));
+ assertFalse(BodyFacts.isOnlyToString(bytes, "parsed"));
+ // an id, an address or a point in time, whose toString() is its text
+ UUID uuid = UUID.randomUUID();
+ assertFalse(BodyFacts.isOnlyToString(uuid, uuid.toString()));
+
assertFalse(BodyFacts.isOnlyToString(URI.create("https://camel.apache.org"),
"https://camel.apache.org"));
+ assertFalse(BodyFacts.isOnlyToString(Instant.EPOCH,
Instant.EPOCH.toString()));
+ // a real converter, which gives other text than toString()
+ char[] chars = "text".toCharArray();
+ assertFalse(BodyFacts.isOnlyToString(chars, "text"));
+ }
+
@Test
public void testTheKindOfABody() {
assertEquals(Kind.NULL, BodyFacts.kindOf(null));
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/BodyFacts.java
b/core/camel-support/src/main/java/org/apache/camel/support/BodyFacts.java
index 144cf3b5f87d..b2ac2ecebff0 100644
--- a/core/camel-support/src/main/java/org/apache/camel/support/BodyFacts.java
+++ b/core/camel-support/src/main/java/org/apache/camel/support/BodyFacts.java
@@ -21,15 +21,21 @@ import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Modifier;
+import java.net.URI;
+import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
+import java.time.temporal.Temporal;
+import java.time.temporal.TemporalAmount;
import java.util.Collection;
+import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
+import java.util.UUID;
import java.util.stream.BaseStream;
import java.util.stream.Collectors;
@@ -632,6 +638,33 @@ public final class BodyFacts {
return BodyTypeRegistry.Kind.DATA;
}
+ /**
+ * Whether the text a type converter gave for a value is no more than the
toString() of the value, which is what
+ * ToStringTypeConverter, the fallback that is never promoted, gives for
an object no other converter reads as text,
+ * such as a Map or a POJO. Asking the type converter for its converter
does not tell them apart, as the registry
+ * caches that fallback for the pair of types after the first conversion,
so a step that reads a value as text
+ * compares the text instead, and fails rather than send the toString() of
an object.
+ * <p>
+ * A payload (text, bytes, a stream, a file) or a single value (a number,
a boolean, an enum) is text by itself,
+ * whatever its toString(), and so is an id, an address or a point in time
(a UUID, URI, URL, java.time value or
+ * Date), whose toString() is its text and which no type converter reads
otherwise. A value with a real converter to
+ * text whose text happens to equal its toString() counts as only a
toString() too: a step that rejects it should
+ * name convertBodyTo(String.class) as the way to send that text.
+ *
+ * @param value the value, not null
+ * @param text the text the type converter gave for the value
+ * @return true when the text is no more than value.toString()
+ */
+ public static boolean isOnlyToString(Object value, String text) {
+ return kindOf(value) != BodyTypeRegistry.Kind.PAYLOAD &&
!isTextValue(value) && text.equals(value.toString());
+ }
+
+ /** A value whose toString() is its text, rather than a dump of its
fields: an id, an address or a point in time. */
+ private static boolean isTextValue(Object value) {
+ return value instanceof UUID || value instanceof URI || value
instanceof URL || value instanceof Temporal
+ || value instanceof TemporalAmount || value instanceof Date;
+ }
+
/**
* The payload in its serialized form: text, bytes, a stream or a file. A
ByteArrayOutputStream, which camel-tika
* parse puts in the body, holds the bytes written to it, and converts to
bytes, a stream or text as they do.
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 529c70b439f7..ff248526693f 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -3825,16 +3825,16 @@ Each element of a `List` body is now read as text, and
a `null` element fails wi
Before, a `List` of other objects failed with a `ClassCastException` in the
embedding model. An empty `List` now gives
an empty `List` without calling the embedding model.
-The body, and each element of a `List` body, must now be text, bytes, a
stream, a `Reader`, a file or a Spring AI
-`Document` (its text is embedded). Any other value, such as a `Map`, a POJO or
a number, fails the exchange with an
-`InvalidPayloadException`. Before, such a body was embedded as its
`toString()`, for example `{a=1, b=2}`, and a
-`Document` too. Convert the body to text before the endpoint, with
`convertBodyTo(String.class)` or a marshal to JSON.
-
-This also applies to bodies that Camel can convert to text but that are not in
the list above, and that were embedded
-as their text before: a `char[]`, a Netty `ByteBuf` (for example from
netty-http with `disableStreamCache=true`), and a
-custom type with its own type converter to `String`. A `List` with such an
element fails too, as do a `Set` and an
-array of texts (only a `java.util.List` is embedded as a batch). Add
`convertBodyTo(String.class)` before the
-endpoint for such a body, or convert each element of the `List` to a `String`.
+A Spring AI `Document` body, or `List` element, is now embedded as its text.
Before, it was embedded as its
+`toString()`.
+
+A body, or element of a `List` body, that Camel reads only as its
`toString()`, such as a `Map` or a POJO, now fails
+the exchange with an `InvalidPayloadException`. Before, it was embedded as
that `toString()`, for example `{a=1, b=2}`.
+Marshal such a body before the endpoint, to JSON for example, or, when its
`toString()` is the text to embed, add
+`convertBodyTo(String.class)`. A `Set` and an array of texts fail too, as only
a `java.util.List` is embedded as a
+batch. A body that Camel converts to its text is still embedded as that text:
text, bytes, a stream, a `Reader`, a
+file, a `char[]`, a Netty `ByteBuf` (for example from netty-http with
`disableStreamCache=true`), a number, a custom
+type with its own type converter to `String`, and a `UUID`, a `URI`, a `URL`,
a `java.time` value or a `Date`.
=== camel-spring-ai-vector-store - DELETE takes the ids from the body first,
and the embeddings headers go with a vector body