diff --git a/components/camel-ai/camel-langchain4j-agent/pom.xml b/components/camel-ai/camel-langchain4j-agent/pom.xml index ff706901a108f..5f0f0fc309468 100644 --- a/components/camel-ai/camel-langchain4j-agent/pom.xml +++ b/components/camel-ai/camel-langchain4j-agent/pom.xml @@ -113,6 +113,11 @@ assertj-core test + + org.apache.camel + camel-json-validator + test + org.apache.camel camel-test-infra-ollama diff --git a/components/camel-ai/camel-langchain4j-agent/src/main/docs/langchain4j-agent-component.adoc b/components/camel-ai/camel-langchain4j-agent/src/main/docs/langchain4j-agent-component.adoc index a126832f26bc4..37df7d930263d 100644 --- a/components/camel-ai/camel-langchain4j-agent/src/main/docs/langchain4j-agent-component.adoc +++ b/components/camel-ai/camel-langchain4j-agent/src/main/docs/langchain4j-agent-component.adoc @@ -1303,6 +1303,85 @@ public class AgentConfig { |Retries LLM call |=== +=== Structured Outputs with JSON Schema + +The LangChain4j Agent component supports structured outputs by configuring the `ChatModel` with a `ResponseFormat` that enforces a JSON schema. This feature is available for providers that support structured outputs including Amazon Bedrock, Azure OpenAI, Google AI Gemini, Mistral, Ollama, and OpenAI. + +IMPORTANT: The `ResponseFormat` must be configured on the `ChatModel` itself before passing it to the `AgentConfiguration`. The LangChain4j `AiServices` builder does not support setting response format directly. + +==== Configuring Structured Outputs + +To use structured outputs with the agent component: + +1. Define your JSON schema +2. Create a `ResponseFormat` with the schema +3. Configure your `ChatModel` with the `ResponseFormat` +4. Pass the configured model to `AgentConfiguration` + +===== Complete Example with OpenAI + +[source,java] +---- +import dev.langchain4j.model.chat.ChatModel; +import dev.langchain4j.model.chat.request.ResponseFormat; +import dev.langchain4j.model.chat.request.json.JsonRawSchema; +import dev.langchain4j.model.chat.request.json.JsonSchema; +import dev.langchain4j.model.openai.OpenAiChatModel; +import static dev.langchain4j.model.chat.request.ResponseFormatType.JSON; + +// Define JSON schema +String personSchema = """ + { + "type": "object", + "properties": { + "name": {"type": "string", "description": "The person's full name"}, + "age": {"type": "integer", "description": "The person's age in years"}, + "occupation": {"type": "string", "description": "The person's job"} + }, + "required": ["name", "age", "occupation"], + "additionalProperties": false + } + """; + +// Create ResponseFormat with JSON Schema +JsonRawSchema jsonRawSchema = JsonRawSchema.from(personSchema); +ResponseFormat responseFormat = ResponseFormat.builder() + .type(JSON) + .jsonSchema(JsonSchema.builder() + .name("person_schema") + .rootElement(jsonRawSchema) + .build()) + .build(); + +// Configure ChatModel with ResponseFormat +ChatModel chatModel = OpenAiChatModel.builder() + .apiKey(openAiApiKey) + .modelName("gpt-4o-mini") + .responseFormat(responseFormat) // Apply structured output here + .build(); + +// Create agent with the configured model +AgentConfiguration configuration = new AgentConfiguration() + .withChatModel(chatModel); + +Agent agent = new AgentWithoutMemory(configuration); +context.getRegistry().bind("structuredAgent", agent); + +// Use in route +from("direct:extract-person-info") + .setBody(constant("Extract information about John Smith, a 35-year-old software engineer")) + .to("langchain4j-agent:structured?agent=#structuredAgent") + .unmarshal().json() // Parse the JSON response + .log("Extracted person: ${body}"); +---- + +[NOTE] +==== +* The LLM response will be guaranteed to conform to the provided schema +* No prompt engineering is needed for output formatting +* The same schema file can be shared across `camel-openai` and `camel-langchain4j-agent` components +==== + === Multimodal Content Support The LangChain4j Agent component supports multimodal content, allowing you to send images, PDFs, audio, video, and text files to AI models that support vision and document understanding capabilities. diff --git a/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/integration/LangChain4jAgentStructuredOutputIT.java b/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/integration/LangChain4jAgentStructuredOutputIT.java new file mode 100644 index 0000000000000..7a3d497fe0c25 --- /dev/null +++ b/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/integration/LangChain4jAgentStructuredOutputIT.java @@ -0,0 +1,135 @@ +/* + * 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.langchain4j.agent.integration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import dev.langchain4j.model.chat.ChatModel; +import dev.langchain4j.model.chat.request.ResponseFormat; +import dev.langchain4j.model.chat.request.json.JsonRawSchema; +import dev.langchain4j.model.chat.request.json.JsonSchema; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.langchain4j.agent.api.Agent; +import org.apache.camel.component.langchain4j.agent.api.AgentConfiguration; +import org.apache.camel.component.langchain4j.agent.api.AgentWithoutMemory; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.infra.ollama.services.OllamaService; +import org.apache.camel.test.infra.ollama.services.OllamaServiceFactory; +import org.apache.camel.test.junit6.CamelTestSupport; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static dev.langchain4j.model.chat.request.ResponseFormatType.JSON; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Integration test for structured outputs with JSON Schema using the langchain4j-agent component. + */ +@DisabledIfSystemProperty(named = "ci.env.name", matches = ".*", disabledReason = "Requires too much network resources") +public class LangChain4jAgentStructuredOutputIT extends CamelTestSupport { + + private static final String PERSON_SCHEMA = """ + { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The person's full name" + }, + "age": { + "type": "integer", + "description": "The person's age in years" + }, + "occupation": { + "type": "string", + "description": "The person's job or profession" + } + }, + "required": ["name", "age", "occupation"], + "additionalProperties": false + } + """; + + private static final String TEST_PROMPT + = "Generate information about a software engineer named Alice who is 30 years old."; + + private final ObjectMapper objectMapper = new ObjectMapper(); + + protected ChatModel chatModel; + + @RegisterExtension + static OllamaService OLLAMA = OllamaServiceFactory.createSingletonService(); + + @Override + protected void setupResources() throws Exception { + super.setupResources(); + + JsonRawSchema jsonRawSchema = JsonRawSchema.from(PERSON_SCHEMA); + ResponseFormat responseFormat = ResponseFormat.builder() + .type(JSON) + .jsonSchema(JsonSchema.builder() + .name("person_schema") + .rootElement(jsonRawSchema) + .build()) + .build(); + + chatModel = ModelHelper.loadChatModel(OLLAMA, responseFormat); + } + + @Test + void testStructuredOutputWithJsonSchema() throws Exception { + MockEndpoint mockEndpoint = getMockEndpoint("mock:result"); + mockEndpoint.expectedMessageCount(1); + + String response = template.requestBody("direct:structured-output", TEST_PROMPT, String.class); + + mockEndpoint.assertIsSatisfied(); + + assertNotNull(response); + JsonNode jsonResponse = objectMapper.readTree(response); + + assertThat(jsonResponse.has("name")).isTrue(); + assertThat(jsonResponse.has("age")).isTrue(); + assertThat(jsonResponse.has("occupation")).isTrue(); + + assertThat(jsonResponse.get("name").asText()).contains("Alice"); + assertThat(jsonResponse.get("age").asInt()).isEqualTo(30); + assertThat(jsonResponse.get("occupation").asText().toLowerCase()).containsAnyOf("engineer", "developer"); + } + + @Override + protected RouteBuilder createRouteBuilder() { + AgentConfiguration configuration = new AgentConfiguration() + .withChatModel(chatModel); + + Agent agent = new AgentWithoutMemory(configuration); + context.getRegistry().bind("structuredOutputAgent", agent); + + return new RouteBuilder() { + @Override + public void configure() { + from("direct:structured-output") + .to("langchain4j-agent:structured-output?agent=#structuredOutputAgent") + .to("json-validator:classpath:person-schema.json") + .to("mock:result"); + } + }; + } + +} diff --git a/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/integration/ModelHelper.java b/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/integration/ModelHelper.java index 243aaa7b4ade3..9ae834909399e 100644 --- a/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/integration/ModelHelper.java +++ b/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/integration/ModelHelper.java @@ -18,6 +18,7 @@ package org.apache.camel.component.langchain4j.agent.integration; import dev.langchain4j.model.chat.ChatModel; +import dev.langchain4j.model.chat.request.ResponseFormat; import dev.langchain4j.model.embedding.EmbeddingModel; import dev.langchain4j.model.ollama.OllamaChatModel; import dev.langchain4j.model.ollama.OllamaEmbeddingModel; @@ -59,6 +60,32 @@ public static ChatModel loadChatModel(OllamaService ollamaService) { .build(); } + /** + * Load chat model with a specific ResponseFormat for structured outputs. + */ + public static ChatModel loadChatModel(OllamaService ollamaService, ResponseFormat responseFormat) { + if (ollamaService instanceof OpenAIService openaiService) { + return OpenAiChatModel.builder() + .apiKey(openaiService.apiKey()) + .baseUrl(openaiService.baseUrl()) + .modelName(openaiService.modelName()) + .responseFormat(responseFormat) + .temperature(1.0) + .timeout(ofSeconds(120)) + .logRequests(true) + .logResponses(true) + .build(); + } + + return OllamaChatModel.builder() + .baseUrl(ollamaService.baseUrl()) + .modelName(ollamaService.modelName()) + .responseFormat(responseFormat) + .temperature(0.3) + .timeout(ofSeconds(120)) + .build(); + } + /** * Load embedding model from OllamaService. Detects if the service is OpenAIService and creates the appropriate * model type. diff --git a/components/camel-ai/camel-langchain4j-agent/src/test/resources/person-schema.json b/components/camel-ai/camel-langchain4j-agent/src/test/resources/person-schema.json new file mode 100644 index 0000000000000..21ff5dd85d973 --- /dev/null +++ b/components/camel-ai/camel-langchain4j-agent/src/test/resources/person-schema.json @@ -0,0 +1,19 @@ +{ + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "age": { + "type": "integer", + "minimum": 0 + }, + "occupation": { + "type": "string", + "minLength": 1 + } + }, + "required": ["name", "age", "occupation"], + "additionalProperties": false +}