Camel Components

OpenAI

Since Camel 4.17

Both producer and consumer are supported

The LLM component provides integration with OpenAI and OpenAI-compatible APIs (Ollama, vLLM, LM Studio, OpenRouter, Azure OpenAI, and others) for chat completion, text embeddings, content moderation, audio transcription, audio translation, text-to-speech, and image generation and editing using the official openai-java SDK.

The Maven artifact remains camel-openai. Routes may use either the llm: or the openai: scheme.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-openai</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

Decisions

openai:decisions (also llm:decisions) accepts a native com.openai.models.decisions.DecisionCreateParams body and returns a com.openai.models.decisions.Decision body. It uses the endpoint’s managed OpenAI client, including credentials, base URL, TLS, proxy, timeout and retry settings. Decisions does not initialize configured MCP servers or route tools. The model is taken from the DecisionCreateParams body; the endpoint model option is not applied by this producer. The Semantic adapter instead builds its request using the endpoint’s configured model.

The producer emits GenAI observations with operation name decisions, request and response models, and input/output token counts when the provider returns usage. Failures are recorded through the shared GenAI error handling. Direct OpenAIEndpoint.decide() calls, including the Semantic adapter, do not emit these observations because they have no Exchange.

var request = DecisionCreateParams.builder()
    .model("gpt-6-luna")
    .input("The service is unavailable for every customer")
    .addQuestion(DecisionCreateParams.Question.Predicate.builder()
        .name("urgent").instructions("Does this require immediate attention?").build())
    .build();
var response = template.requestBody("openai:decisions", request, Decision.class);
double probability = response.answers().get(0).asPredicate().probability();

Use a model and API endpoint that implement Decisions. Inputs are text or native ordered text/image messages; images use inline PNG, JPEG, GIF or WebP base64 data URLs. Other input modalities and hosted image URLs are rejected by this integration. Requests contain 1–200 questions and at most 128 images. Responses are validated against the complete request before returning any result. OpenAI predicate probabilities have no built-in Boolean threshold.

Refusal raises OpenAIDecisionRefusalException, invalid provider output raises OpenAIDecisionResponseException, and transport/API/client-start failures raise OpenAIDecisionServiceException. No failure is converted into a decision value.

For named Semantic evaluations, typed Boolean/Choice/Score mapping, and body image input, add camel-semantic-openai. The OpenAI component itself has no dependency on camel-semantic. See the Decisions guide for the provider contract.

URI Format

llm:operation[?options]

The openai: scheme is a supported alias (openai:operation[?options]) for existing routes.

Prefer llm: in new routes for discoverability. Examples below use openai: for backward compatibility; substitute llm: in the operation URI when starting a new integration.

Supported operations:

  • chat-completion - Generate chat completions using language models

  • decisions - Native typed predicate, choice and rubric assessments of text and images

  • responses - Call the OpenAI Responses API (hosted tools, server-side conversation state; non-streaming)

  • responses-retrieve - Retrieve a stored Responses API response, such as one started in background mode

  • responses-cancel - Cancel a Responses API response still running in background mode

  • batch - Upload the requests of a batch as a JSONL file and create the batch that runs them offline

  • batch-retrieve - Report the status and request counts of a batch

  • batch-cancel - Cancel a batch that is still running

  • batch-results - Download the output or error file of a finished batch

See Responses API operation for usage (previousResponseId, builtin tools, MCP pass-through, background mode).

See Batch API operations for usage (building the input, polling, reading the results).

  • embeddings - Generate vector embeddings from text for semantic search and RAG applications

  • tool-execution - Execute MCP tool calls from a stored chat completion response (used in manual tool loops)

  • audio-transcription - Transcribe audio files to text using speech-to-text models (e.g., Whisper, GPT-4o Transcribe)

  • audio-translation - Transcribe and translate audio files into English text (e.g., Whisper)

  • audio-speech - Synthesize spoken audio from text using text-to-speech models (e.g., gpt-4o-mini-tts, tts-1)

  • moderation - Check text or an image against the OpenAI usage policies before it reaches a model

  • image-generation - Generate images from a text prompt (e.g., gpt-image-1, gpt-image-1-mini)

  • image-edit - Edit an existing image, optionally through a mask, from a text prompt

  • webhook - Receive the events OpenAI sends when a background response, a batch or a job finishes. It is a consumer: it is used in a from, see Webhook Events

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The OpenAI component supports the following options which are listed below.

Name Description Default Type

apiKey (common)

The API key that the endpoints of this component use unless they set the apiKey option. When neither is set, the OPENAI_API_KEY environment variable and then the openai.api.key system property are used.

String

audioModel (common)

The model that the audio-transcription and audio-translation endpoints of this component use unless they set the audioModel option.

String

baseUrl (common)

The base URL of the API that the endpoints of this component use unless they set the baseUrl option.

https://api.openai.com/v1

String

embeddingModel (common)

The model that the embeddings endpoints of this component use unless they set the embeddingModel option.

String

model (common)

The model that the chat-completion, responses and batch endpoints of this component use unless they set the model option.

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

useGlobalSslContextParameters (security)

Enable usage of global SSL context parameters.

false

boolean

Endpoint Options

The OpenAI endpoint is configured using URI syntax:

openai:operation

With the following path and query parameters:

Path Parameters

Name Description Default Type

operation (common)

Required The operation to perform. All operations are producers, used in a to(), except webhook, which receives the events that OpenAI posts to a webhook and is used in a from().

Enum values:

  • chat-completion

  • decisions

  • responses

  • responses-retrieve

  • responses-cancel

  • batch

  • batch-retrieve

  • batch-cancel

  • batch-results

  • embeddings

  • tool-execution

  • audio-transcription

  • audio-translation

  • audio-speech

  • moderation

  • image-generation

  • image-edit

  • webhook

OpenAIOperations

Query Parameters

Name Description Default Type

additionalBodyProperty (common)

Extra top-level fields of the JSON request body of chat-completion and responses (and of the batch requests built for them), such as fields that only an OpenAI-compatible server knows (e.g. additionalBodyProperty.top_k=20). A value that parses as JSON, such as a number, true or an object, is sent as that JSON, any other as a string. This is a multi-value option with prefix: additionalBodyProperty.

Map

additionalHeader (common)

Additional HTTP headers to send with every API call, such as additionalHeader.OpenAI-Organization=my-org, or additionalHeader.api-key=secret for a server that takes its key in another header. Values may contain secrets. This is a multi-value option with prefix: additionalHeader.

Map

additionalResponseHeader (common)

Copy fields of the answer message that the OpenAI API does not define, such as those an OpenAI-compatible server adds, to headers: the key is the field name in the message of the first choice, the value the header name (e.g. additionalResponseHeader.reasoning_content=MyReasoningHeader). A string field is copied as it is, any other as its JSON. Only used by chat-completion, and not for a streamed answer. This is a multi-value option with prefix: additionalResponseHeader.

Map

apiKey (common)

The API key, sent as a bearer token in the Authorization header. When not set, the OPENAI_API_KEY environment variable and then the openai.api.key system property are used. Ignored when oauthProfile is set. Optional for a server that checks no key, such as a local Ollama, vLLM or LM Studio (with baseUrl): without any key, the requests are sent without an Authorization header.

String

audioChunkingStrategy (common)

How audio-transcription cuts the audio into chunks: auto (normalize the loudness, then voice activity detection) or vad (server voice activity detection with its default settings). When not set, the audio is transcribed as one block. Required by gpt-4o-transcribe-diarize for audio longer than 30 seconds.

Enum values:

  • auto

  • vad

String

audioInclude (common)

Comma-separated additional information that audio-transcription asks for: logprobs, the log probabilities of the tokens, which are only in the full response (storeFullResponse). logprobs only works with the json format on gpt-4o-transcribe, gpt-4o-mini-transcribe and gpt-4o-mini-transcribe-2025-12-15.

String

audioKeywords (common)

Comma-separated words or phrases that guide the transcription, such as names and terms. Supported by gpt-transcribe.

String

audioKnownSpeakerNames (common)

Comma-separated names of up to 4 known speakers (such as customer,agent) for diarized transcription, in the order of the samples of audioKnownSpeakerReferences.

String

audioKnownSpeakerReferences (common)

Comma-separated audio samples of the known speakers for diarized transcription, 2 to 10 seconds each, in the order of audioKnownSpeakerNames. The API takes each sample as a data URL, whose own comma this option also splits on.

String

audioLanguage (common)

The language of the input audio in ISO-639-1 format (e.g. en), which improves accuracy and latency (audio-transcription only).

String

audioLanguages (common)

Comma-separated possible languages of the input audio, in ISO-639-1 format. Supported by gpt-transcribe.

String

audioModel (common)

The model of the audio-transcription and audio-translation operations, such as gpt-4o-transcribe or whisper-1 (OpenAI only offers whisper-1 for translation). Required by these operations.

String

audioPrompt (common)

A text to guide the style of the transcription or translation, or to continue a previous audio segment: in the language of the audio for audio-transcription, in English for audio-translation. Not supported by gpt-4o-transcribe-diarize.

String

audioResponseFormat (common)

The format in which the API returns the transcript. The message body is its text (for srt and vtt the subtitles); verbose_json also sets the duration and detected language headers, diarized_json the speaker segments. gpt-4o-transcribe and gpt-4o-mini-transcribe only support json, and audio-translation does not support diarized_json.

Enum values:

  • json

  • text

  • srt

  • verbose_json

  • vtt

  • diarized_json

json

String

audioTemperature (common)

The sampling temperature of audio-transcription and audio-translation, between 0 and 1. With 0, the model raises the temperature itself, using log probabilities, until certain thresholds are hit. When not set, it is not sent and the API default applies.

Double

audioTimestampGranularities (common)

Comma-separated timestamp granularities of audio-transcription: word, segment, or both. Requires audioResponseFormat=verbose_json, and the timestamps are only in the full response (storeFullResponse). Word timestamps add latency. Not available for gpt-4o-transcribe-diarize.

String

autoToolExecution (common)

When true, run the tool calls the model asks for, both MCP tools (mcpServer.*) and route tools (tags), and send the results back to the model until it answers. When false, the tool calls are returned as the message body for the route to handle.

true

boolean

background (common)

Run the model response in the background (Responses API only). The exchange completes as soon as the response is queued, with an empty body and the CamelOpenAIResponseStatus header, and the response is stored so that it can be retrieved later. Cannot be combined with automatic tool execution.

false

boolean

baseUrl (common)

The base URL of the API, the path included, such as http://localhost:11434/v1 for Ollama or the URL of another OpenAI-compatible server. The OPENAI_BASE_URL environment variable is not read.

https://api.openai.com/v1

String

batchEndpoint (common)

The endpoint every request in a batch calls. Required by the batch operation, which validates it against the endpoints the Batch API supports.

Enum values:

  • /v1/responses

  • /v1/chat/completions

  • /v1/embeddings

  • /v1/completions

  • /v1/moderations

  • /v1/images/generations

  • /v1/images/edits

  • /v1/videos

String

batchMetadata (common)

Metadata (key-value pairs) to attach to a batch, used to find it again later (e.g. batchMetadata.job=nightly-enrichment). This is a multi-value option with prefix: batchMetadata.

Map

batchResultsFile (common)

Which result file the batch-results operation downloads: the output file holding the results of the successful requests, or the error file holding the failed ones.

Enum values:

  • output

  • error

output

String

builtinTools (common)

Comma-separated hosted tools that OpenAI runs itself for the responses operation: web_search, file_search (which needs fileSearchVectorStoreIds) and code_interpreter (in a container that OpenAI creates).

String

connectTimeout (common)

Timeout in milliseconds for establishing the TCP connection to the API. A connect timeout means the endpoint was unreachable, so the request never ran and is safe to retry. When 0 or negative, the SDK default (1 minute) is used.

0

long

conversationHistoryProperty (common)

