1+ package azure .openai ;
2+
3+ import com .azure .ai .openai .OpenAIAsyncClient ;
4+ import com .azure .ai .openai .OpenAIClient ;
5+ import com .azure .ai .openai .OpenAIClientBuilder ;
6+ import com .azure .core .credential .AzureKeyCredential ;
7+ import com .microsoft .semantickernel .Kernel ;
8+ import com .microsoft .semantickernel .SKBuilders ;
9+ import com .microsoft .semantickernel .chatcompletion .ChatCompletion ;
10+ import com .microsoft .semantickernel .chatcompletion .ChatHistory ;
11+ import org .springframework .boot .autoconfigure .AutoConfiguration ;
12+ import org .springframework .boot .autoconfigure .condition .ConditionalOnClass ;
13+ import org .springframework .boot .autoconfigure .condition .ConditionalOnMissingBean ;
14+ import org .springframework .boot .context .properties .EnableConfigurationProperties ;
15+ import org .springframework .context .annotation .Bean ;
16+ import org .springframework .util .Assert ;
17+
18+ @ AutoConfiguration
19+ @ EnableConfigurationProperties (AzureOpenAiConnectionProperties .class )
20+ public class AzureOpenAIAutoConfiguration {
21+
22+ @ Bean
23+ @ ConditionalOnClass (OpenAIClientBuilder .class )
24+ @ ConditionalOnMissingBean
25+ public OpenAIClient openAIClient (AzureOpenAiConnectionProperties connectionProperties ) {
26+ Assert .hasText (connectionProperties .getEndpoint (), "Azure OpenAI endpoint must be set" );
27+ Assert .hasText (connectionProperties .getKey (), "Azure OpenAI key must be set" );
28+ return new OpenAIClientBuilder ().endpoint (connectionProperties .getEndpoint ())
29+ .credential (new AzureKeyCredential (connectionProperties .getKey ()))
30+ .buildClient ();
31+ }
32+
33+ @ Bean
34+ @ ConditionalOnClass (OpenAIAsyncClient .class )
35+ public OpenAIAsyncClient openAIAsyncClient (AzureOpenAiConnectionProperties connectionProperties ) {
36+ Assert .hasText (connectionProperties .getEndpoint (), "Azure OpenAI endpoint must be set" );
37+ Assert .hasText (connectionProperties .getKey (), "Azure OpenAI key must be set" );
38+ return new OpenAIClientBuilder ().endpoint (connectionProperties .getEndpoint ())
39+ .credential (new AzureKeyCredential (connectionProperties .getKey ()))
40+ .buildAsyncClient ();
41+ }
42+
43+ @ Bean
44+ public Kernel semanticKernel (AzureOpenAiConnectionProperties connectionProperties ) {
45+ Assert .hasText (connectionProperties .getDeploymentName (),
46+ "Azure OpenAI deployment name must be set and match the ModelID" );
47+ OpenAIAsyncClient openAIAsyncClient = openAIAsyncClient (new AzureOpenAiConnectionProperties ());
48+ ChatCompletion <ChatHistory > chatCompletion = SKBuilders .chatCompletion ()
49+ .withOpenAIClient (openAIAsyncClient )
50+ .withModelId (connectionProperties .getDeploymentName ())
51+ .build ();
52+ return SKBuilders .kernel ().withDefaultAIService (chatCompletion ).build ();
53+ }
54+
55+ }
0 commit comments