This is an automated email from the ASF dual-hosted git repository.
Croway 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 9d0aa80581f2 CAMEL-27247: camel-spring-ai-chat - finish reason
category and reasoning headers (#30451)
9d0aa80581f2 is described below
commit 9d0aa80581f2f77cc6f4b29e5969b6f08a38586d
Author: Federico Mariani <[email protected]>
AuthorDate: Thu Nov 19 21:24:38 2026 +0100
CAMEL-27247: camel-spring-ai-chat - finish reason category and reasoning
headers (#30451)
* CAMEL-27247: camel-spring-ai-chat - finish reason category and reasoning
headers
CamelSpringAiChatFinishReasonCategory is the category of the finish reason
that Spring AI 2.1 classifies the same for
every provider (COMPLETED, TRUNCATED, TOOL_CALL, FILTERED, OTHER,
UNSPECIFIED), so a route checks for a truncated or
filtered answer without knowing how the provider names it. A refusal of the
SafeGuard advisor is FILTERED.
CamelSpringAiChatReasoning is the text of the reasoning parts of the reply
(or the summary of a part that has only a
summary), set only when the reply has reasoning, and removed otherwise so a
header of an earlier call does not stay.
Both are also in the CamelSpringAiChatResponseMetadata map.
* CAMEL-27247: camel-spring-ai-chat - remove a finish reason of an earlier
call, and list the finish reason categories
- CamelSpringAiChatFinishReason is removed when the reply has no finish
reason, as CamelSpringAiChatReasoning, so it
does not stay next to the category of the current reply.
- The FINISH_REASON_CATEGORY header lists its values (enums) in the catalog.
- The generation metadata is read once for the headers and the metadata map.
- A reasoning part with blank text uses its summary.
---
.../camel/catalog/components/spring-ai-chat.json | 12 +-
.../catalog/docs/spring-ai-chat-component.adoc | 26 +++-
.../component/springai/chat/spring-ai-chat.json | 12 +-
.../src/main/docs/spring-ai-chat-component.adoc | 26 +++-
.../springai/chat/SpringAiChatConstants.java | 11 ++
.../springai/chat/SpringAiChatProducer.java | 57 +++++--
.../SpringAiChatFinishReasonReasoningTest.java | 168 +++++++++++++++++++++
.../dsl/SpringAiChatEndpointBuilderFactory.java | 29 ++++
8 files changed, 320 insertions(+), 21 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/spring-ai-chat.json
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/spring-ai-chat.json
index e03af782c92c..8b2a68611224 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/spring-ai-chat.json
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/spring-ai-chat.json
@@ -56,11 +56,13 @@
"CamelSpringAiChatConversationId": { "index": 24, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "Conversation ID for managing separate conversation contexts in
chat memory", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#CONVERSATION_ID"
},
"CamelSpringAiChatMaxFileSize": { "index": 25, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "Long", "deprecated": false, "autowired": false, "secret": false,
"description": "Maximum file size in bytes for multimodal content. Overrides
endpoint configuration.", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#MAX_FILE_SIZE"
},
"CamelSpringAiChatFinishReason": { "index": 26, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The reason why the chat response generation stopped (e.g.,
STOP, LENGTH, TOOL_CALLS)", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#FINISH_REASON"
},
- "CamelSpringAiChatModelName": { "index": 27, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The name of the AI model used to generate the response",
"constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#MODEL_NAME" },
- "CamelSpringAiChatResponseId": { "index": 28, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The unique ID of the chat response", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#RESPONSE_ID" },
- "CamelSpringAiChatResponseMetadata": { "index": 29, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.Map<String, Object>", "deprecated": false, "autowired":
false, "secret": false, "description": "Full response metadata as a Map
containing all available metadata fields", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#RESPONSE_METADATA"
},
- "CamelSpringAiChatToolNames": { "index": 30, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "Comma-separated tool names for selecting tools by name via
ToolCallbackResolver", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#TOOL_NAMES" },
- "CamelSpringAiChatToolContext": { "index": 31, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.Map<String, Object>", "deprecated": false, "autowired":
false, "secret": false, "description": "Context map to pass to tools during
execution", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#TOOL_CONTEXT" }
+ "CamelSpringAiChatFinishReasonCategory": { "index": 27, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "enum": [ "COMPLETED", "TRUNCATED", "TOOL_CALL",
"FILTERED", "OTHER", "UNSPECIFIED" ], "deprecated": false, "autowired": false,
"secret": false, "description": "The category of the finish reason, the same
for every provider: COMPLETED, TRUNCATED (a token or length limit), TOOL_CALL,
FILTERED (a content filter, or a ref [...]
+ "CamelSpringAiChatReasoning": { "index": 28, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The reasoning of the model for its reply (thinking, thoughts or
reasoning content), when the model returns it as text", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#REASONING" },
+ "CamelSpringAiChatModelName": { "index": 29, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The name of the AI model used to generate the response",
"constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#MODEL_NAME" },
+ "CamelSpringAiChatResponseId": { "index": 30, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The unique ID of the chat response", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#RESPONSE_ID" },
+ "CamelSpringAiChatResponseMetadata": { "index": 31, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.Map<String, Object>", "deprecated": false, "autowired":
false, "secret": false, "description": "Full response metadata as a Map
containing all available metadata fields", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#RESPONSE_METADATA"
},
+ "CamelSpringAiChatToolNames": { "index": 32, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "Comma-separated tool names for selecting tools by name via
ToolCallbackResolver", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#TOOL_NAMES" },
+ "CamelSpringAiChatToolContext": { "index": 33, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.Map<String, Object>", "deprecated": false, "autowired":
false, "secret": false, "description": "Context map to pass to tools during
execution", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#TOOL_CONTEXT" }
},
"bodyTypes": {
"producerIn": { "carriers": [ "any" ], "byOption": [ { "option":
"chatOperation", "value": "CHAT_SINGLE_MESSAGE_WITH_PROMPT", "carriers": [
"map" ] }, { "option": "chatOperation", "value": "CHAT_MULTIPLE_MESSAGES",
"carriers": [ "list" ] } ], "description": "The prompt as text, or a
UserMessage or another Spring AI Message. A byte[] is sent as media (image\/png
unless the CamelSpringAiChatMediaType header says otherwise), and a WrappedFile
of a local file, or a List of them, as media [...]
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-ai-chat-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-ai-chat-component.adoc
index 757593a769b7..27a508e245a5 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-ai-chat-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-ai-chat-component.adoc
@@ -317,13 +317,37 @@ The following headers are set after each chat operation:
**Response Metadata Headers:**
-* `CamelSpringAiChatFinishReason` - Why the generation stopped (e.g., "STOP",
"LENGTH", "TOOL_CALLS")
+* `CamelSpringAiChatFinishReason` - Why the generation stopped, as the
provider names it (e.g., "STOP", "end_turn", "LENGTH", "TOOL_CALLS")
+* `CamelSpringAiChatFinishReasonCategory` - The category of the finish reason,
the same for every provider: `COMPLETED`, `TRUNCATED`, `TOOL_CALL`, `FILTERED`,
`OTHER` or `UNSPECIFIED`
+* `CamelSpringAiChatReasoning` - The reasoning of the model for its reply
(thinking, thoughts or reasoning content), when the model returns it as text
* `CamelSpringAiChatModelName` - The name of the AI model used for the response
* `CamelSpringAiChatResponseId` - Unique identifier for the response
* `CamelSpringAiChatResponseMetadata` - Full metadata Map containing all
available fields
NOTE: Not all AI models provide all metadata fields. The availability of
specific metadata depends on the underlying model and provider. Most models
provide at least finish reason and token counts.
+The finish reason is named differently by each provider: `stop`, `end_turn`
and `STOP` all mean that the model finished
+its answer. Check `CamelSpringAiChatFinishReasonCategory` instead, so that a
route works with any model. For example, an
+answer cut by the token limit is `TRUNCATED`, and a reply blocked by a content
filter, or refused by the SafeGuard
+advisor (`safeguardSensitiveWords`), is `FILTERED`:
+
+[source,java]
+----
+from("direct:chat")
+ .to("spring-ai-chat:test?chatModel=#chatModel")
+ .choice()
+
.when(header("CamelSpringAiChatFinishReasonCategory").isEqualTo("TRUNCATED"))
+ .log("The answer was cut by the token limit")
+
.when(header("CamelSpringAiChatFinishReasonCategory").isEqualTo("FILTERED"))
+ .log("The reply was filtered or refused")
+ .end();
+----
+
+`CamelSpringAiChatReasoning` holds the text of the reasoning parts of the
reply, such as the thinking of Anthropic and
+Bedrock models, the thoughts of Gemini models, or the `reasoning_content` of
DeepSeek and OpenAI-compatible servers. A
+part with only a summary gives its summary, and a redacted part is left out.
The header is not set, and is removed if an
+earlier call set it, when the reply has no reasoning.
+
=== Message Metadata
The component supports attaching metadata to both user and system messages.
This is useful for tracking message identifiers, conversation context, priority
levels, or other application-specific data.
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/generated/resources/META-INF/org/apache/camel/component/springai/chat/spring-ai-chat.json
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/generated/resources/META-INF/org/apache/camel/component/springai/chat/spring-ai-chat.json
index e03af782c92c..8b2a68611224 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/generated/resources/META-INF/org/apache/camel/component/springai/chat/spring-ai-chat.json
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/generated/resources/META-INF/org/apache/camel/component/springai/chat/spring-ai-chat.json
@@ -56,11 +56,13 @@
"CamelSpringAiChatConversationId": { "index": 24, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "Conversation ID for managing separate conversation contexts in
chat memory", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#CONVERSATION_ID"
},
"CamelSpringAiChatMaxFileSize": { "index": 25, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "Long", "deprecated": false, "autowired": false, "secret": false,
"description": "Maximum file size in bytes for multimodal content. Overrides
endpoint configuration.", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#MAX_FILE_SIZE"
},
"CamelSpringAiChatFinishReason": { "index": 26, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The reason why the chat response generation stopped (e.g.,
STOP, LENGTH, TOOL_CALLS)", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#FINISH_REASON"
},
- "CamelSpringAiChatModelName": { "index": 27, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The name of the AI model used to generate the response",
"constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#MODEL_NAME" },
- "CamelSpringAiChatResponseId": { "index": 28, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The unique ID of the chat response", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#RESPONSE_ID" },
- "CamelSpringAiChatResponseMetadata": { "index": 29, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.Map<String, Object>", "deprecated": false, "autowired":
false, "secret": false, "description": "Full response metadata as a Map
containing all available metadata fields", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#RESPONSE_METADATA"
},
- "CamelSpringAiChatToolNames": { "index": 30, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "Comma-separated tool names for selecting tools by name via
ToolCallbackResolver", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#TOOL_NAMES" },
- "CamelSpringAiChatToolContext": { "index": 31, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.Map<String, Object>", "deprecated": false, "autowired":
false, "secret": false, "description": "Context map to pass to tools during
execution", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#TOOL_CONTEXT" }
+ "CamelSpringAiChatFinishReasonCategory": { "index": 27, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "enum": [ "COMPLETED", "TRUNCATED", "TOOL_CALL",
"FILTERED", "OTHER", "UNSPECIFIED" ], "deprecated": false, "autowired": false,
"secret": false, "description": "The category of the finish reason, the same
for every provider: COMPLETED, TRUNCATED (a token or length limit), TOOL_CALL,
FILTERED (a content filter, or a ref [...]
+ "CamelSpringAiChatReasoning": { "index": 28, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The reasoning of the model for its reply (thinking, thoughts or
reasoning content), when the model returns it as text", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#REASONING" },
+ "CamelSpringAiChatModelName": { "index": 29, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The name of the AI model used to generate the response",
"constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#MODEL_NAME" },
+ "CamelSpringAiChatResponseId": { "index": 30, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "The unique ID of the chat response", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#RESPONSE_ID" },
+ "CamelSpringAiChatResponseMetadata": { "index": 31, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.Map<String, Object>", "deprecated": false, "autowired":
false, "secret": false, "description": "Full response metadata as a Map
containing all available metadata fields", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#RESPONSE_METADATA"
},
+ "CamelSpringAiChatToolNames": { "index": 32, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "String", "deprecated": false, "autowired": false, "secret": false,
"description": "Comma-separated tool names for selecting tools by name via
ToolCallbackResolver", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#TOOL_NAMES" },
+ "CamelSpringAiChatToolContext": { "index": 33, "kind": "header",
"displayName": "", "group": "producer", "label": "", "required": false,
"javaType": "java.util.Map<String, Object>", "deprecated": false, "autowired":
false, "secret": false, "description": "Context map to pass to tools during
execution", "constantName":
"org.apache.camel.component.springai.chat.SpringAiChatConstants#TOOL_CONTEXT" }
},
"bodyTypes": {
"producerIn": { "carriers": [ "any" ], "byOption": [ { "option":
"chatOperation", "value": "CHAT_SINGLE_MESSAGE_WITH_PROMPT", "carriers": [
"map" ] }, { "option": "chatOperation", "value": "CHAT_MULTIPLE_MESSAGES",
"carriers": [ "list" ] } ], "description": "The prompt as text, or a
UserMessage or another Spring AI Message. A byte[] is sent as media (image\/png
unless the CamelSpringAiChatMediaType header says otherwise), and a WrappedFile
of a local file, or a List of them, as media [...]
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/docs/spring-ai-chat-component.adoc
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/docs/spring-ai-chat-component.adoc
index 757593a769b7..27a508e245a5 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/docs/spring-ai-chat-component.adoc
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/docs/spring-ai-chat-component.adoc
@@ -317,13 +317,37 @@ The following headers are set after each chat operation:
**Response Metadata Headers:**
-* `CamelSpringAiChatFinishReason` - Why the generation stopped (e.g., "STOP",
"LENGTH", "TOOL_CALLS")
+* `CamelSpringAiChatFinishReason` - Why the generation stopped, as the
provider names it (e.g., "STOP", "end_turn", "LENGTH", "TOOL_CALLS")
+* `CamelSpringAiChatFinishReasonCategory` - The category of the finish reason,
the same for every provider: `COMPLETED`, `TRUNCATED`, `TOOL_CALL`, `FILTERED`,
`OTHER` or `UNSPECIFIED`
+* `CamelSpringAiChatReasoning` - The reasoning of the model for its reply
(thinking, thoughts or reasoning content), when the model returns it as text
* `CamelSpringAiChatModelName` - The name of the AI model used for the response
* `CamelSpringAiChatResponseId` - Unique identifier for the response
* `CamelSpringAiChatResponseMetadata` - Full metadata Map containing all
available fields
NOTE: Not all AI models provide all metadata fields. The availability of
specific metadata depends on the underlying model and provider. Most models
provide at least finish reason and token counts.
+The finish reason is named differently by each provider: `stop`, `end_turn`
and `STOP` all mean that the model finished
+its answer. Check `CamelSpringAiChatFinishReasonCategory` instead, so that a
route works with any model. For example, an
+answer cut by the token limit is `TRUNCATED`, and a reply blocked by a content
filter, or refused by the SafeGuard
+advisor (`safeguardSensitiveWords`), is `FILTERED`:
+
+[source,java]
+----
+from("direct:chat")
+ .to("spring-ai-chat:test?chatModel=#chatModel")
+ .choice()
+
.when(header("CamelSpringAiChatFinishReasonCategory").isEqualTo("TRUNCATED"))
+ .log("The answer was cut by the token limit")
+
.when(header("CamelSpringAiChatFinishReasonCategory").isEqualTo("FILTERED"))
+ .log("The reply was filtered or refused")
+ .end();
+----
+
+`CamelSpringAiChatReasoning` holds the text of the reasoning parts of the
reply, such as the thinking of Anthropic and
+Bedrock models, the thoughts of Gemini models, or the `reasoning_content` of
DeepSeek and OpenAI-compatible servers. A
+part with only a summary gives its summary, and a redacted part is left out.
The header is not set, and is removed if an
+earlier call set it, when the reply has no reasoning.
+
=== Message Metadata
The component supports attaching metadata to both user and system messages.
This is useful for tracking message identifiers, conversation context, priority
levels, or other application-specific data.
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/SpringAiChatConstants.java
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/SpringAiChatConstants.java
index bd7090974bc6..8bc3f37414ae 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/SpringAiChatConstants.java
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/SpringAiChatConstants.java
@@ -109,6 +109,17 @@ public final class SpringAiChatConstants {
javaType = "String")
public static final String FINISH_REASON = "CamelSpringAiChatFinishReason";
+ @Metadata(description = "The category of the finish reason, the same for
every provider: COMPLETED, TRUNCATED (a token "
+ + "or length limit), TOOL_CALL, FILTERED (a
content filter, or a refusal of the SafeGuard "
+ + "advisor), OTHER or UNSPECIFIED",
+ javaType = "String", enums =
"COMPLETED,TRUNCATED,TOOL_CALL,FILTERED,OTHER,UNSPECIFIED")
+ public static final String FINISH_REASON_CATEGORY =
"CamelSpringAiChatFinishReasonCategory";
+
+ @Metadata(description = "The reasoning of the model for its reply
(thinking, thoughts or reasoning content), when the "
+ + "model returns it as text",
+ javaType = "String")
+ public static final String REASONING = "CamelSpringAiChatReasoning";
+
@Metadata(description = "The name of the AI model used to generate the
response", javaType = "String")
public static final String MODEL_NAME = "CamelSpringAiChatModelName";
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/SpringAiChatProducer.java
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/SpringAiChatProducer.java
index b9f36ff0d256..f285a83de460 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/SpringAiChatProducer.java
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/SpringAiChatProducer.java
@@ -65,6 +65,7 @@ import
org.springframework.ai.chat.client.advisor.vectorstore.VectorStoreChatMem
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
+import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.ChatOptions;
@@ -888,6 +889,14 @@ public class SpringAiChatProducer extends DefaultProducer {
}
private void populateResponseMetadata(ChatResponse response, Exchange
exchange) {
+ // The reasoning of this reply only, so a header of an earlier call
does not stay
+ String reasoning = reasoningText(response);
+ if (reasoning != null) {
+ exchange.getMessage().setHeader(SpringAiChatConstants.REASONING,
reasoning);
+ } else {
+
exchange.getMessage().removeHeader(SpringAiChatConstants.REASONING);
+ }
+
// Add response metadata if available
if (response.getMetadata() != null) {
var responseMetadata = response.getMetadata();
@@ -904,12 +913,22 @@ public class SpringAiChatProducer extends DefaultProducer
{
responseMetadata.getId());
}
- // Finish reason is on the Generation metadata, not the Response
metadata
- if (response.getResult() != null &&
response.getResult().getMetadata() != null) {
- String finishReason =
response.getResult().getMetadata().getFinishReason();
+ // Finish reason is on the Generation metadata, not the Response
metadata. Its category is the same for every
+ // provider, unlike the finish reason. A finish reason of an
earlier call does not stay next to the category
+ // of this one
+ ChatGenerationMetadata generationMetadata
+ = response.getResult() != null ?
response.getResult().getMetadata() : null;
+ String finishReason = null;
+ String finishReasonCategory = null;
+ if (generationMetadata != null) {
+ finishReason = generationMetadata.getFinishReason();
+ finishReasonCategory =
generationMetadata.getFinishReasonCategory().name();
if (finishReason != null) {
exchange.getMessage().setHeader(SpringAiChatConstants.FINISH_REASON,
finishReason);
+ } else {
+
exchange.getMessage().removeHeader(SpringAiChatConstants.FINISH_REASON);
}
+
exchange.getMessage().setHeader(SpringAiChatConstants.FINISH_REASON_CATEGORY,
finishReasonCategory);
}
// Full metadata map for advanced users
@@ -921,12 +940,15 @@ public class SpringAiChatProducer extends DefaultProducer
{
if (responseMetadata.getModel() != null) {
metadataMap.put("model", responseMetadata.getModel());
}
- // Add finish reason from generation metadata
- if (response.getResult() != null &&
response.getResult().getMetadata() != null) {
- String finishReason =
response.getResult().getMetadata().getFinishReason();
- if (finishReason != null) {
- metadataMap.put("finishReason", finishReason);
- }
+ // Add finish reason and its category from generation metadata
+ if (finishReason != null) {
+ metadataMap.put("finishReason", finishReason);
+ }
+ if (finishReasonCategory != null) {
+ metadataMap.put("finishReasonCategory", finishReasonCategory);
+ }
+ if (reasoning != null) {
+ metadataMap.put("reasoning", reasoning);
}
if (responseMetadata.getUsage() != null) {
metadataMap.put("usage", responseMetadata.getUsage());
@@ -946,6 +968,23 @@ public class SpringAiChatProducer extends DefaultProducer {
}
}
+ /**
+ * The reasoning of the reply as text: the text of each reasoning part, or
its summary when the provider returns
+ * only a summary. A redacted part has neither and is left out.
+ *
+ * @return the reasoning, or {@code null} when the reply has none
+ */
+ private static String reasoningText(ChatResponse response) {
+ if (response.getResult() == null) {
+ return null;
+ }
+ String reasoning =
response.getResult().getOutput().getReasoning().stream()
+ .map(part -> part.text() != null && !part.text().isBlank() ?
part.text() : part.summary())
+ .filter(text -> text != null && !text.isBlank())
+ .collect(Collectors.joining("\n\n"));
+ return reasoning.isEmpty() ? null : reasoning;
+ }
+
@SuppressWarnings("unchecked")
private Map<String, Object> getUserMetadata(Exchange exchange) {
// Check if metadata is provided via header (takes highest priority)
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/SpringAiChatFinishReasonReasoningTest.java
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/SpringAiChatFinishReasonReasoningTest.java
new file mode 100644
index 000000000000..83259fb9fe76
--- /dev/null
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/SpringAiChatFinishReasonReasoningTest.java
@@ -0,0 +1,168 @@
+/*
+ * 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.camel.component.springai.chat;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+import org.springframework.ai.chat.messages.AssistantMessage;
+import org.springframework.ai.chat.messages.part.ReasoningPart;
+import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
+import org.springframework.ai.chat.metadata.ChatResponseMetadata;
+import org.springframework.ai.chat.model.ChatModel;
+import org.springframework.ai.chat.model.ChatResponse;
+import org.springframework.ai.chat.model.Generation;
+import org.springframework.ai.chat.prompt.ChatOptions;
+import org.springframework.ai.chat.prompt.Prompt;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The CamelSpringAiChatFinishReasonCategory and CamelSpringAiChatReasoning
headers.
+ */
+class SpringAiChatFinishReasonReasoningTest extends CamelTestSupport {
+
+ private final ReplyModel model = new ReplyModel();
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ CamelContext context = super.createCamelContext();
+ SpringAiChatComponent component = new SpringAiChatComponent();
+ component.setChatModel(model);
+ context.addComponent("spring-ai-chat", component);
+ return context;
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:chat").to("spring-ai-chat:test");
+
from("direct:safeguard").to("spring-ai-chat:test?safeguardSensitiveWords=secret");
+ }
+ };
+ }
+
+ @Test
+ void setsTheCategoryAndTheReasoning() {
+ model.finishReason = "end_turn";
+ model.reasoning = List.of(ReasoningPart.of("The user greets me."),
ReasoningPart.of("I greet back."));
+
+ Exchange out = template.request("direct:chat", e ->
e.getIn().setBody("Hello"));
+
+ assertThat(out.getMessage().getBody(String.class)).isEqualTo("Hi
there");
+
assertThat(out.getMessage().getHeader(SpringAiChatConstants.FINISH_REASON)).isEqualTo("end_turn");
+
assertThat(out.getMessage().getHeader(SpringAiChatConstants.FINISH_REASON_CATEGORY)).isEqualTo("COMPLETED");
+ assertThat(out.getMessage().getHeader(SpringAiChatConstants.REASONING))
+ .isEqualTo("The user greets me.\n\nI greet back.");
+
assertThat(out.getMessage().getHeader(SpringAiChatConstants.RESPONSE_METADATA,
Map.class))
+ .containsEntry("finishReasonCategory", "COMPLETED")
+ .containsEntry("reasoning", "The user greets me.\n\nI greet
back.");
+ }
+
+ @Test
+ void truncatedReplyWithoutReasoningRemovesAnEarlierReasoningHeader() {
+ model.finishReason = "max_tokens";
+ model.reasoning = List.of();
+
+ Exchange out = template.request("direct:chat", e -> {
+ e.getIn().setBody("Hello");
+ e.getIn().setHeader(SpringAiChatConstants.REASONING, "reasoning of
an earlier call");
+ });
+
+
assertThat(out.getMessage().getHeader(SpringAiChatConstants.FINISH_REASON_CATEGORY)).isEqualTo("TRUNCATED");
+
assertThat(out.getMessage().getHeaders()).doesNotContainKey(SpringAiChatConstants.REASONING);
+ }
+
+ @Test
+ void replyWithoutFinishReasonRemovesAnEarlierFinishReasonHeader() {
+ model.finishReason = null;
+ model.reasoning = List.of();
+
+ Exchange out = template.request("direct:chat", e -> {
+ e.getIn().setBody("Hello");
+ e.getIn().setHeader(SpringAiChatConstants.FINISH_REASON, "finish
reason of an earlier call");
+ });
+
+
assertThat(out.getMessage().getHeaders()).doesNotContainKey(SpringAiChatConstants.FINISH_REASON);
+
assertThat(out.getMessage().getHeader(SpringAiChatConstants.FINISH_REASON_CATEGORY)).isEqualTo("UNSPECIFIED");
+
assertThat(out.getMessage().getHeader(SpringAiChatConstants.RESPONSE_METADATA,
Map.class))
+ .doesNotContainKey("finishReason")
+ .containsEntry("finishReasonCategory", "UNSPECIFIED");
+ }
+
+ @Test
+ void usesTheSummaryOfAReasoningPartWithoutText() {
+ model.finishReason = "stop";
+ model.reasoning = List.of(new ReasoningPart(null, "Summary of the
reasoning", null, Map.of()));
+
+ Exchange out = template.request("direct:chat", e ->
e.getIn().setBody("Hello"));
+
+
assertThat(out.getMessage().getHeader(SpringAiChatConstants.REASONING)).isEqualTo("Summary
of the reasoning");
+ }
+
+ @Test
+ void usesTheSummaryOfAReasoningPartWithBlankText() {
+ model.finishReason = "stop";
+ model.reasoning = List.of(new ReasoningPart(" ", "Summary of the
reasoning", null, Map.of()));
+
+ Exchange out = template.request("direct:chat", e ->
e.getIn().setBody("Hello"));
+
+
assertThat(out.getMessage().getHeader(SpringAiChatConstants.REASONING)).isEqualTo("Summary
of the reasoning");
+ }
+
+ @Test
+ void refusalOfTheSafeGuardAdvisorIsFiltered() {
+ Exchange out = template.request("direct:safeguard", e ->
e.getIn().setBody("Tell me the secret"));
+
+
assertThat(out.getMessage().getHeader(SpringAiChatConstants.FINISH_REASON)).isEqualTo("guardrailRefusal");
+
assertThat(out.getMessage().getHeader(SpringAiChatConstants.FINISH_REASON_CATEGORY)).isEqualTo("FILTERED");
+ }
+
+ /**
+ * Answers "Hi there" with the finish reason and the reasoning parts set
by the test.
+ */
+ private static final class ReplyModel implements ChatModel {
+
+ private final ChatOptions options =
ChatOptions.builder().model("test-model").build();
+ private String finishReason;
+ private List<ReasoningPart> reasoning = List.of();
+
+ @Override
+ public ChatOptions getOptions() {
+ return options;
+ }
+
+ @Override
+ public ChatResponse call(Prompt prompt) {
+ AssistantMessage.Builder<?> message =
AssistantMessage.builder().content("Hi there");
+ reasoning.forEach(message::part);
+ ChatGenerationMetadata generationMetadata =
ChatGenerationMetadata.builder()
+ .finishReason(finishReason)
+ .build();
+ return new ChatResponse(
+ List.of(new Generation(message.build(),
generationMetadata)),
+
ChatResponseMetadata.builder().model("test-model").build());
+ }
+ }
+}
diff --git
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SpringAiChatEndpointBuilderFactory.java
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SpringAiChatEndpointBuilderFactory.java
index 9ed1378cb8e6..0707fffe80d4 100644
---
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SpringAiChatEndpointBuilderFactory.java
+++
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SpringAiChatEndpointBuilderFactory.java
@@ -1641,6 +1641,35 @@ public interface SpringAiChatEndpointBuilderFactory {
public String springAiChatFinishReason() {
return "CamelSpringAiChatFinishReason";
}
+ /**
+ * The category of the finish reason, the same for every provider:
+ * COMPLETED, TRUNCATED (a token or length limit), TOOL_CALL, FILTERED
+ * (a content filter, or a refusal of the SafeGuard advisor), OTHER or
+ * UNSPECIFIED.
+ *
+ * The option is a: {@code String} type.
+ *
+ * Group: producer
+ *
+ * @return the name of the header {@code
+ * SpringAiChatFinishReasonCategory}.
+ */
+ public String springAiChatFinishReasonCategory() {
+ return "CamelSpringAiChatFinishReasonCategory";
+ }
+ /**
+ * The reasoning of the model for its reply (thinking, thoughts or
+ * reasoning content), when the model returns it as text.
+ *
+ * The option is a: {@code String} type.
+ *
+ * Group: producer
+ *
+ * @return the name of the header {@code SpringAiChatReasoning}.
+ */
+ public String springAiChatReasoning() {
+ return "CamelSpringAiChatReasoning";
+ }
/**
* The name of the AI model used to generate the response.
*