The name of the exchange property that holds the conversation memory: the List of ChatCompletionMessageParam of chat-completion, which tool-execution also reads and updates, or the id of the last response of responses.

CamelOpenAIConversationHistory

String

conversationId (common)

Id of a conversation created with the OpenAI Conversations API to run the request in. The conversation keeps its items across exchanges. Cannot be combined with previousResponseId (Responses API only).

String

conversationMemory (common)

Enable conversation memory per Exchange. The chat-completion operation keeps the message history in the conversationHistoryProperty exchange property. The responses operation keeps the conversation on the server, stores the last response id in that property and sends it as previous_response_id, which requires a server that stores responses.

false

boolean

developerMessage (common)

The developer message, instructions that the model follows over the user message: sent after the system message and before the conversation by chat-completion, and as the first input item by responses (and in the batch requests for them).

String

dimensions (common)

The number of dimensions of the returned vectors, for the models that can shorten them (text-embedding-3 and later). When not set, the vectors have the full size of the model.

Integer

embeddingModel (common)

The model of the embeddings operation and of the /v1/embeddings requests that the batch operation builds, such as text-embedding-3-small. Required by the embeddings operation.

String

encodingFormat (common)

The format in which the API returns the vectors: base64 (a smaller response) or float. The SDK decodes both, so the message body is a List of Float either way. Use float for an OpenAI-compatible server that does not support base64.

Enum values:

  • float

  • base64

base64

String

fileSearchVectorStoreIds (common)

Comma-separated ids of the vector stores that the file_search hosted tool searches. Required when builtinTools includes file_search.

String

hallucinatedToolNameStrategy (common)

Strategy for handling tool names hallucinated by the model (tool not found in any MCP server). 'failExchange' (default) throws an IllegalStateException, failing the exchange immediately. 'repromptModel' sends a corrective tool result listing the available tools so the model can self-correct and retry. The maxToolIterations option bounds retries.

Enum values:

  • failExchange

  • repromptModel

failExchange

HallucinatedToolNameStrategy

hostedMcpTools (common)

JSON array of hosted MCP tool definitions passed to the Responses API as OpenAI mcp tools. Every field of the API is sent, such as server_label, server_url, require_approval, allowed_tools, headers and authorization. Marked secret because it can carry credentials.

String

imageBackground (common)

The background of the generated image. Only supported by the GPT image models, and a transparent background requires the png or webp output format.

Enum values:

  • transparent

  • opaque

  • auto

String

imageCount (common)

The number of images to generate, between 1 and 10. dall-e-3 only supports 1.

Integer

imageInputFidelity (common)

How closely the edit must match the style and features of the input image. Only supported by the image-edit operation on gpt-image-1 and gpt-image-1.5.

Enum values:

  • high

  • low

String

imageModel (common)

The model to use for image generation or editing (e.g., gpt-image-1, gpt-image-1-mini, gpt-image-1.5, gpt-image-2). Required for the image-generation and image-edit operations, because the model determines which of the other image options are accepted. The DALL-E models are no longer offered by OpenAI, but remain valid values for OpenAI-compatible providers.

String

imageModeration (common)

The content moderation level applied to image generation. Only supported by the GPT image models.

Enum values:

  • low

  • auto

String

imageOutputCompression (common)

The compression level from 0 to 100 for the webp and jpeg output formats. Only supported by the GPT image models.

Integer

imageOutputFormat (common)

The output format of the generated image. Only supported by the GPT image models, which default to png.

Enum values:

  • png

  • jpeg

  • webp

String

imagePrompt (common)

The prompt describing the image to generate, or the edit to apply. For image-generation the message body is used when this is not set; for image-edit the body carries the input image, so the prompt must come from this option or from the CamelOpenAIImagePrompt header.

String

imageQuality (common)

The quality of the generated image. GPT image models accept auto, high, medium and low; hd and standard are DALL-E values kept for OpenAI-compatible providers.

Enum values:

  • auto

  • high

  • medium

  • low

  • hd

  • standard

String

imageResponseFormat (common)

The response format of the generated image. The OpenAI images endpoint rejects this option: the GPT image models always return base64, and the DALL-E models that used to accept it are no longer offered. It is only sent when explicitly set, and is kept for OpenAI-compatible providers that still implement the older images API.

Enum values:

  • url

  • b64_json

String

imageSize (common)

The size of the generated image (e.g., 1024x1024, 1536x1024, 1024x1536, auto). The accepted values depend on the model.

String

imageStyle (common)

The style of the generated image. A dall-e-3 option, so only useful with OpenAI-compatible providers.

Enum values:

  • vivid

  • natural

String

jsonSchema (common)

A JSON schema (a JSON object) that the answer must follow (structured outputs), sent as the json_schema response format named camel_schema by chat-completion, responses and batch. Inline JSON, or for chat-completion and responses also a resource such as resource:classpath:schema.json. Camel does not validate the answer against it. Ignored when outputClass is set.

String

jsonSchemaStrict (common)

Whether the model must follow jsonSchema exactly (strict structured outputs): sets strict to true in the JSON schema response format of chat-completion, the Responses API and batch. OpenAI then only accepts a schema that meets its rules, every property of each object listed in required and additionalProperties false on every object, and rejects any other with HTTP 400. Without it, OpenAI takes the schema as a hint, and the answer can miss required fields or have others. Other OpenAI-compatible servers may ignore it.

false

boolean

maxAgenticTokens (common)

Maximum cumulative prompt plus completion tokens allowed across the tool loop. When 0 or negative, no token budget is enforced. Enforcement runs after each API call that requests further tool execution, so actual spend may exceed the configured budget by up to one call (typically the largest, as the prompt grows each iteration). A final text response is returned even when cumulative usage exceeds the budget; otherwise the exchange fails with an IllegalStateException.

0

long

maxHistoryMessages (common)

When conversationMemory is enabled, retain at most this many messages in the exchange conversation history. System and developer messages are prepended separately and are not stored in history. Assistant tool-call blocks are kept intact and may retain slightly more than this limit to preserve tool result pairing. When 0, no message limit is applied.

0

int

maxHistoryTokens (common)

When conversationMemory is enabled, trim conversation history using a token estimate (character count / 4, including image payload size for multi-modal user messages). Oldest segments are dropped first until the estimated tokens are within this limit. Assistant tool-call blocks are removed as a unit with their tool results. The most recent segment is always retained, even when it alone exceeds this limit. When 0, no token limit is applied.

0

int

maxRetries (common)

Maximum number of times the OpenAI SDK client retries a failed request, with exponential backoff: on a connection error and on HTTP 408, 409, 429 and 5xx, waiting as long as a Retry-After header asks. 0 disables the retries.

2

int

maxTokens (common)

Upper bound for the number of tokens the model generates for an answer, the reasoning tokens included: sent as max_completion_tokens by chat-completion and as max_output_tokens by responses (and in the batch requests for them). When not set, the limit of the model applies.

Integer

maxToolIterations (common)

Maximum number of rounds of tool calls in the tool loop of chat-completion and responses. When the model still asks for tools after that many rounds, the exchange fails with an IllegalStateException.

50

int

mcpProtocolVersions (common)

Comma-separated list of MCP protocol versions to advertise when connecting to MCP servers using Streamable HTTP transport. When not set, the SDK default is used. Example: 2024-11-05,2025-03-26,2025-06-18.

String

mcpReconnect (common)

Automatically reconnect to MCP servers when a tool call fails due to a transport error, and retry the call once.

true

boolean

mcpServer (common)

MCP (Model Context Protocol) server configurations. Define servers using prefix notation, where myServer stands for the name of the server: mcpServer.myServer.transportType=stdio|sse|streamableHttp (sse is deprecated), mcpServer.myServer.command=npx (stdio), mcpServer.myServer.args=arg1,arg2 (stdio, comma-separated), mcpServer.myServer.url=http://localhost:8080/mcp (sse/streamableHttp, the URL of the endpoint of the server, path included, such as http://localhost:8080/sse for sse), mcpServer.myServer.oauthProfile=myProfile (OAuth profile for HTTP auth, requires camel-oauth), mcpServer.myServer.toolNames=tool1,tool2 (optional comma-separated include list to restrict which tools are registered from this server). This is a multi-value option with prefix: mcpServer.

Map

mcpTimeout (common)

Timeout in seconds for MCP tool call requests. Applies to all MCP operations including tool execution and initialization.

20

int

mcpToolRefresh (common)

Refresh the advertised tool list when an MCP server notifies that its tools changed. Set to false to keep the tool list fixed to what was listed when the endpoint started, for deployments that require a deterministic set of tools.

true

boolean

model (common)

The model of the chat-completion and responses operations and of the requests that the batch operation builds for them, such as gpt-5 or a model name of an OpenAI-compatible server. Required by these operations; the other operations have model options of their own, and decisions takes the model from its body.

String

moderationModel (common)

The model of the moderation operation and of the /v1/moderations requests that the batch operation builds. The omni-moderation models also moderate images.

omni-moderation-latest

String

outputClass (common)

Fully qualified name of a Java class from which the OpenAI SDK builds a strict JSON schema that the answer must follow (structured outputs). The message body is the JSON text of the answer, not an instance of the class. Takes precedence over jsonSchema. Used by chat-completion, responses and batch.

String

parallelToolExecution (common)

Execute the tool calls returned by the model in a single response concurrently instead of sequentially. Tool calls in the same batch are independent by design, so this reduces the latency of a batch to that of its slowest tool. Results are always fed back to the model in the original tool call order. Note that with toolExecutionErrorStrategy=failExchange the sibling tool calls already dispatched complete before the exchange fails.

false

boolean

parallelToolTimeout (common)

Timeout in milliseconds for a batch of parallel tool calls, so that one slow tool cannot block the whole batch. The timeout applies to the batch as a whole, not per tool call. A tool call that exceeds it is cancelled and handled according to toolExecutionErrorStrategy. The default of 0 disables the batch timeout and relies on mcpTimeout, which already bounds each individual MCP request. Only used when parallelToolExecution=true.

0

long

previousResponseId (common)

The id of a stored response that the request continues, sent as previous_response_id, so that the server keeps the conversation state (responses only). Cannot be combined with conversationId. With conversationMemory, the id of the last response of the exchange is used when this is not set.

String

readTimeout (common)

Timeout in milliseconds for reading the response. A read timeout means the model was slow mid-generation, so the request may have been processed. When 0 or negative, requestTimeout applies.

0

long

requestTimeout (common)

Timeout in milliseconds for a whole HTTP call of the OpenAI SDK client, from sending the request to reading the end of the response (of a streamed answer too). Each retry is a new call. When 0 or negative, the SDK default (10 minutes) is used. Also the read and write timeout when readTimeout and writeTimeout are not set.

0

long

speechInstructions (common)

Optional instructions to control the voice of the generated audio. Does not work with tts-1 or tts-1-hd.

String

speechModel (common)

The model of the audio-speech operation, such as gpt-4o-mini-tts, tts-1 or tts-1-hd. Required by the operation.

String

speechResponseFormat (common)

The audio format of the generated speech. The message body is the audio as a byte[], and the Content-Type header is set to its media type.

Enum values:

  • mp3

  • opus

  • aac

  • flac

  • wav

  • pcm

mp3

String

speechSpeed (common)

The speed of the generated audio, from 0.25 to 4.0. When not set, it is not sent and the API uses 1.0, the normal speed.

Double

speechVoice (common)

The voice of the generated audio: alloy, ash, ballad, coral, echo, fable, onyx, nova, sage, shimmer, verse, marin or cedar.

alloy

String

storeFullResponse (common)

Keep the full SDK response object in an exchange property (not a header), except for a streamed answer: CamelOpenAIResponse for chat-completion, which tool-execution needs, CamelOpenAIResponsesResponse for responses, responses-retrieve and responses-cancel, CamelOpenAIBatchResponse for batch, batch-retrieve and batch-cancel, CamelOpenAIModerationResponse for moderation, CamelOpenAIImageResponse for image-generation and image-edit, CamelOpenAIEmbeddingsResponse for embeddings, CamelOpenAIAudioTranscriptionResponse for audio-transcription and CamelOpenAIAudioTranslationResponse for audio-translation.

