Skip to content

Commit c9998c1

Browse files
authored
CAMEL-23327: Add structured outputs documentation and integration test for langchain4j-agent (#22724)
1 parent c890e58 commit c9998c1

5 files changed

Lines changed: 265 additions & 0 deletions

File tree

components/camel-ai/camel-langchain4j-agent/pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,11 @@
113113
<artifactId>assertj-core</artifactId>
114114
<scope>test</scope>
115115
</dependency>
116+
<dependency>
117+
<groupId>org.apache.camel</groupId>
118+
<artifactId>camel-json-validator</artifactId>
119+
<scope>test</scope>
120+
</dependency>
116121
<dependency>
117122
<groupId>org.apache.camel</groupId>
118123
<artifactId>camel-test-infra-ollama</artifactId>

components/camel-ai/camel-langchain4j-agent/src/main/docs/langchain4j-agent-component.adoc

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1303,6 +1303,85 @@ public class AgentConfig {
13031303
|Retries LLM call
13041304
|===
13051305

1306+
=== Structured Outputs with JSON Schema
1307+
1308+
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.
1309+
1310+
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.
1311+
1312+
==== Configuring Structured Outputs
1313+
1314+
To use structured outputs with the agent component:
1315+
1316+
1. Define your JSON schema
1317+
2. Create a `ResponseFormat` with the schema
1318+
3. Configure your `ChatModel` with the `ResponseFormat`
1319+
4. Pass the configured model to `AgentConfiguration`
1320+
1321+
===== Complete Example with OpenAI
1322+
1323+
[source,java]
1324+
----
1325+
import dev.langchain4j.model.chat.ChatModel;
1326+
import dev.langchain4j.model.chat.request.ResponseFormat;
1327+
import dev.langchain4j.model.chat.request.json.JsonRawSchema;
1328+
import dev.langchain4j.model.chat.request.json.JsonSchema;
1329+
import dev.langchain4j.model.openai.OpenAiChatModel;
1330+
import static dev.langchain4j.model.chat.request.ResponseFormatType.JSON;
1331+
1332+
// Define JSON schema
1333+
String personSchema = """
1334+
{
1335+
"type": "object",
1336+
"properties": {
1337+
"name": {"type": "string", "description": "The person's full name"},
1338+
"age": {"type": "integer", "description": "The person's age in years"},
1339+
"occupation": {"type": "string", "description": "The person's job"}
1340+
},
1341+
"required": ["name", "age", "occupation"],
1342+
"additionalProperties": false
1343+
}
1344+
""";
1345+
1346+
// Create ResponseFormat with JSON Schema
1347+
JsonRawSchema jsonRawSchema = JsonRawSchema.from(personSchema);
1348+
ResponseFormat responseFormat = ResponseFormat.builder()
1349+
.type(JSON)
1350+
.jsonSchema(JsonSchema.builder()
1351+
.name("person_schema")
1352+
.rootElement(jsonRawSchema)
1353+
.build())
1354+
.build();
1355+
1356+
// Configure ChatModel with ResponseFormat
1357+
ChatModel chatModel = OpenAiChatModel.builder()
1358+
.apiKey(openAiApiKey)
1359+
.modelName("gpt-4o-mini")
1360+
.responseFormat(responseFormat) // Apply structured output here
1361+
.build();
1362+
1363+
// Create agent with the configured model
1364+
AgentConfiguration configuration = new AgentConfiguration()
1365+
.withChatModel(chatModel);
1366+
1367+
Agent agent = new AgentWithoutMemory(configuration);
1368+
context.getRegistry().bind("structuredAgent", agent);
1369+
1370+
// Use in route
1371+
from("direct:extract-person-info")
1372+
.setBody(constant("Extract information about John Smith, a 35-year-old software engineer"))
1373+
.to("langchain4j-agent:structured?agent=#structuredAgent")
1374+
.unmarshal().json() // Parse the JSON response
1375+
.log("Extracted person: ${body}");
1376+
----
1377+
1378+
[NOTE]
1379+
====
1380+
* The LLM response will be guaranteed to conform to the provided schema
1381+
* No prompt engineering is needed for output formatting
1382+
* The same schema file can be shared across `camel-openai` and `camel-langchain4j-agent` components
1383+
====
1384+
13061385
=== Multimodal Content Support
13071386

13081387
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.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package org.apache.camel.component.langchain4j.agent.integration;
18+
19+
import com.fasterxml.jackson.databind.JsonNode;
20+
import com.fasterxml.jackson.databind.ObjectMapper;
21+
import dev.langchain4j.model.chat.ChatModel;
22+
import dev.langchain4j.model.chat.request.ResponseFormat;
23+
import dev.langchain4j.model.chat.request.json.JsonRawSchema;
24+
import dev.langchain4j.model.chat.request.json.JsonSchema;
25+
import org.apache.camel.builder.RouteBuilder;
26+
import org.apache.camel.component.langchain4j.agent.api.Agent;
27+
import org.apache.camel.component.langchain4j.agent.api.AgentConfiguration;
28+
import org.apache.camel.component.langchain4j.agent.api.AgentWithoutMemory;
29+
import org.apache.camel.component.mock.MockEndpoint;
30+
import org.apache.camel.test.infra.ollama.services.OllamaService;
31+
import org.apache.camel.test.infra.ollama.services.OllamaServiceFactory;
32+
import org.apache.camel.test.junit6.CamelTestSupport;
33+
import org.junit.jupiter.api.Test;
34+
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
35+
import org.junit.jupiter.api.extension.RegisterExtension;
36+
37+
import static dev.langchain4j.model.chat.request.ResponseFormatType.JSON;
38+
import static org.assertj.core.api.Assertions.assertThat;
39+
import static org.junit.jupiter.api.Assertions.assertNotNull;
40+
41+
/**
42+
* Integration test for structured outputs with JSON Schema using the langchain4j-agent component.
43+
*/
44+
@DisabledIfSystemProperty(named = "ci.env.name", matches = ".*", disabledReason = "Requires too much network resources")
45+
public class LangChain4jAgentStructuredOutputIT extends CamelTestSupport {
46+
47+
private static final String PERSON_SCHEMA = """
48+
{
49+
"type": "object",
50+
"properties": {
51+
"name": {
52+
"type": "string",
53+
"description": "The person's full name"
54+
},
55+
"age": {
56+
"type": "integer",
57+
"description": "The person's age in years"
58+
},
59+
"occupation": {
60+
"type": "string",
61+
"description": "The person's job or profession"
62+
}
63+
},
64+
"required": ["name", "age", "occupation"],
65+
"additionalProperties": false
66+
}
67+
""";
68+
69+
private static final String TEST_PROMPT
70+
= "Generate information about a software engineer named Alice who is 30 years old.";
71+
72+
private final ObjectMapper objectMapper = new ObjectMapper();
73+
74+
protected ChatModel chatModel;
75+
76+
@RegisterExtension
77+
static OllamaService OLLAMA = OllamaServiceFactory.createSingletonService();
78+
79+
@Override
80+
protected void setupResources() throws Exception {
81+
super.setupResources();
82+
83+
JsonRawSchema jsonRawSchema = JsonRawSchema.from(PERSON_SCHEMA);
84+
ResponseFormat responseFormat = ResponseFormat.builder()
85+
.type(JSON)
86+
.jsonSchema(JsonSchema.builder()
87+
.name("person_schema")
88+
.rootElement(jsonRawSchema)
89+
.build())
90+
.build();
91+
92+
chatModel = ModelHelper.loadChatModel(OLLAMA, responseFormat);
93+
}
94+
95+
@Test
96+
void testStructuredOutputWithJsonSchema() throws Exception {
97+
MockEndpoint mockEndpoint = getMockEndpoint("mock:result");
98+
mockEndpoint.expectedMessageCount(1);
99+
100+
String response = template.requestBody("direct:structured-output", TEST_PROMPT, String.class);
101+
102+
mockEndpoint.assertIsSatisfied();
103+
104+
assertNotNull(response);
105+
JsonNode jsonResponse = objectMapper.readTree(response);
106+
107+
assertThat(jsonResponse.has("name")).isTrue();
108+
assertThat(jsonResponse.has("age")).isTrue();
109+
assertThat(jsonResponse.has("occupation")).isTrue();
110+
111+
assertThat(jsonResponse.get("name").asText()).contains("Alice");
112+
assertThat(jsonResponse.get("age").asInt()).isEqualTo(30);
113+
assertThat(jsonResponse.get("occupation").asText().toLowerCase()).containsAnyOf("engineer", "developer");
114+
}
115+
116+
@Override
117+
protected RouteBuilder createRouteBuilder() {
118+
AgentConfiguration configuration = new AgentConfiguration()
119+
.withChatModel(chatModel);
120+
121+
Agent agent = new AgentWithoutMemory(configuration);
122+
context.getRegistry().bind("structuredOutputAgent", agent);
123+
124+
return new RouteBuilder() {
125+
@Override
126+
public void configure() {
127+
from("direct:structured-output")
128+
.to("langchain4j-agent:structured-output?agent=#structuredOutputAgent")
129+
.to("json-validator:classpath:person-schema.json")
130+
.to("mock:result");
131+
}
132+
};
133+
}
134+
135+
}

components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/integration/ModelHelper.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
package org.apache.camel.component.langchain4j.agent.integration;
1919

2020
import dev.langchain4j.model.chat.ChatModel;
21+
import dev.langchain4j.model.chat.request.ResponseFormat;
2122
import dev.langchain4j.model.embedding.EmbeddingModel;
2223
import dev.langchain4j.model.ollama.OllamaChatModel;
2324
import dev.langchain4j.model.ollama.OllamaEmbeddingModel;
@@ -59,6 +60,32 @@ public static ChatModel loadChatModel(OllamaService ollamaService) {
5960
.build();
6061
}
6162

63+
/**
64+
* Load chat model with a specific ResponseFormat for structured outputs.
65+
*/
66+
public static ChatModel loadChatModel(OllamaService ollamaService, ResponseFormat responseFormat) {
67+
if (ollamaService instanceof OpenAIService openaiService) {
68+
return OpenAiChatModel.builder()
69+
.apiKey(openaiService.apiKey())
70+
.baseUrl(openaiService.baseUrl())
71+
.modelName(openaiService.modelName())
72+
.responseFormat(responseFormat)
73+
.temperature(1.0)
74+
.timeout(ofSeconds(120))
75+
.logRequests(true)
76+
.logResponses(true)
77+
.build();
78+
}
79+
80+
return OllamaChatModel.builder()
81+
.baseUrl(ollamaService.baseUrl())
82+
.modelName(ollamaService.modelName())
83+
.responseFormat(responseFormat)
84+
.temperature(0.3)
85+
.timeout(ofSeconds(120))
86+
.build();
87+
}
88+
6289
/**
6390
* Load embedding model from OllamaService. Detects if the service is OpenAIService and creates the appropriate
6491
* model type.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"type": "object",
3+
"properties": {
4+
"name": {
5+
"type": "string",
6+
"minLength": 1
7+
},
8+
"age": {
9+
"type": "integer",
10+
"minimum": 0
11+
},
12+
"occupation": {
13+
"type": "string",
14+
"minLength": 1
15+
}
16+
},
17+
"required": ["name", "age", "occupation"],
18+
"additionalProperties": false
19+
}

0 commit comments

Comments
 (0)