經過前幾篇的介紹以及講解後,接下來要開始在 Spring 上架設 Semantic Kernel,將這個功能建立在後端,讓前端及後端可以分工合作
首先照前面建立 Spring boot + Spring Data 新增一個專案
接著新增以下的類別
我們要將 Semantic Kernel 的依賴加進專案,輸入以下的程式碼
</dependencies>
<dependency>
<groupId>com.microsoft.semantic-kernel</groupId>
<artifactId>semantickernel-api</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>com.microsoft.semantic-kernel</groupId>
<artifactId>semantickernel-aiservices-openai</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.microsoft.semantic-kernel</groupId>
<artifactId>semantickernel-bom</artifactId>
<version>1.2.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
記得點選 Load Maven
接著要設定一些基本的項目,這部分就跟前面介紹的是一樣的
spring.application.name=SementicKernelDemo
# PostgreSQL
spring.datasource.url=jdbc:postgresql://localhost:5432/semantic_kernel
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
# JPA
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database=postgresql
資料庫的部分跟之前也一樣,到 DB 新增資料庫
首先要確認連線正常
接著建立一個新的 Database,名成要跟上方 application.propertise 設定的一樣
這次先進行一個簡單的測試
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/semantic-kernel/demo")
public class SemanticKernelController {
private final SemanticKernelService service;
@GetMapping
public ResponseEntity<Object> TestChat() {
return ResponseEntity.ok(service.TestChat());
}
}
一些基本的設定
@Slf4j
@Service
@RequiredArgsConstructor
public class SemanticKernelService {
private final String modelId = "gpt-4o-mini";
private final String OPEN_AI_KEY = "API KEY";
AzureKeyCredential openAICredential = new AzureKeyCredential(OPEN_AI_KEY);
// Create the client
OpenAIAsyncClient client = new OpenAIClientBuilder()
.credential(openAICredential)
.buildAsyncClient();
// Create the chat completion service
ChatCompletionService openAIChatCompletion = OpenAIChatCompletion.builder()
.withOpenAIAsyncClient(client)
.withModelId(modelId)
.build();
// Initialize the kernel
Kernel kernel = Kernel.builder()
.withAIService(ChatCompletionService.class, openAIChatCompletion)
.build();
ChatCompletionService chatCompletionService;
{
try {
chatCompletionService = kernel.getService(ChatCompletionService.class);
} catch (ServiceNotFoundException e) {
log.error("Service : " + e.getMessage());
}
}
public Object TestChat(){
ChatHistory history = new ChatHistory();
history.addUserMessage("Hello, how are you?");
List<ChatMessageContent<?>> results = chatCompletionService.getChatMessageContentsAsync(
history,
kernel,
null
).block();
System.out.println(results.get(0).getContent());
return results.get(0).getContent();
}
接著只要使用 Postman 對這個方法的路徑測試就可以看到效果囉