false

boolean

streaming (common)

Stream the answer of chat-completion: the message body is an Iterator of ChatCompletionChunk, for example for a streaming split, and the stream is closed when the exchange completes. A streamed answer sets no response headers, does not update the conversation memory and is not stripped of think blocks. When tools run in the tool loop, the request is not streamed. The responses and batch operations reject it.

false

boolean

stripThinking (common)

Remove the think block (from the opening to the closing think tag) at the start of the answer of chat-completion, which reasoning models such as Qwen3 and DeepSeek-R1 write on some servers, and put its text in the CamelOpenAIThinkingContent header. A streamed answer is not changed.

false

boolean

systemMessage (common)

The system message, sent before the conversation by chat-completion and as the instructions by responses (and in the batch requests for them). With conversationMemory, a chat-completion endpoint with this option clears the stored history at every call, so every call starts a new conversation.

String

tags (common)

Comma-separated tags for discovering route-based tools registered via the ai-tool component. When set, matching tools from the shared AiToolRegistry are exposed to the model alongside MCP tools, and run in the same tool loop (see autoToolExecution). No MCP server is needed for route tools.

String

temperature (common)

The sampling temperature, between 0 and 2: higher values such as 0.8 make the answer more random, lower values such as 0.2 more focused. OpenAI recommends changing temperature or topP, not both. When not set, it is not sent and the model default applies. Used by chat-completion, responses and batch.

Double

toolExecutionErrorStrategy (common)

Strategy for handling exceptions thrown during MCP tool execution. 'failExchange' (default) propagates the exception to the Camel exchange so that standard Camel error handling (onException, dead-letter channel) can process it. This is the safer default because 'repromptModel' sends raw exception messages (which may contain connection strings, hostnames, or internal paths) to a third-party LLM provider. 'repromptModel' catches the error and sends it back to the model as a tool result so the model can attempt to recover.

Enum values:

  • failExchange

  • repromptModel

failExchange

ToolExecutionErrorStrategy

toolSearch (common)

When true, route tools marked searchable and remote MCP tools are omitted from the initial model request and exposed through one synthetic search tool. Directly visible tools stay in the request. Search is a visibility policy, not authorization. Enabling it does not skip MCP tools/list; it only reduces the definitions sent to the model. When false, every eligible tool is sent as before and the searchable flag has no effect.

false

boolean

toolSearchEmbeddingModel (common)

Embedding model used when toolSearchStrategy=VECTOR, for example text-embedding-3-small. Required for vector search. It is not read from the embeddings operation model option.

String

toolSearchMaxResults (common)

Maximum number of tools returned by one tool search. Route and MCP tools are ranked together against this limit.

5

int

toolSearchStrategy (common)

How tool search ranks route and MCP tools. 'KEYWORD' matches the tool name and description. 'VECTOR' uses cosine similarity and requires toolSearchEmbeddingModel. Vector search does not fall back to keyword search.

Enum values:

  • KEYWORD

  • VECTOR

KEYWORD

AiToolSearchStrategy

topP (common)

Nucleus sampling, between 0 and 1: the model only considers the tokens that make up this top probability mass, so 0.1 means the top 10%. OpenAI recommends changing temperature or topP, not both. When not set, it is not sent and the model default applies. Used by chat-completion, responses and batch.

Double

userMessage (common)

The text of the user message of chat-completion and responses. When set, it replaces a text body, which is then not sent. With an image or PDF body (chat-completion also audio), it is the text sent along with the file, and then required.

String

writeTimeout (common)

Timeout in milliseconds for writing the request body, which matters for large payloads such as audio and image uploads. When 0 or negative, requestTimeout applies.

0

long

httpServerComponent (consumer)

The component, or the bean, that serves the HTTP endpoint of the webhook operation. It must implement RestConsumerFactory, for example platform-http, which is used when it is on the classpath. Also read from the rest configuration when not set.

String

webhookMaxPayloadSize (consumer)

The largest webhook request body that is read, in bytes. A bigger request is answered with 413 and is not verified.

1048576

int

webhookPath (consumer)

The HTTP path the webhook operation listens on.

/openai/webhook

String

webhookSecret (consumer)

The webhook signing secret of the OpenAI dashboard (it starts with whsec_), used to verify the signature of the events. Required by the webhook operation.

String

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

oauthProfile (security)

OAuth profile name for obtaining an access token via the OAuth 2.0 Client Credentials grant. When set, the token is acquired from the configured identity provider and used instead of apiKey. Requires camel-oauth on the classpath. The profile properties are resolved from camel.oauth.myProfile.client-id, camel.oauth.myProfile.client-secret, and camel.oauth.myProfile.token-endpoint, where myProfile is the profile name.

String

sslContextParameters (security)

SSLContextParameters to use for configuring SSL/TLS. When set, all the other ssl options are ignored. When not set, the global SSL context parameters are used if the component has useGlobalSslContextParameters enabled.

SSLContextParameters

sslEndpointAlgorithm (security)

Whether to verify that the hostname of the server matches its certificate: an empty value or none disables the check, any other value, such as https, keeps it. Only applies when sslTruststoreLocation or sslKeystoreLocation is set; otherwise the hostname is always verified.

https

String

sslKeymanagerAlgorithm (security)

The algorithm used by the key manager factory for SSL connections.

SunX509

String

sslKeyPassword (security)

The password of the private key in the key store file. When not set, the key store password is used.

String

sslKeystoreLocation (security)

The path of the key store file on the file system, with the client certificate and key for two-way TLS (mutual TLS) authentication with the server.

String

sslKeystorePassword (security)

The store password for the key store file.

String

sslKeystoreType (security)

The file format of the key store file.

JKS

String

sslProtocol (security)

The protocol of the SSLContext created from the trust store and key store options, such as TLSv1.3 or TLSv1.2.

TLSv1.3

String

sslTrustmanagerAlgorithm (security)

The algorithm used by the trust manager factory for SSL connections.

PKIX

String

sslTruststoreLocation (security)

The path of the trust store file on the file system, used to validate the certificate of the server. When neither a trust store nor a key store is set, the default trust store of the JVM is used.

String

sslTruststorePassword (security)

The password for the trust store file. If a password is not set, the configured trust store can still be used, but integrity checking is disabled.

String

sslTruststoreType (security)

The file format of the trust store file.

JKS

String

Message Headers

The OpenAI component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelOpenAIWebhookEventType (consumer)

Constant: WEBHOOK_EVENT_TYPE

The type of the webhook event, such as response.completed or batch.completed.

String

CamelOpenAIWebhookEventId (consumer)

Constant: WEBHOOK_EVENT_ID

The id of the webhook event.

String

CamelOpenAIWebhookObjectId (consumer)

Constant: WEBHOOK_OBJECT_ID

The id of the object the event is about, such as the response id of response.completed, which the responses-retrieve operation takes.

String

CamelOpenAIWebhookCreatedAt (consumer)

Constant: WEBHOOK_CREATED_AT

When the event was created, in seconds since the epoch.

Long

CamelOpenAIUserMessage (common)

Constant: USER_MESSAGE

The text of the user message of chat-completion and responses, in place of the userMessage option: it replaces a text body, and is the text sent along with an image, PDF or audio body.

String

CamelOpenAISystemMessage (common)

Constant: SYSTEM_MESSAGE

The system message of chat-completion (the instructions of responses), in place of the systemMessage option. Unlike the option, it does not clear the conversation memory.

String

CamelOpenAIDeveloperMessage (common)

Constant: DEVELOPER_MESSAGE

The developer message of chat-completion and responses, in place of the developerMessage option.

String

CamelOpenAIModel (common)

Constant: MODEL

The model of chat-completion, responses and the requests that batch builds, in place of the model option.

String

CamelOpenAITemperature (common)

Constant: TEMPERATURE

The sampling temperature, between 0 and 2, in place of the temperature option.

Double

CamelOpenAITopP (common)

Constant: TOP_P

The nucleus sampling probability mass, between 0 and 1, in place of the topP option.

Double

CamelOpenAIMaxTokens (common)

Constant: MAX_TOKENS

The upper bound for the number of tokens of the answer, in place of the maxTokens option.

Integer

CamelOpenAIPreviousResponseId (common)

Constant: PREVIOUS_RESPONSE_ID

The id of the stored response that a responses request continues, in place of the previousResponseId option. Also set on the answer of responses when it continued another response.

String

CamelOpenAIConversationId (common)

Constant: CONVERSATION_ID

The id of a conversation created with the Conversations API to run the responses request in, in place of the conversationId option. chat-completion only records it in its observations.

String

CamelOpenAIToolSearchSessionId (common)

Constant: TOOL_SEARCH_SESSION_ID

An id under which the tools that tool search found are kept across exchanges, so that a later exchange with the same id offers them without searching again. Only used with toolSearch and conversationMemory.

String

CamelOpenAIStreaming (common)

Constant: STREAMING

Whether to stream the answer of chat-completion, in place of the streaming option. responses and batch fail when it is true.

Boolean

CamelOpenAIOutputClass (common)

Constant: OUTPUT_CLASS

The fully qualified name of the Java class whose JSON schema the answer must follow, in place of the outputClass option.

String

CamelOpenAIJsonSchema (common)

Constant: JSON_SCHEMA

The JSON schema that the answer must follow, as inline JSON, in place of the jsonSchema option.

String

CamelOpenAIJsonSchemaStrict (common)

Constant: JSON_SCHEMA_STRICT

Whether the model must follow the JSON schema exactly (strict structured outputs), in place of the jsonSchemaStrict option.

Boolean

CamelOpenAIStripThinking (common)

Constant: STRIP_THINKING

Whether to remove the think block at the start of the answer of chat-completion, in place of the stripThinking option.

Boolean

CamelOpenAIMediaType (common)

Constant: MEDIA_TYPE

The MIME type of the message body when sending a file or binary content (File, WrappedFile, byte[] or InputStream) to the model. Takes precedence over component content-type headers and automatic MIME type detection.

String

Content-Type (common)

Constant: CONTENT_TYPE

The content type of a binary body (byte[], InputStream or a remote file) sent to the model, read when the CamelOpenAIMediaType header and the content type headers of the cloud storage components (such as CamelAwsS3ContentType) are not set. Image generation and image edit set it to the type of a binary image result, and audio speech to the type of the audio.

String

CamelFileContentType (common)

Constant: FILE_CONTENT_TYPE

The content type of a file or binary body sent to the model, as the file components set it. Read when the CamelOpenAIMediaType header is not set, before the file name extension.

String

CamelFileName (common)

Constant: FILE_NAME

The name of the file of a binary body, as the file components set it. Its extension gives the MIME type when no content type header is set, and it is the file name of an uploaded PDF or audio file when the CamelFileNameOnly header is not set.

String

CamelFileNameOnly (common)

Constant: FILE_NAME_ONLY

The name of the file of a binary body without its path, as the file components set it. It is the file name of an uploaded PDF, audio file or image, and takes precedence over the CamelFileName header.

String

CamelOpenAIThinkingContent (common)

Constant: THINKING_CONTENT

The text of the think block that stripThinking removed from the start of the answer.

String

CamelOpenAIReasoningContent (common)

Constant: REASONING_CONTENT

The reasoning_content field of the answer message of chat-completion, which some OpenAI-compatible servers return for reasoning models such as Qwen3 and DeepSeek-R1.

String

CamelOpenAIResponseModel (common)

Constant: RESPONSE_MODEL

The model that produced the answer of chat-completion or responses, as the API reports it.

String

CamelOpenAIResponseId (common)

Constant: RESPONSE_ID

