OpenAI SDK 채팅 설정

OpenAI SDK 채팅 설정 (공식)

Spring AI는 OpenAI의 공식 openai-java SDK를 통해 OpenAI 언어 모델을 지원해요. 이 방식은 공식적으로 유지보수되는 견고한 통합을 제공하며, Microsoft Foundry와 GitHub Models 서비스까지 포함해요. base URL을 보고 OpenAI인지 Microsoft Foundry인지 GitHub Models인지를 자동으로 감지해요.

출처: 공식문서

인증 (Authentication)

인증은 base URL과 API 키로 이루어져요. 이 구현은 Spring Boot 프로퍼티나 환경 변수를 통해 유연한 설정을 제공해요.

OpenAI 사용

 spring.ai.openai-sdk.api-key=<your-openai-api-key> # base-url is optional, defaults to https://api.openai.com/v1

또는 환경 변수로 설정해요.

 export OPENAI_API_KEY=<your-openai-api-key> # OPENAI_BASE_URL is optional, defaults to https://api.openai.com/v1

Microsoft Foundry 사용

Microsoft Foundry URL을 쓰면 자동으로 감지돼요. 프로퍼티로 설정할 수 있어요.

 spring.ai.openai-sdk.base-url=https://<your-deployment-url>.openai.azure.com spring.ai.openai-sdk.api-key=<your-api-key> spring.ai.openai-sdk.microsoft-deployment-name=<your-deployment-name>

또는 환경 변수로:

 export OPENAI_BASE_URL=https://<your-deployment-url>.openai.azure.com export OPENAI_API_KEY=<your-api-key>

Passwordless 인증 (Azure 권장): Microsoft Foundry는 API 키 없이 passwordless 인증을 지원하는데, Azure에서 실행할 때 더 안전해요. com.azure:azure-identity 의존성을 추가하면 돼요.

 <dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> </dependency>

그 다음 API 키 없이 설정해요.

 spring.ai.openai-sdk.base-url=https://<your-deployment-url>.openai.azure.com spring.ai.openai-sdk.microsoft-deployment-name=<your-deployment-name> # No api-key needed - will use Azure credentials from environment

GitHub Models 사용

GitHub Models는 GitHub Models base URL을 쓰면 자동으로 감지돼요. models:read 스코프의 GitHub Personal Access Token(PAT)이 필요해요.

 spring.ai.openai-sdk.base-url=https://models.inference.ai.azure.com spring.ai.openai-sdk.api-key=github_pat_XXXXXXXXXXX

또는 환경 변수로:

 export OPENAI_BASE_URL=https://models.inference.ai.azure.com export OPENAI_API_KEY=github_pat_XXXXXXXXXXX

API 키 같은 민감 정보를 다룰 때 보안을 높이려면 SpEL을 쓸 수 있어요.

 spring.ai.openai-sdk.api-key=${OPENAI_API_KEY}

저장소와 BOM 추가

Spring AI 아티팩트는 Maven Central과 Spring Snapshot 저장소에 게시돼요. 이 저장소를 추가하는 방법은 아티팩트 저장소 섹션을 참고하세요. 일관된 Spring AI 버전을 위해 BOM 제공도를 제공하는데, 추가 방법은 의존성 관리 섹션을 보면 돼요.

자동 설정 (Auto-Configuration)

Spring AI는 OpenAI SDK 채팅 클라이언트에 대한 Spring Boot 자동 설정을 제공해요. 활성화하려면 Maven pom.xml이나 Gradle build.gradle에 다음 의존성을 추가하면 돼요.

 <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-openai-sdk</artifactId> </dependency>
 dependencies { implementation 'org.springframework.ai:spring-ai-starter-model-openai-sdk' }

설정 프로퍼티 (Configuration Properties)

연결 프로퍼티 (Connection Properties)

OpenAI SDK 클라이언트를 설정하는 프리픽스는 spring.ai.openai-sdk 이에요.

Property Description Default
spring.ai.openai-sdk.base-url The URL to connect to. Auto-detects from OPENAI_BASE_URL environment variable if not set.
spring.ai.openai-sdk.api-key The API Key. Auto-detects from OPENAI_API_KEY environment variable if not set. -
spring.ai.openai-sdk.organization-id Optionally specify which organization to use for API requests. -
spring.ai.openai-sdk.timeout Request timeout duration. -
spring.ai.openai-sdk.max-retries Maximum number of retry attempts for failed requests. -
spring.ai.openai-sdk.proxy Proxy settings for OpenAI client (Java Proxy object). -
spring.ai.openai-sdk.custom-headers Custom HTTP headers to include in requests. Map of header name to header value. -