The unique identifier for the completion response. The responses-retrieve and responses-cancel operations read the id of the response to act on from this header.

String

CamelOpenAIFinishReason (common)

Constant: FINISH_REASON

Why the model stopped, such as stop, length, tool_calls or content_filter for chat-completion. For responses, stop when the response completed, otherwise its status.

String

CamelOpenAIPromptTokens (common)

Constant: PROMPT_TOKENS

The number of tokens used in the prompt for the latest API call.

Long

CamelOpenAICompletionTokens (common)

Constant: COMPLETION_TOKENS

The number of tokens used in the completion for the latest API call.

Long

CamelOpenAITotalTokens (common)

Constant: TOTAL_TOKENS

The total number of tokens used (prompt + completion) for the latest API call.

Long

CamelOpenAIResponseAnnotations (common)

Constant: RESPONSE_ANNOTATIONS

The annotations attached to the output text of a Responses API answer, such as the url_citation and file_citation citations of web_search and file_search. Each entry is a map of the API fields.

List

CamelOpenAIResponseStatus (common)

Constant: RESPONSE_STATUS

The status of a Responses API response: completed, failed, in_progress, cancelled, queued or incomplete.

String

CamelOpenAIToolIterations (common)

Constant: TOOL_ITERATIONS

The number of rounds of tool calls in the tool loop of chat-completion and responses. tool-execution sets it to the number of tool calls it ran.

Integer

CamelOpenAIMcpToolCalls (common)

Constant: MCP_TOOL_CALLS

The names of the tools, MCP and route tools, called in the tool loop, in call order.

List

CamelOpenAIMcpReturnDirect (common)

Constant: MCP_RETURN_DIRECT

Whether the response came directly from a tool with returnDirect=true, rather than from the LLM.

Boolean

CamelOpenAIAgenticPromptTokens (common)

Constant: AGENTIC_PROMPT_TOKENS

Cumulative prompt tokens consumed across all agentic loop iterations.

Long

CamelOpenAIAgenticCompletionTokens (common)

Constant: AGENTIC_COMPLETION_TOKENS

Cumulative completion tokens consumed across all agentic loop iterations.

Long

CamelOpenAIAgenticTotalTokens (common)

Constant: AGENTIC_TOTAL_TOKENS

Cumulative total tokens consumed across all agentic loop iterations.

Long

CamelOpenAIResponse (common)

Constant: RESPONSE

The complete ChatCompletion of chat-completion, kept as an exchange property (not a header) when storeFullResponse is enabled. tool-execution reads the tool calls from it.

ChatCompletion

CamelOpenAIResponsesResponse (common)

Constant: RESPONSES_RESPONSE

The complete Response of the Responses API, kept as an exchange property (not a header) when storeFullResponse is enabled.

Response

CamelOpenAIModerationResponse (common)

Constant: MODERATION_RESPONSE

The complete moderation response, kept as an exchange property (not a header) when storeFullResponse is enabled.

ModerationCreateResponse

CamelOpenAIImageResponse (common)

Constant: IMAGE_RESPONSE

The complete image generation or edit response, kept as an exchange property (not a header) when storeFullResponse is enabled.

ImagesResponse

CamelOpenAIEmbeddingsResponse (common)

Constant: EMBEDDINGS_RESPONSE

The complete embeddings response, kept as an exchange property (not a header) when storeFullResponse is enabled.

CreateEmbeddingResponse

CamelOpenAIAudioTranscriptionResponse (common)

Constant: AUDIO_TRANSCRIPTION_RESPONSE

The complete audio transcription response, kept as an exchange property (not a header) when storeFullResponse is enabled.

TranscriptionCreateResponse

CamelOpenAIAudioTranslationResponse (common)

Constant: AUDIO_TRANSLATION_RESPONSE

The complete audio translation response, kept as an exchange property (not a header) when storeFullResponse is enabled.

TranslationCreateResponse

CamelOpenAIBatchId (common)

Constant: BATCH_ID

The id of the batch to act on. Set by the batch operation, and read by batch-retrieve, batch-cancel and batch-results.

String

CamelOpenAIBatchEndpoint (common)

Constant: BATCH_ENDPOINT

The endpoint every request in the batch calls, such as /v1/chat/completions. Overrides the batchEndpoint option.

String

CamelOpenAIBatchMetadata (common)

Constant: BATCH_METADATA

Metadata to attach to the batch. Overrides the batchMetadata option.

Map

CamelOpenAIBatchCustomId (common)

Constant: BATCH_CUSTOM_ID

The custom_id of the request that OpenAIBatchAggregationStrategy builds from this message. Defaults to the message id.

String

CamelOpenAIBatchResultsFile (common)

Constant: BATCH_RESULTS_FILE

Which result file the batch-results operation downloads: 'output' or 'error'. Overrides the batchResultsFile option.

String

CamelOpenAIBatchStatus (common)

Constant: BATCH_STATUS

The status of the batch: validating, failed, in_progress, finalizing, completed, expired, cancelling or cancelled.

String

CamelOpenAIBatchInputFileId (common)

Constant: BATCH_INPUT_FILE_ID

The id of the uploaded input file of the batch.

String

CamelOpenAIBatchOutputFileId (common)

Constant: BATCH_OUTPUT_FILE_ID

The id of the file holding the results of the successful requests.

String

CamelOpenAIBatchErrorFileId (common)

Constant: BATCH_ERROR_FILE_ID

The id of the file holding the results of the failed requests.

String

CamelOpenAIBatchRequestCountTotal (common)

Constant: BATCH_REQUEST_COUNT_TOTAL

Total number of requests in the batch.

Long

CamelOpenAIBatchRequestCountCompleted (common)

Constant: BATCH_REQUEST_COUNT_COMPLETED

Number of requests in the batch that completed successfully.

Long

CamelOpenAIBatchRequestCountFailed (common)

Constant: BATCH_REQUEST_COUNT_FAILED

Number of requests in the batch that failed.

Long

CamelOpenAIBatchErrors (common)

Constant: BATCH_ERRORS

The errors that made the batch fail validation, each a map of the code, message, param and line fields of the API.

List

CamelOpenAIBatchResponse (common)

Constant: BATCH_RESPONSE

The complete Batch object, kept as an exchange property (not a header) when storeFullResponse is enabled.

Batch

CamelOpenAIEmbeddingModel (common)

Constant: EMBEDDING_MODEL

The model of embeddings, in place of the embeddingModel option.

String

CamelOpenAIEmbeddingDimensions (common)

Constant: EMBEDDING_DIMENSIONS

The number of dimensions of the returned vectors, in place of the dimensions option.

Integer

CamelOpenAIEmbeddingResponseModel (common)

Constant: EMBEDDING_RESPONSE_MODEL

The embedding model that produced the vectors, as the API reports it.

String

CamelOpenAIEmbeddingCount (common)

Constant: EMBEDDING_COUNT

The number of vectors returned.

Integer

CamelOpenAIEmbeddingVectorSize (common)

Constant: EMBEDDING_VECTOR_SIZE

The number of dimensions of the returned vectors.

Integer

CamelOpenAIReferenceEmbedding (common)

Constant: REFERENCE_EMBEDDING

A vector (a List of Float) to compare with the vector of the first input: their cosine similarity is then set in the CamelOpenAISimilarityScore header.

List

CamelOpenAISimilarityScore (common)

Constant: SIMILARITY_SCORE

The cosine similarity between the CamelOpenAIReferenceEmbedding vector and the vector of the first input, from -1.0 to 1.0, where higher is more similar.

Double

CamelOpenAIOriginalText (common)

Constant: ORIGINAL_TEXT

The input of embeddings: the text, or the List of texts for a List body.

String or List

CamelOpenAIModerationModel (common)

Constant: MODERATION_MODEL

The model of moderation, in place of the moderationModel option.

String

CamelOpenAIModerationText (common)

Constant: MODERATION_TEXT

Text to moderate together with an image body, such as the caption the image was posted with. The text and the image are scored as one input and share a single verdict. Ignored when the body is not an image.

String

CamelOpenAIModerationFlagged (common)

Constant: MODERATION_FLAGGED

Whether the moderation API flagged the input as violating the usage policies. For a batch of inputs this is true when at least one input was flagged.

Boolean

CamelOpenAIModerationResults (common)

Constant: MODERATION_RESULTS

One verdict per moderated input, in the order of the inputs. Each entry holds the keys 'input', 'flagged', 'categories', 'categoryScores' and, when the provider reports it, 'categoryAppliedInputTypes', so a batch can be split and routed per item.

List

CamelOpenAIModerationCategories (common)

Constant: MODERATION_CATEGORIES

The moderation categories and whether each one was violated, for a single input. Not set for a list body, where 'CamelOpenAIModerationResults' carries the verdicts.

Map

CamelOpenAIModerationCategoryScores (common)

Constant: MODERATION_CATEGORY_SCORES

The moderation confidence score per category, for a single input. Not set for a list body, where 'CamelOpenAIModerationResults' carries the verdicts.

Map

CamelOpenAIModerationResponseModel (common)

Constant: MODERATION_RESPONSE_MODEL

The moderation model used in the response.

String

CamelOpenAIAudioModel (common)

Constant: AUDIO_MODEL

The model of audio-transcription and audio-translation, in place of the audioModel option.

String

CamelOpenAIAudioLanguage (common)

Constant: AUDIO_LANGUAGE

The language of the input audio in ISO-639-1 format, in place of the audioLanguage option.

String

CamelOpenAIAudioResponseFormat (common)

Constant: AUDIO_RESPONSE_FORMAT

The format in which the API returns the transcript (json, text, srt, verbose_json, vtt or diarized_json), in place of the audioResponseFormat option.

String

CamelOpenAIAudioTemperature (common)

Constant: AUDIO_TEMPERATURE

The sampling temperature of audio-transcription and audio-translation, between 0 and 1, in place of the audioTemperature option.

Double

CamelOpenAIAudioPrompt (common)

Constant: AUDIO_PROMPT

A text to guide the style of the transcript or to continue a previous audio segment, in place of the audioPrompt option.

String

CamelOpenAIAudioTimestampGranularities (common)

Constant: AUDIO_TIMESTAMP_GRANULARITIES

Comma-separated timestamp granularities (word, segment, or both) for verbose_json, in place of the audioTimestampGranularities option.

String

CamelOpenAIAudioChunkingStrategy (common)

Constant: AUDIO_CHUNKING_STRATEGY

How the audio is cut into chunks (auto or vad), in place of the audioChunkingStrategy option.

String

CamelOpenAIAudioKnownSpeakerNames (common)

Constant: AUDIO_KNOWN_SPEAKER_NAMES

Comma-separated names of up to 4 known speakers for diarized transcription, in place of the audioKnownSpeakerNames option.

String

CamelOpenAIAudioKnownSpeakerReferences (common)

Constant: AUDIO_KNOWN_SPEAKER_REFERENCES

Comma-separated audio samples of the known speakers for diarized transcription, in place of the audioKnownSpeakerReferences option.

String

CamelOpenAIAudioKeywords (common)

Constant: AUDIO_KEYWORDS

Comma-separated words or phrases that guide the transcription, in place of the audioKeywords option.

String

CamelOpenAIAudioLanguages (common)

Constant: AUDIO_LANGUAGES

Comma-separated possible languages of the input audio in ISO-639-1 format, in place of the audioLanguages option.

String

CamelOpenAIAudioInclude (common)

Constant: AUDIO_INCLUDE

Comma-separated additional information to ask for, such as logprobs, in place of the audioInclude option.

String

CamelOpenAIAudioDuration (common)

Constant: AUDIO_DURATION

The duration of the audio in seconds, for the verbose_json and diarized_json formats.

Double

CamelOpenAIAudioDiarizedSegments (common)

Constant: AUDIO_DIARIZED_SEGMENTS

Speaker-labelled segments from diarized_json transcription.

List

CamelOpenAIAudioDetectedLanguage (common)