Microsoft Foundry (Azure OpenAI) 프로퍼티

OpenAI SDK 구현은 Microsoft Foundry(Azure OpenAI)를 네이티브로 지원해요.

Property Description Default
spring.ai.openai-sdk.microsoft-foundry Enable Microsoft Foundry mode. Auto-detected if base URL contains openai.azure.com, cognitiveservices.azure.com, or .openai.microsoftFoundry.com. false
spring.ai.openai-sdk.microsoft-deployment-name Microsoft Foundry deployment name. If not specified, the model name will be used. Also accessible via alias deployment-name. -
spring.ai.openai-sdk.microsoft-foundry-service-version Microsoft Foundry API service version. -
spring.ai.openai-sdk.credential Credential object for passwordless authentication (requires com.azure:azure-identity dependency). -

Microsoft Foundry는 passwordless 인증을 지원해요. com.azure:azure-identity 의존성을 추가하면 API 키가 없을 때 환경의 Azure 자격 증명을 자동으로 사용하려 해요.

GitHub Models 프로퍼티

GitHub Models에 대한 네이티브 지원이 있어요.

Property Description Default
spring.ai.openai-sdk.github-models Enable GitHub Models mode. Auto-detected if base URL contains models.github.ai or models.inference.ai.azure.com. false

GitHub Models는 models:read 스코프의 Personal Access Token이 필요해요. OPENAI_API_KEY 환경 변수나 spring.ai.openai-sdk.api-key 프로퍼티로 설정하면 돼요.

채팅 모델 프로퍼티 (Chat Model Properties)

채팅 모델 구현을 설정하는 프리픽스는 spring.ai.openai-sdk.chat 이에요.

Property Description Default
spring.ai.openai-sdk.chat.options.model Name of the OpenAI chat model to use. Models include gpt-5-mini, gpt-4o, gpt-4o-mini, gpt-4-turbo, o1, o3-mini, and more. gpt-5-mini
spring.ai.openai-sdk.chat.options.temperature The sampling temperature that controls the apparent creativity of generated completions. Higher values make output more random; lower values make results more focused and deterministic. It is not recommended to modify temperature and top_p for the same request. 1.0
spring.ai.openai-sdk.chat.options.frequency-penalty Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far. 0.0
spring.ai.openai-sdk.chat.options.logit-bias Modify the likelihood of specified tokens appearing in the completion. -
spring.ai.openai-sdk.chat.options.logprobs Whether to return log probabilities of the output tokens. false
spring.ai.openai-sdk.chat.options.top-logprobs An integer between 0 and 5 specifying the number of most likely tokens to return at each token position. Requires logprobs to be true. -
spring.ai.openai-sdk.chat.options.max-tokens The maximum number of tokens to generate. Use for non-reasoning models (e.g., gpt-4o, gpt-3.5-turbo). Cannot be used with reasoning models (e.g., o1, o3, o4-mini series). Mutually exclusive with maxCompletionTokens. -
spring.ai.openai-sdk.chat.options.max-completion-tokens An upper bound for the number of tokens generated for a completion, including visible and reasoning tokens. Required for reasoning models. Mutually exclusive with maxTokens. -
spring.ai.openai-sdk.chat.options.n How many chat completion choices to generate for each input message. 1
spring.ai.openai-sdk.chat.options.output-modalities List of output modalities. Can include "text" and "audio". -
spring.ai.openai-sdk.chat.options.output-audio Parameters for audio output. Use AudioParameters with voice (ALLOY, ASH, BALLAD, CORAL, ECHO, FABLE, ONYX, NOVA, SAGE, SHIMMER) and format (MP3, FLAC, OPUS, PCM16, WAV, AAC). -
spring.ai.openai-sdk.chat.options.presence-penalty Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far. 0.0
spring.ai.openai-sdk.chat.options.response-format.type Response format type: TEXT, JSON_OBJECT, or JSON_SCHEMA. TEXT
spring.ai.openai-sdk.chat.options.response-format.json-schema JSON schema for structured outputs when type is JSON_SCHEMA. -
spring.ai.openai-sdk.chat.options.seed If specified, the system will make a best effort to sample deterministically for reproducible results. -
spring.ai.openai-sdk.chat.options.stop Up to 4 sequences where the API will stop generating further tokens. -
spring.ai.openai-sdk.chat.options.top-p An alternative to sampling with temperature, called nucleus sampling. -
spring.ai.openai-sdk.chat.options.user A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. -
spring.ai.openai-sdk.chat.options.parallel-tool-calls Whether to enable parallel function calling during tool use. true
spring.ai.openai-sdk.chat.options.reasoning-effort Constrains effort on reasoning for reasoning models: low, medium, or high. -
spring.ai.openai-sdk.chat.options.verbosity Controls the verbosity of the model’s response. -
spring.ai.openai-sdk.chat.options.store Whether to store the output of this chat completion request for use in OpenAI’s model distillation or evals products. false
spring.ai.openai-sdk.chat.options.metadata Developer-defined tags and values used for filtering completions in the dashboard. -
spring.ai.openai-sdk.chat.options.service-tier Specifies the latency tier to use: auto, default, flex, or priority. -
spring.ai.openai-sdk.chat.options.stream-options.include-usage Whether to include usage statistics in streaming responses. false
spring.ai.openai-sdk.chat.options.stream-options.include-obfuscation Whether to include obfuscation in streaming responses. false

수동 설정 (Manual Configuration)

Spring Boot를 쓰지 않는다면 OpenAiSdkChatModel을 직접 구성해서 텍스트 생성에 쓸 수 있어요. spring-ai-openai-sdk 의존성을 Maven pom.xml에 추가하면 돼요.

 <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-openai-sdk</artifactId> </dependency>

또는 Gradle build.gradle:

 dependencies { implementation 'org.springframework.ai:spring-ai-openai-sdk' }

그 다음 OpenAiSdkChatModel을 만들어 텍스트 생성에 사용해요.

 var chatOptions = OpenAiSdkChatOptions.builder() .model("gpt-4o") .temperature(0.7) .apiKey(System.getenv("OPENAI_API_KEY")) .build(); var chatModel = OpenAiSdkChatModel.builder() .options(chatOptions) .build(); ChatResponse response = chatModel.call( new Prompt("Generate the names of 5 famous pirates.")); // Or with streaming responses Flux<ChatResponse> response = chatModel.stream( new Prompt("Generate the names of 5 famous pirates."));

Microsoft Foundry 구성

 var chatOptions = OpenAiSdkChatOptions.builder() .baseUrl("https://your-resource.openai.azure.com") .apiKey(System.getenv("OPENAI_API_KEY")) .deploymentName("gpt-4") .azureOpenAIServiceVersion(AzureOpenAIServiceVersion.V2024_10_01_PREVIEW) .azure(true) // Enables Microsoft Foundry mode .build(); var chatModel = OpenAiSdkChatModel.builder() .options(chatOptions) .build();

GitHub Models 구성

 var chatOptions = OpenAiSdkChatOptions.builder() .baseUrl("https://models.inference.ai.azure.com") .apiKey(System.getenv("GITHUB_TOKEN")) .model("gpt-4o") .githubModels(true) .build(); var chatModel = OpenAiSdkChatModel.builder() .options(chatOptions) .build();

Spring AI OpenAI와의 주요 차이점

이 구현은 Spring AI OpenAI 구현과 몇 가지 면에서 달라요.

Aspect Official OpenAI SDK Existing OpenAI
HTTP Client OkHttp (via official SDK) Spring RestClient/WebClient
API Updates Automatic via SDK updates Manual maintenance
Azure Support Native with passwordless auth Manual URL construction
GitHub Models Native support Not supported
Audio/Moderation Not yet supported Fully supported
Retry Logic SDK-managed (exponential backoff) Spring Retry (customizable)
Dependencies Official OpenAI SDK Spring WebFlux

OpenAI SDK를 써야 할 때:

  • 새 프로젝트를 시작할 때
  • 주로 Microsoft Foundry나 GitHub Models를 사용할 때
  • OpenAI의 자동 API 업데이트를 원할 때
  • 오디오 전사나 moderation 기능이 필요 없을 때
  • 공식 SDK 지원을 선호할 때

Spring AI OpenAI를 써야 할 때:

  • 이미 그걸 쓰는 기존 프로젝트일 때
  • 오디오 전사 또는 moderation 기능이 필요할 때
  • 세밀한 HTTP 제어가 필요할 때
  • 네이티브 Spring reactive 지원을 원할 때
  • 커스텀 재시도 전략이 필요할 때

관찰 가능성 (Observability)과 제한 사항

OpenAI SDK 구현은 Micrometer를 통한 Spring AI 관찰 가능성 기능을 지원해요. 모든 채팅 모델 작업이 모니터링·추적 대상으로 계측돼요.

아직 지원되지 않는 기능도 있어요: 오디오 음성 생성(TTS), 오디오 전사, Moderation API, File API 연산.

더 알아보기