Constant: AUDIO_DETECTED_LANGUAGE

The language of the audio, for the verbose_json format.

String

CamelOpenAISpeechModel (common)

Constant: SPEECH_MODEL

The model of audio-speech, in place of the speechModel option.

String

CamelOpenAISpeechVoice (common)

Constant: SPEECH_VOICE

The voice of the generated audio, in place of the speechVoice option.

String

CamelOpenAISpeechResponseFormat (common)

Constant: SPEECH_RESPONSE_FORMAT

The audio format of the generated speech (mp3, opus, aac, flac, wav or pcm), in place of the speechResponseFormat option.

String

CamelOpenAISpeechSpeed (common)

Constant: SPEECH_SPEED

The speed of the generated audio, from 0.25 to 4.0, in place of the speechSpeed option.

Double

CamelOpenAISpeechInstructions (common)

Constant: SPEECH_INSTRUCTIONS

Instructions to control the voice of the generated audio (not supported by tts-1 and tts-1-hd), in place of the speechInstructions option.

String

CamelOpenAIImageModel (common)

Constant: IMAGE_MODEL

The model of image-generation and image-edit, such as gpt-image-1, in place of the imageModel option.

String

CamelOpenAIImagePrompt (common)

Constant: IMAGE_PROMPT

The prompt describing the image to generate, or the edit to apply, in place of the imagePrompt option and, for image-generation, of the message body.

String

CamelOpenAIImageSize (common)

Constant: IMAGE_SIZE

The size of the generated image (e.g. 1024x1024, 1536x1024 or auto), in place of the imageSize option.

String

CamelOpenAIImageQuality (common)

Constant: IMAGE_QUALITY

The quality of the generated image (auto, high, medium or low for the GPT image models), in place of the imageQuality option.

String

CamelOpenAIImageResponseFormat (common)

Constant: IMAGE_RESPONSE_FORMAT

The response format of the generated image (url or b64_json), in place of the imageResponseFormat option. Rejected by the GPT image models, which always return base64.

String

CamelOpenAIImageCount (common)

Constant: IMAGE_COUNT

The number of images to generate, between 1 and 10, in place of the imageCount option.

Integer

CamelOpenAIImageBackground (common)

Constant: IMAGE_BACKGROUND

The background of the generated image (transparent, opaque or auto), in place of the imageBackground option. Only supported by the GPT image models.

String

CamelOpenAIImageOutputFormat (common)

Constant: IMAGE_OUTPUT_FORMAT

The output format of the generated image (png, jpeg or webp), in place of the imageOutputFormat option. Only supported by the GPT image models.

String

CamelOpenAIImageOutputCompression (common)

Constant: IMAGE_OUTPUT_COMPRESSION

The compression level from 0 to 100 for the webp and jpeg output formats, in place of the imageOutputCompression option. Only supported by the GPT image models.

Integer

CamelOpenAIImageStyle (common)

Constant: IMAGE_STYLE

The style of the generated image (vivid or natural), in place of the imageStyle option. A dall-e-3 option.

String

CamelOpenAIImageModeration (common)

Constant: IMAGE_MODERATION

The content moderation level of image generation (low or auto), in place of the imageModeration option. Only supported by the GPT image models.

String

CamelOpenAIImageInputFidelity (common)

Constant: IMAGE_INPUT_FIDELITY

How closely the edit must match the style and features of the input image (high or low), in place of the imageInputFidelity option. Only supported by image-edit on gpt-image-1 and gpt-image-1.5.

String

CamelOpenAIImageMask (common)

Constant: IMAGE_MASK

An optional PNG mask for the image-edit operation, where the fully transparent areas indicate where the image should be edited.

InputStream

CamelOpenAIImageResultCount (common)

Constant: IMAGE_RESULT_COUNT

The number of images returned in the response.

Integer

CamelOpenAIImageRevisedPrompt (common)

Constant: IMAGE_REVISED_PROMPT

The prompt as revised by the model, when a single image is returned (dall-e-3).

String

CamelOpenAIImageRevisedPrompts (common)

Constant: IMAGE_REVISED_PROMPTS

The prompts as revised by the model, one entry per returned image (dall-e-3).

List

CamelOpenAIImageInputTokens (common)

Constant: IMAGE_INPUT_TOKENS

The number of input tokens billed for the image request. Only reported by GPT image models.

Long

CamelOpenAIImageOutputTokens (common)

Constant: IMAGE_OUTPUT_TOKENS

The number of output tokens billed for the image request. Only reported by GPT image models.

Long

CamelOpenAIImageTotalTokens (common)

Constant: IMAGE_TOTAL_TOKENS

The total number of tokens billed for the image request. Only reported by GPT image models.

Long

Message Body

The message body at each side of the OpenAI component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

pojo (com.openai.models.webhooks.UnwrapWebhookEvent)

The event of the webhook operation, verified with webhookSecret, such as a batch or a background response that completed. The event type and the id of the object it is about are in headers.

Consumer reply

any

The body at the end of the route is not sent: OpenAI gets 200 without a body, or 500 when the route fails, and then sends the event again.

Producer input

any

The prompt of chat-completion and responses: text, or a file, bytes or a stream with an image or a PDF (chat-completion also audio), which userMessage then describes. Another body is sent as its toString(), and userMessage or the CamelOpenAIUserMessage header replaces a text body. embeddings and moderation take text or a List of texts (moderation also an image), audio-speech the text to speak, and image-generation the prompt unless imagePrompt is set. batch takes the requests as a Map keyed by custom_id, a List, or JSONL; audio takes the audio and image-edit the image, or a List of images. The operations that read a stored response, a batch or the tool calls of the last answer do not use the body.

  • With operation=decisions: pojo (com.openai.models.decisions.DecisionCreateParams)

  • With operation=batch: map, list, text, bytes, stream or file

  • With operation=audio-transcription: file, bytes or stream

  • With operation=audio-translation: file, bytes or stream

  • With operation=image-edit: file, bytes, stream or list

Producer output

text

The answer of chat-completion as text, also with outputClass or jsonSchema, where it is JSON text: unmarshal it to read its fields. With streaming, an Iterator of the chunks (text when tools run in a loop). With autoToolExecution=false, the tool calls the model asks for: an Optional of the List of tool calls, or a List of the function calls for responses. embeddings gives a vector (a List of Float), or a List of vectors for a List of texts; image-generation and image-edit the image as bytes or its URL as text, a List for several; batch-results an Iterator of the result lines as Maps. batch and moderation keep the body and set headers, and tool-execution clears it when it runs tool calls.

  • With streaming=true: iterator

  • With autoToolExecution=false: text, pojo or list

  • With operation=decisions: pojo (com.openai.models.decisions.Decision)

  • With operation=responses: text

  • With operation=responses-retrieve: text

  • With operation=responses-cancel: text

  • With operation=batch: unchanged

  • With operation=batch-retrieve: unchanged

  • With operation=batch-cancel: unchanged

  • With operation=batch-results: iterator

  • With operation=embeddings: list

  • With operation=tool-execution: null or unchanged

  • With operation=audio-transcription: text

  • With operation=audio-translation: text

  • With operation=audio-speech: bytes (byte[])

  • With operation=moderation: unchanged

  • With operation=image-generation: bytes, text or list

  • With operation=image-edit: bytes, text or list

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

Authentication

Set baseUrl to your providers endpoint (default: https://api.openai.com/v1).

API key resolution order (when no oauthProfile is set):

  • Endpoint apiKey

  • Component apiKey

  • Environment variable OPENAI_API_KEY

  • System property openai.api.key

When oauthProfile is set, it takes precedence over all of the above and the API key is not used.

The API key can be omitted for an OpenAI-compatible server that checks no key, such as a local Ollama, vLLM or LM Studio: when none of the above is set (and no oauthProfile), the requests are sent without an Authorization header. A server that needs a key then answers with HTTP 401 (UnauthorizedException).

OAuth Authentication

When using an identity provider (e.g., Azure AD for Azure OpenAI), set the oauthProfile parameter to acquire an access token via the OAuth 2.0 Client Credentials grant. The token is used in place of the API key. This requires camel-oauth on the classpath.

camel.oauth.azure.client-id=my-client
camel.oauth.azure.client-secret=my-secret
camel.oauth.azure.token-endpoint=https://login.microsoftonline.com/tenant/oauth2/v2.0/token
camel.oauth.azure.scope=https://cognitiveservices.azure.com/.default
  • Java

  • XML

  • YAML

from("direct:chat")
    .to("openai:chat-completion?model=gpt-4&oauthProfile=azure");
<route>
  <from uri="direct:chat"/>
  <to uri="openai:chat-completion?model=gpt-4&amp;oauthProfile=azure"/>
</route>
- route:
    from:
      uri: direct:chat
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              model: gpt-4
              oauthProfile: azure

MCP servers can also use OAuth independently via per-server oauthProfile:

  • Java

  • XML

  • YAML

from("direct:chat")
    .to("openai:chat-completion?model=gpt-4"
        + "&oauthProfile=azure"
        + "&mcpServer.tools.transportType=streamableHttp"
        + "&mcpServer.tools.url=https://mcp.internal/mcp"
        + "&mcpServer.tools.oauthProfile=keycloak");
<route>
    <from uri="direct:chat"/>
    <to uri="openai:chat-completion?model=gpt-4&amp;oauthProfile=azure&amp;mcpServer.tools.transportType=streamableHttp&amp;mcpServer.tools.url=https://mcp.internal/mcp&amp;mcpServer.tools.oauthProfile=keycloak"/>
</route>
- route:
    from:
      uri: direct:chat
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              model: gpt-4
              oauthProfile: azure
              mcpServer.tools.transportType: streamableHttp
              mcpServer.tools.url: https://mcp.internal/mcp
              mcpServer.tools.oauthProfile: keycloak
For component selection, structured extraction, streaming, and prompt management patterns, see the LLM Integration Guide.

Basic Chat Completion with String Input

  • Java

  • XML

  • YAML

from("direct:chat")
    .setBody(constant("What is Apache Camel?"))
    .to("openai:chat-completion")
    .log("Response: ${body}");
<route>
  <from uri="direct:chat"/>
  <setBody>
    <constant>What is Apache Camel?</constant>
  </setBody>
  <to uri="openai:chat-completion"/>
  <log message="Response: ${body}"/>
</route>
- route:
    from:
      uri: direct:chat
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              userMessage: What is Apache Camel?
        - log:
            message: "Response: ${body}"

Dynamic prompts per exchange

The user prompt can change on every exchange. Set the body to the prompt text, or override with the CamelOpenAIUserMessage header (Simple expressions work):

  • Java

  • YAML

from("direct:score")
    .setHeader("CamelOpenAIUserMessage", simple("Rate 1-10 for ${header.role}: ${body}"))
    .to("openai:chat-completion?model=gpt-4o-mini&temperature=0.2")
    .log("${body}");
- route:
    from:
      uri: direct:score
      steps:
        - setHeader:
            name: CamelOpenAIUserMessage
            expression:
              simple:
                expression: "Rate 1-10 for ${header.role}: ${body}"
        - to:
            uri: openai:chat-completion
            parameters:
              model: gpt-4o-mini
              temperature: 0.2

Chat generation parameters

Control randomness for chat completions with temperature (0.0–2.0) and topP (0.0–1.0). Low temperature (for example 0.1) is recommended for structured JSON extraction.

  • YAML

  • Java

steps:
  - to:
      uri: openai:chat-completion
      parameters:
        model: gpt-4o-mini
        temperature: 0.1
        topP: 1.0
.to("openai:chat-completion?model=gpt-4o-mini&temperature=0.1")

Per-exchange overrides use headers: CamelOpenAITemperature, CamelOpenAITopP.

For provider-specific request fields not exposed as URI options, use additionalBodyProperty (see OpenAI-Compatible Providers).

File-Backed Prompt with Text File

  • Java

  • XML

  • YAML

from("file:prompts?noop=true")
    .to("openai:chat-completion")
    .log("Response: ${body}");
<route>
  <from uri="file:prompts?noop=true"/>
  <to uri="openai:chat-completion"/>
  <log message="Response: ${body}"/>
</route>
- route:
    from:
      uri: file:prompts?noop=true
      steps:
        - to:
            uri: openai:chat-completion
        - log:
            message: "Response: ${body}"

Image File Input with Vision Model

  • Java

  • XML

  • YAML

from("file:images?noop=true")
    .to("openai:chat-completion?model=gpt-4.1-mini&userMessage=Describe what you see in this image")
    .log("Response: ${body}");
<route>
  <from uri="file:images?noop=true"/>
  <to uri="openai:chat-completion?model=gpt-4.1-mini&amp;userMessage=Describe what you see in this image"/>
  <log message="Response: ${body}"/>
</route>
- route:
    from:
      uri: file:images?noop=true
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              model: gpt-4.1-mini
              userMessage: Describe what you see in this image
        - log:
            message: "Response: ${body}"

Image input also works with bodies produced by remote file and cloud storage components, such as FTP/SFTP (WrappedFile), AWS S3, Azure Blob Storage or MinIO (byte[] or InputStream). The MIME type is detected from the component’s content-type header or the file name:

  • Java

  • XML

  • YAML

from("aws2-s3:my-bucket")
    .to("openai:chat-completion?model=gpt-4.1-mini&userMessage=Describe what you see in this image")
    .log("Response: ${body}");
<route>
  <from uri="aws2-s3:my-bucket"/>
  <to uri="openai:chat-completion?model=gpt-4.1-mini&amp;userMessage=Describe what you see in this image"/>
  <log message="Response: ${body}"/>
</route>
- route:
    from:
      uri: aws2-s3:my-bucket
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              model: gpt-4.1-mini
              userMessage: Describe what you see in this image
        - log:
            message: "Response: ${body}"

When no content-type header is available, set the CamelOpenAIMediaType header explicitly:

  • Java

  • XML

  • YAML

from("direct:image")
    .setHeader("CamelOpenAIMediaType", constant("image/png"))
    .setHeader("CamelOpenAIUserMessage", constant("Describe what you see in this image"))
    .to("openai:chat-completion?model=gpt-4.1-mini")
    .log("Response: ${body}");
<route>
  <from uri="direct:image"/>
  <setHeader name="CamelOpenAIMediaType">
    <constant>image/png</constant>
  </setHeader>
  <setHeader name="CamelOpenAIUserMessage">
    <constant>Describe what you see in this image</constant>
  </setHeader>
  <to uri="openai:chat-completion?model=gpt-4.1-mini"/>
  <log message="Response: ${body}"/>
</route>
- route:
    from:
      uri: direct:image
      steps:
        - setHeader:
            name: CamelOpenAIMediaType
            expression:
              constant:
                expression: "image/png"
        - setHeader:
            name: CamelOpenAIUserMessage
            expression:
              constant:
                expression: "Describe what you see in this image"
        - to:
            uri: openai:chat-completion
            parameters:
              model: gpt-4.1-mini
        - log:
            message: "Response: ${body}"

When using image input, the userMessage is required. Supported image formats are detected by MIME type (e.g., image/png, image/jpeg, image/gif, image/webp).

PDF and Audio File Input with Chat Completion

The chat-completion operation also accepts PDF documents and short audio clips (WAV or MP3) as the message body. Set userMessage to the prompt that accompanies the file, and provide a MIME type through CamelOpenAIMediaType, Content-Type, or a file name extension when needed:

from("direct:pdf-summary")
    .setHeader("CamelOpenAIMediaType", constant("application/pdf"))
    .setHeader("CamelOpenAIUserMessage", constant("Summarize this document"))
    .to("openai:chat-completion?model=gpt-4o")
    .log("Response: ${body}");

For audio input, supported MIME types are audio/wav and audio/mpeg (MP3).

Diarized Audio Transcription

Speaker-labelled transcription is available through the audio-transcription operation with audioResponseFormat=diarized_json and diarization models such as gpt-4o-transcribe-diarize. Optional tuning parameters include audioChunkingStrategy, audioKnownSpeakerNames, audioKnownSpeakerReferences, audioKeywords, audioLanguages and audioInclude.

from("file:recordings?noop=true")
    .to("openai:audio-transcription?audioModel=gpt-4o-transcribe-diarize&audioResponseFormat=diarized_json")
    .log("Transcript: ${body}");

Streaming Response

When streaming=true, the component returns an Iterator<ChatCompletionChunk> in the message body. You can consume this iterator using Camel’s streaming EIPs or process it directly.

For Server-Sent Events to web clients (platform-http), structured extraction pipelines, and when to stream through Camel vs. a dedicated handler, see LLM Integration Guide — Streaming responses.

Usage example:
- route:
    id: route-1145
    from:
      id: from-1972
      uri: timer
      parameters:
        repeatCount: 1
        timerName: timer
      steps:
        - to:
            id: to-1301
            uri: openai:chat-completion
            parameters:
              userMessage: In one sentence, what is Apache Camel?
              streaming: true
        - split:
            id: split-3196
            steps:
              - marshal:
                  id: marshal-3773
                  json:
                    library: Jackson
              - log:
                  id: log-6722
                  message: ${body}
            expression:
              simple:
                expression: ${body}
            streaming: true

Structured Output with outputClass

For extraction tasks (resumes, invoices, classification), prefer jsonSchema or outputClass instead of hand-written JSON parsing. Use low temperature (0.0–0.2). See LLM Integration Guide — Structured output.
Java-only: uses Java class definition for outputClass schema
public class Person {
    public String name;
    public int age;
    public String occupation;
}

from("direct:structured")
    .setBody(constant("Generate a person profile for a software engineer"))
    .to("openai:chat-completion?baseUrl=https://api.openai.com/v1&outputClass=com.example.Person")
    .log("Structured response: ${body}");

Structured Output with JSON Schema

The jsonSchema option instructs the model to return JSON that conforms to the provided schema. The response will be valid JSON but is not automatically validated against the schema (see jsonSchemaStrict below to have the model follow it exactly):

  • Java

  • XML

  • YAML

from("direct:json-schema")
    .setBody(constant("Create a product description"))
    .setHeader("CamelOpenAIJsonSchema", constant("{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"price\":{\"type\":\"number\"}}}"))
    .to("openai:chat-completion")
    .log("JSON response: ${body}");
<route>
  <from uri="direct:json-schema"/>
  <setBody>
    <constant>Create a product description</constant>
  </setBody>
  <setHeader name="CamelOpenAIJsonSchema">
    <constant>{"type":"object","properties":{"name":{"type":"string"},"price":{"type":"number"}}}</constant>
  </setHeader>
  <to uri="openai:chat-completion"/>
  <log message="JSON response: ${body}"/>
</route>
- route:
    from:
      uri: direct:json-schema
      steps:
        - setBody:
            expression:
              constant:
                expression: "Create a product description"
        - setHeader:
            name: CamelOpenAIJsonSchema
            expression:
              constant:
                expression: '{"type":"object","properties":{"name":{"type":"string"},"price":{"type":"number"}}}'
        - to:
            uri: openai:chat-completion
        - log:
            message: "JSON response: ${body}"

You can also load the schema from a resource file:

  • Java

  • XML

  • YAML

from("direct:json-schema-resource")
    .setBody(constant("Create a product description"))
    .to("openai:chat-completion?jsonSchema=resource:classpath:schemas/product.schema.json")
    .log("JSON response: ${body}");
<route>
  <from uri="direct:json-schema-resource"/>
  <setBody>
    <constant>Create a product description</constant>
  </setBody>
  <to uri="openai:chat-completion?jsonSchema=resource:classpath:schemas/product.schema.json"/>
  <log message="JSON response: ${body}"/>
</route>
- route:
    from:
      uri: direct:json-schema-resource
      steps:
        - setBody:
            expression:
              constant:
                expression: "Create a product description"
        - to:
            uri: openai:chat-completion
            parameters:
              jsonSchema: "resource:classpath:schemas/product.schema.json"
        - log:
            message: "JSON response: ${body}"

For full schema validation, integrate with the camel-json-validator component after receiving the response.

Conversation Memory (Per Exchange)

Usage example:
  • Java

  • XML

  • YAML

from("direct:conversation")
    .setBody(constant("My name is Alice"))
    .to("openai:chat-completion?conversationMemory=true")
    .log("First response: ${body}")
    .setBody(constant("What is my name?"))
    .to("openai:chat-completion?conversationMemory=true")
    .log("Second response: ${body}"); // Will remember "Alice"
<route>
  <from uri="direct:conversation"/>
  <setBody>
    <constant>My name is Alice</constant>
  </setBody>
  <to uri="openai:chat-completion?conversationMemory=true"/>
  <log message="First response: ${body}"/>
  <setBody>
    <constant>What is my name?</constant>
  </setBody>
  <to uri="openai:chat-completion?conversationMemory=true"/>
  <log message="Second response: ${body}"/>
</route>
- route:
    from:
      uri: direct:conversation
      steps:
        - setBody:
            expression:
              constant:
                expression: "My name is Alice"
        - to:
            uri: openai:chat-completion
            parameters:
              conversationMemory: true
        - log:
            message: "First response: ${body}"
        - setBody:
            expression:
              constant:
                expression: "What is my name?"
        - to:
            uri: openai:chat-completion
            parameters:
              conversationMemory: true
        - log:
            message: "Second response: ${body}"

Input Handling

The component accepts the following types of input in the message body:

  1. String: The prompt text is taken directly from the body

  2. File, Path or WrappedFile (the body type produced by the file, FTP, SFTP and SMB components): Used for file-based prompts. The component handles two types of files:

    • Text files (MIME type starting with text/, plus application/xml and application/json): The file content is read and used as the prompt. If userMessage endpoint option or CamelOpenAIUserMessage is set, it overrides the file content

    • Image files (MIME type starting with image/): The file is encoded as a base64 data URL and sent to vision-capable models. The userMessage is required when using image files

  3. byte[] or InputStream (the body types produced by cloud storage components such as AWS S3, Azure Blob Storage, Google Cloud Storage and MinIO): When the detected MIME type is an image, the content is encoded as a base64 data URL and sent to vision-capable models (userMessage is required). Otherwise, the content is converted to a String and used as the prompt

MIME Type Detection

For File, Path and locally backed WrappedFile bodies, the MIME type is resolved in the following order:

  1. The CamelOpenAIMediaType header

  2. The CamelFileContentType header

  3. The file name extension, using the Camel built-in MIME type table (e.g., .png, .jpg, .gif, .webp, .txt, .csv, .md, .xml, .json)

For byte[], InputStream and remote WrappedFile bodies, the MIME type is resolved in the following order:

  1. The CamelOpenAIMediaType header

  2. Cloud storage content-type headers: CamelAwsS3ContentType, CamelAzureStorageBlobContentType, CamelAzureStorageDataLakeContentType, CamelGoogleCloudStorageContentType, CamelMinioContentType, CamelIBMCOSContentType

  3. The Content-Type header

  4. The CamelFileContentType header

  5. The extension of the file name in the CamelFileName header

Set the CamelOpenAIMediaType header to override the MIME type detection, for example when the payload has no content-type metadata or the detection picks the wrong type.

Output Handling

Default Mode

The full model response is returned as a String in the message body.

Streaming Mode

When streaming=true, the message body contains an Iterator<ChatCompletionChunk> suitable for Camel streaming EIPs (such as split() with streaming()).

IMPORTANT:

  • Conversation memory is not automatically updated for streaming responses (only for non-streaming responses)

Structured Outputs

Using outputClass

The model is instructed to return JSON matching the specified class, but the response body remains a String.

Using jsonSchema

The jsonSchema option instructs the model to return JSON conforming to the provided schema. The response will be valid JSON but is not automatically validated against the schema. For full schema validation, integrate with the camel-json-validator component after receiving the response.

The JSON schema must be a valid JSON object. Invalid schema strings will result in an IllegalArgumentException.

Strict schema (jsonSchemaStrict)

Without more, OpenAI takes the schema as a hint: the answer is JSON, but it can miss required fields or have others. With jsonSchemaStrict=true, the JSON schema response format of chat-completion, responses and batch has strict: true (strict structured outputs), and the model follows the schema exactly. OpenAI then only accepts a schema that meets its rules, and answers any other with HTTP 400 (BadRequestException):

  • every property of each object is listed in required (an optional field is a required one whose type allows null, such as "type": ["string", "null"])

  • every object has "additionalProperties": false

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "price": { "type": ["number", "null"] }
  },
  "required": ["name", "price"],
  "additionalProperties": false
}

The option is off by default, and then strict is not sent. The CamelOpenAIJsonSchemaStrict header sets it per message, as CamelOpenAIJsonSchema does for the schema. Other OpenAI-compatible servers may ignore it. With outputClass, the openai-java SDK builds a strict schema from the class itself.

Conversation Memory

When conversationMemory=true, the component maintains conversation history in the CamelOpenAIConversationHistory exchange property (configurable via conversationHistoryProperty option). This history is scoped to a single Exchange and allows multi-turn conversations within a route.

Use maxHistoryMessages and maxHistoryTokens to bound how much history is retained in that property. Oldest conversation segments are dropped first; assistant tool-call blocks are always removed together with their tool results. The most recent segment is always kept, even when it alone exceeds maxHistoryMessages or maxHistoryTokens. Token limits use a character-count / 4 estimate (including image payload size for multi-modal user messages).

IMPORTANT:

  • Conversation history is automatically updated with each assistant response for non-streaming responses only

  • The history is stored as a List<ChatCompletionMessageParam> in the Exchange property

  • The history persists across multiple calls to the endpoint within the same Exchange

  • You can manually set the CamelOpenAIConversationHistory exchange property to provide custom conversation context

Example of manual conversation history:

Java-only: uses OpenAI SDK ChatCompletionMessageParam types
List<ChatCompletionMessageParam> history = new ArrayList<>();
history.add(ChatCompletionMessageParam.ofUser(/* ... */));
history.add(ChatCompletionMessageParam.ofAssistant(/* ... */));

from("direct:with-history")
    .setBody(constant("Continue the conversation"))
    .setProperty("CamelOpenAIConversationHistory", constant(history))
    .to("openai:chat-completion?conversationMemory=true")
    .log("${body}");

SSL Configuration

The component supports custom SSL/TLS configuration for connecting to OpenAI or OpenAI-compatible endpoints that use self-signed certificates, private CAs, or require mutual TLS (mTLS) authentication.

When no SSL parameters are set, the default JVM trust store is used.

Using SSLContextParameters

The component implements SSLContextParametersAware and supports Camel’s standard SSLContextParameters for SSL configuration. When set, SSLContextParameters takes precedence over the individual ssl* properties (same pattern as camel-kafka).

Java-only: programmatic SSLContextParameters configuration
KeyStoreParameters trustStoreParams = new KeyStoreParameters();
trustStoreParams.setResource("/path/to/truststore.jks");
trustStoreParams.setPassword("changeit");

TrustManagersParameters trustManagers = new TrustManagersParameters();
trustManagers.setKeyStore(trustStoreParams);

SSLContextParameters sslContextParameters = new SSLContextParameters();
sslContextParameters.setTrustManagers(trustManagers);

from("direct:chat")
    .to("openai:chat-completion?model=gpt-4"
        + "&baseUrl=https://my-llm-server:8443/v1"
        + "&sslContextParameters=#sslContextParameters");

To use global SSL context parameters for all OpenAI endpoints:

Java-only: programmatic component configuration
OpenAIComponent openai = context.getComponent("openai", OpenAIComponent.class);
openai.setUseGlobalSslContextParameters(true);

Custom Trust Store

To trust a server using a self-signed or private CA certificate:

  • Java

  • YAML

from("direct:chat")
    .to("openai:chat-completion?model=gpt-4"
        + "&baseUrl=https://my-llm-server:8443/v1"
        + "&sslTruststoreLocation=/path/to/truststore.jks"
        + "&sslTruststorePassword=changeit");
- route:
    from:
      uri: direct:chat
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              model: gpt-4
              baseUrl: https://my-llm-server:8443/v1
              sslTruststoreLocation: /path/to/truststore.jks
              sslTruststorePassword: changeit

Mutual TLS (mTLS)

For two-way authentication, configure both trust store and key store:

  • Java

  • XML

  • YAML

from("direct:chat")
    .to("openai:chat-completion?model=gpt-4"
        + "&baseUrl=https://my-llm-server:8443/v1"
        + "&sslTruststoreLocation=/path/to/truststore.jks"
        + "&sslTruststorePassword=changeit"
        + "&sslKeystoreLocation=/path/to/keystore.jks"
        + "&sslKeystorePassword=changeit"
        + "&sslKeyPassword=keypass");
<route>
  <from uri="direct:chat"/>
  <to uri="openai:chat-completion?model=gpt-4&amp;baseUrl=https://my-llm-server:8443/v1&amp;sslTruststoreLocation=/path/to/truststore.jks&amp;sslTruststorePassword=changeit&amp;sslKeystoreLocation=/path/to/keystore.jks&amp;sslKeystorePassword=changeit&amp;sslKeyPassword=keypass"/>
</route>
- route:
    from:
      uri: direct:chat
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              model: gpt-4
              baseUrl: https://my-llm-server:8443/v1
              sslTruststoreLocation: /path/to/truststore.jks
              sslTruststorePassword: changeit
              sslKeystoreLocation: /path/to/keystore.jks
              sslKeystorePassword: changeit
              sslKeyPassword: keypass

Disabling Hostname Verification

In development or test environments, hostname verification can be disabled by setting sslEndpointAlgorithm to an empty string or none:

  • Java

  • XML

  • YAML

from("direct:chat")
    .to("openai:chat-completion?model=gpt-4"
        + "&baseUrl=https://localhost:8443/v1"
        + "&sslTruststoreLocation=/path/to/truststore.jks"
        + "&sslTruststorePassword=changeit"
        + "&sslEndpointAlgorithm=none");
<route>
  <from uri="direct:chat"/>
  <to uri="openai:chat-completion?model=gpt-4&amp;baseUrl=https://localhost:8443/v1&amp;sslTruststoreLocation=/path/to/truststore.jks&amp;sslTruststorePassword=changeit&amp;sslEndpointAlgorithm=none"/>
</route>
- route:
    from:
      uri: direct:chat
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              model: gpt-4
              baseUrl: https://localhost:8443/v1
              sslTruststoreLocation: /path/to/truststore.jks
              sslTruststorePassword: changeit
              sslEndpointAlgorithm: none
Disabling hostname verification is insecure and should only be used in non-production environments.

SSL Parameters

Parameter Type Default Description

sslContextParameters

SSLContextParameters

Camel SSL context parameters. When set, takes precedence over the individual ssl* options below

sslTruststoreLocation

String

Location of the trust store file

sslTruststorePassword

String

Trust store password

sslTruststoreType

String

JKS

Trust store format (e.g., JKS, PKCS12)

sslKeystoreLocation

String

Location of the key store file (for mTLS)

sslKeystorePassword

String

Key store password

sslKeystoreType

String

JKS

Key store format (e.g., JKS, PKCS12)

sslKeyPassword

String

Private key password in the key store

sslProtocol

String

TLSv1.3

SSL protocol for generating the SSLContext

sslKeymanagerAlgorithm

String

SunX509

Algorithm for the key manager factory

sslTrustmanagerAlgorithm

String

PKIX

Algorithm for the trust manager factory

sslEndpointAlgorithm

String

https

Hostname verification algorithm; set to empty or none to disable

Reasoning Models

Some OpenAI-compatible models (e.g., Qwen3, DeepSeek-R1) return chain-of-thought reasoning in a separate reasoning_content field alongside the regular content in the API response. The component automatically extracts this field and sets it as the CamelOpenAIReasoningContent message header.

This is independent from the inline <think>…​</think> tag stripping controlled by stripThinking. A response can populate both headers simultaneously:

  • CamelOpenAIReasoningContent — from the API-level reasoning_content field

  • CamelOpenAIThinkingContent — from inline <think> tags in the content field (requires stripThinking=true)

  • Java

  • XML

  • YAML

from("direct:chat")
    .to("openai:chat-completion?model=qwen3&stripThinking=true")
    .log("Answer: ${body}")
    .log("Reasoning: ${header.CamelOpenAIReasoningContent}")
    .log("Thinking: ${header.CamelOpenAIThinkingContent}");
<route>
  <from uri="direct:chat"/>
  <to uri="openai:chat-completion?model=qwen3&amp;stripThinking=true"/>
  <log message="Answer: ${body}"/>
  <log message="Reasoning: ${header.CamelOpenAIReasoningContent}"/>
  <log message="Thinking: ${header.CamelOpenAIThinkingContent}"/>
</route>
- route:
    from:
      uri: direct:chat
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              model: qwen3
              stripThinking: true
        - log:
            message: "Answer: ${body}"
        - log:
            message: "Reasoning: ${header.CamelOpenAIReasoningContent}"
        - log:
            message: "Thinking: ${header.CamelOpenAIThinkingContent}"
Reasoning content extraction is supported in non-streaming mode only (both simple and agentic/MCP tool loop paths). Streaming responses do not extract reasoning content.

Mapping Additional Response Fields to Headers

The additionalResponseHeader option allows mapping any extra field from the API response message into a named Camel header. This is useful for provider-specific fields that are not part of the standard OpenAI response schema.

The key is the field name in the API response, and the value is the Camel header name to set:

  • Java

  • XML

  • YAML

from("direct:chat")
    .to("openai:chat-completion?model=qwen3"
        + "&additionalResponseHeader.reasoning_content=MyReasoning"
        + "&additionalResponseHeader.custom_field=MyCustomField")
    .log("Custom reasoning: ${header.MyReasoning}");
<route>
  <from uri="direct:chat"/>
  <to uri="openai:chat-completion?model=qwen3&amp;additionalResponseHeader.reasoning_content=MyReasoning&amp;additionalResponseHeader.custom_field=MyCustomField"/>
  <log message="Custom reasoning: ${header.MyReasoning}"/>
</route>
- route:
    from:
      uri: direct:chat
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              model: qwen3
              additionalResponseHeader.reasoning_content: MyReasoning
              additionalResponseHeader.custom_field: MyCustomField
        - log:
            message: "Custom reasoning: ${header.MyReasoning}"

String-valued fields are set directly. Non-string fields (numbers, booleans, objects) are converted using toString().

This maps fields from the response message’s additional properties (fields not part of the standard schema). Standard response fields like content, role, and tool_calls are not accessible through this option.

Tips for Production Use

This section covers practical advice for production routes. For component selection, streaming to browsers, and prompt management at scale, see the LLM Integration Guide.

Timeouts

Four options bound the HTTP call to the API, all in milliseconds and all unset by default so the SDK defaults apply. Which phase times out tells you whether a retry is safe:

Option SDK default Bounds

connectTimeout

1 minute

Establishing the TCP connection. Hitting this means the request never reached the model, so retrying is safe

readTimeout

falls back to requestTimeout

Reading the response. Hitting this means the model may have processed the request already, so a retry can duplicate work and cost

writeTimeout

falls back to requestTimeout

Writing the request body, which is what bites on large audio and image uploads

requestTimeout

10 minutes

The request as a whole, and the fallback for the read and write phases

Setting only requestTimeout behaves exactly as it did before the per-phase options existed.

from("direct:ask")
    .to("openai:chat-completion?model=gpt-4o-mini"
        + "&connectTimeout=5000&readTimeout=120000&requestTimeout=180000");

A short connectTimeout with a long readTimeout is the usual shape for chat: fail fast when the endpoint is unreachable, but leave the model room to generate. Reasoning models need the read budget in particular, because a long thinking phase produces no bytes on the wire.

These timeouts bound a single HTTP request, not the exchange. The SDK retries internally, so one exchange can span several of them. See maxRetries.

Temperature and Model Parameters

The temperature endpoint option controls how deterministic the model’s output is. Lower values produce more consistent, predictable responses; higher values produce more varied, creative output.

For structured extraction tasks (JSON parsing, data extraction, classification), use a low temperature such as 0.1 to reduce the chance of the model adding unexpected commentary or formatting around the structured output:

  • Java

  • YAML

from("direct:extract-skills")
    .to("openai:chat-completion?temperature=0.1&outputClass=com.example.SkillList")
    .log("Extracted: ${body}");
- route:
    from:
      uri: direct:extract-skills
      steps:
        - to:
            uri: openai:chat-completion
            parameters:
              temperature: 0.1
              outputClass: com.example.SkillList
        - log:
            message: "Extracted: ${body}"

Temperature can also be set per-exchange via the CamelOpenAITemperature header. Other tuning options include topP (nucleus sampling) and maxTokens (response length limit).

Dynamic Prompts

The CamelOpenAIUserMessage header is evaluated per-exchange, so you can construct prompts dynamically using Camel’s Simple language or any other expression:

  • Java

  • YAML

from("direct:summarize")
    .setHeader("CamelOpenAIUserMessage",
        simple("Summarize this ${header.documentType} in 3 bullet points: ${body}"))
    .to("openai:chat-completion")
    .log("Summary: ${body}");
- route:
    from:
      uri: direct:summarize
      steps:
        - setHeader:
            name: CamelOpenAIUserMessage
            expression:
              simple:
                expression: "Summarize this ${header.documentType} in 3 bullet points: ${body}"
        - to:
            uri: openai:chat-completion
        - log:
            message: "Summary: ${body}"

This is useful when chaining multiple enrichment steps where each step needs a different instruction based on the current exchange state.

Use Structured Output for JSON Extraction

When you need the model to return structured data (JSON objects, arrays, typed fields), prefer the built-in outputClass or jsonSchema options over manually parsing the model’s text output. These options instruct the model to produce valid JSON matching your schema, which significantly reduces parsing failures:

// Recommended — structured output handles JSON formatting:
from("direct:extract")
    .to("openai:chat-completion?outputClass=com.example.Skills")
    .log("${body}");

// Avoid — manual JSON parsing is fragile:
from("direct:extract")
    .setHeader("CamelOpenAIUserMessage",
        constant("Extract skills as a JSON array. Respond with valid JSON only."))
    .to("openai:chat-completion")
    .process(exchange -> {
        // This breaks when the model adds commentary around the JSON
        String json = exchange.getIn().getBody(String.class);
        List<String> skills = objectMapper.readValue(json, new TypeReference<>() {});
        exchange.getIn().setBody(skills);
    });

See Structured Output with outputClass and Structured Output with JSON Schema above for full examples. For additional validation, pipe the response through the JSON Validator component.

Handling Model Output Errors

A successful HTTP 200 response from the model does not guarantee the content is usable. The model may ignore formatting instructions, return truncated output, or produce content that does not match your expected shape. These are not Camel exceptions — they appear as downstream parsing failures in your own processors.

For production routes, add a lightweight validation step after the model call:

from("direct:extract")
    .to("openai:chat-completion?outputClass=com.example.Result")
    .process(exchange -> {
        String response = exchange.getIn().getBody(String.class);
        if (response == null || response.isBlank()) {
            throw new IllegalStateException("Empty model response");
        }
    })
    .to("direct:downstream");

Using outputClass or jsonSchema already reduces this risk substantially by constraining the model’s output format at the API level.

Prompt Management

When your project grows beyond a few routes, keeping prompt strings inline in route definitions becomes hard to maintain. Consider these approaches:

Load prompts from resource files:

from("direct:analyze")
    .setHeader("CamelOpenAISystemMessage",
        constant("resource:classpath:prompts/system-analyst.txt"))
    .to("openai:chat-completion");

Use Camel property placeholders for reusable fragments:

# application.properties
prompt.system.analyst=You are a technical analyst. Be concise and factual.
prompt.output.json=Respond with valid JSON only, no commentary.
from("direct:analyze")
    .setHeader("CamelOpenAISystemMessage", constant("{{prompt.system.analyst}}"))
    .setHeader("CamelOpenAIUserMessage",
        simple("{{prompt.output.json}} Analyze: ${body}"))
    .to("openai:chat-completion");
For prompt templates with named variables (e.g., `{{dishType}}`), the LangChain4j Chat component offers built-in template support via the CHAT_SINGLE_MESSAGE_WITH_PROMPT operation.

Streaming Considerations

The streaming=true option returns an Iterator<ChatCompletionChunk> that can be consumed with Camel’s Split EIP (see Streaming Response above). This works well for pipeline-style processing where each chunk is handled as part of a longer integration flow.

For user-facing scenarios that require Server-Sent Events (SSE) or WebSocket delivery to a browser, see LLM Integration Guide — Streaming responses for platform-http patterns and when to stream through Camel vs. a dedicated handler.

When tools (MCP tools or route tools from tags) with autoToolExecution are active, streaming automatically falls back to non-streaming to allow the agentic tool-calling loop to function. See MCP Tool Calling for details.

Sub-Pages

For more details on specific features, see:

Error Handling

The component may throw the following exceptions:

  • IllegalArgumentException:

    • When an invalid operation is specified (supported: chat-completion, responses, responses-retrieve, responses-cancel, embeddings, tool-execution, audio-transcription, audio-translation, audio-speech, moderation, image-generation, image-edit)

    • When message body or user message is missing

    • When the audio model is missing (audio-transcription, audio-translation) or the speech model is missing (audio-speech)

    • When image file is provided without userMessage (chat-completion)

    • When unsupported file type is provided (only text and image files are supported)

    • When invalid JSON schema string is provided

    • When the moderation input list is empty, contains null elements, or contains an image file (moderation)

    • When the image model is missing (image-generation, image-edit)

    • When the prompt is missing (image-generation, image-edit) or the image list is empty (image-edit)

    • When an unsupported image or mask body type is provided (image-edit)

  • CamelExchangeException:

    • When moderation returns a number of results that does not match the number of inputs (moderation)

    • When the image response contains no images, or an image with neither b64_json nor url (image-generation, image-edit)

  • API-specific exceptions from the OpenAI SDK for network errors, authentication failures, rate limiting, etc. These are propagated unchanged, so routes can match them by type. See Targeting SDK Exceptions with onException.

Targeting SDK Exceptions with onException

The producer does not wrap or reclassify what the OpenAI SDK throws. The SDK exception reaches the exchange as-is, so onException can match the concrete type and treat a transient failure differently from a terminal one.

Every HTTP error response maps to a subclass of com.openai.errors.OpenAIServiceException:

Exception Status Worth retrying

BadRequestException

400

No, the request is malformed

UnauthorizedException

401

No, fix the API key

PermissionDeniedException

403

No

NotFoundException

404

No, usually an unknown model or a wrong baseUrl

UnprocessableEntityException

422

No, typically a context-length or validation error

RateLimitException

429

Yes, with backoff

InternalServerException

5xx

Yes, with backoff

UnexpectedStatusCodeException

other

Depends on the provider

Three further exceptions carry no status code and extend com.openai.errors.OpenAIException directly: OpenAIIoException for connect and read failures, OpenAIRetryableException when the SDK gave up after exhausting its own retries, and OpenAIInvalidDataException when the response body cannot be parsed.

Retrying the transient cases while failing fast on the rest:

onException(RateLimitException.class, InternalServerException.class, OpenAIIoException.class)
    .maximumRedeliveries(3)
    .redeliveryDelay(2000)
    .backOffMultiplier(2)
    .useExponentialBackOff();

onException(BadRequestException.class, UnprocessableEntityException.class,
            UnauthorizedException.class)
    .maximumRedeliveries(0)
    .handled(true)
    .to("direct:rejected");

from("direct:ask")
    .to("openai:chat-completion?model=gpt-4o-mini");

OpenAIServiceException carries the details of the failed call, which is what you want for logging or for routing on the provider’s own error code:

onException(OpenAIServiceException.class)
    .handled(true)
    .process(exchange -> {
        OpenAIServiceException cause
                = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, OpenAIServiceException.class);
        exchange.getIn().setHeader("FailureStatus", cause.statusCode());
        exchange.getIn().setHeader("FailureCode", cause.code().orElse(null));
        exchange.getIn().setHeader("FailureType", cause.type().orElse(null));
    })
    .to("direct:failed-calls");

headers() on the same exception exposes the response headers, including Retry-After on a 429.

Structured error exchange properties

When an OpenAI producer call fails, Camel sets structured metadata on the exchange before the SDK exception propagates. This works even when GenAI observability is disabled.

Exchange property Meaning

CamelAiErrorCategory

Coarse category: RATE_LIMIT, SERVER_ERROR, VALIDATION, AUTH, or UNKNOWN

CamelAiRetryAfterMillis

Suggested retry delay in milliseconds when the OpenAI SDK exposes Retry-After or Retry-After-Ms on a 429; absent for other providers and error types

Use these when a route should branch on category without matching every SDK type, or when you want a single onException policy across OpenAI, LangChain4j, and Spring AI producers:

onException(Exception.class)
    .process(exchange -> {
        String category = exchange.getProperty("CamelAiErrorCategory", String.class);
        Long retryAfter = exchange.getProperty("CamelAiRetryAfterMillis", Long.class);
        if ("RATE_LIMIT".equals(category)) {
            long delay = retryAfter != null ? retryAfter : 2000L;
            exchange.getIn().setHeader("RetryDelay", delay);
        }
    })
    .maximumRedeliveries(3)
    .handled(true)
    .to("direct:rate-limited");

The SDK exception is still available as Exchange.EXCEPTION_CAUGHT, so you can combine coarse categories with the fine-grained types in Targeting SDK Exceptions with onException.

SDK Retry vs Camel Redelivery

The SDK client retries on its own before the exception ever reaches Camel. The maxRetries option controls this and defaults to 2, so one exchange already issues up to three HTTP requests. The SDK retries 408, 409, 429 and 5xx responses as well as connection failures, backing off exponentially and honoring the Retry-After and Retry-After-Ms response headers.

Camel redelivery multiplies with that layer rather than replacing it. With the default maxRetries=2 and maximumRedeliveries(3), a single message can produce twelve HTTP requests, which is rarely what you want against a rate-limited endpoint.

Pick one layer and keep the other out of the way:

  • Leave maxRetries at its default and do not add Camel redelivery for rate limits. The SDK backoff already reads Retry-After, and this is the simplest choice for a plain request/response route.

  • Set maxRetries=0 and drive retries from onException when the retry has to be visible to Camel, for example to reach a dead letter channel, apply a per-route policy, or show up in error handler metrics.

from("direct:ask")
    .to("openai:chat-completion?model=gpt-4o-mini&maxRetries=0");
requestTimeout bounds a single HTTP request, not the whole retry sequence. At the default maxRetries=2, worst-case wall time is roughly three times requestTimeout plus the backoff between attempts.

Errors in Streaming Mode

With streaming=true the producer issues the initial HTTP request and then hands Camel an Iterator<ChatCompletionChunk>. Failures on that first request (authentication, rate limiting, connection errors) are thrown by the producer and behave like any other producer exception.

A failure that occurs after the first chunk is different: it surfaces while the iterator is consumed, so it is reported against the step doing the consuming, usually a Split EIP, and not against the to("openai:…​") step. Route-scoped onException still applies, but an error handler attached to the producer step alone will not see it.