一、项目结构
二、示例代码
1.Calulator.java
package org.ivy.aiservice.func;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.stereotype.Component;
@Component
public class Calculator {
@Tool("Calculates the length of a string")
int stringLength(String s) {
System.out.println("Called stringLength with s='" + s + "'");
return s.length();
}
@Tool("Calculates the sum of two numbers")
int add(int a, int b) {
System.out.println("Called add with a=" + a + ", b=" + b);
return a + b;
}
@Tool("Calculates the square root of a number")
double sqrt(int x) {
System.out.println("Called sqrt with x=" + x);
return Math.sqrt(x);
}
}
2.Assistant.java
package org.ivy.aiservice.service;
import dev.langchain4j.service.spring.AiService;
import dev.langchain4j.service.spring.AiServiceWiringMode;
/**
* 通过 @AiService 注解声明一个 AI 助手接口,并指定 chatModel 为 openAiChatModel。
*/
@AiService(
wiringMode = AiServiceWiringMode.EXPLICIT,
chatModel = "openAiChatModel",
tools = {"calculator"}
)
public interface Assistant {
String chat(String userMessage);
}
3.ChatController.java
package org.ivy.aiservice;
import org.ivy.aiservice.service.Assistant;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/hl")
@RestController
public class ChatController {
private final Assistant assistant;
public ChatController(Assistant assistant) {
this.assistant = assistant;
}
@GetMapping("/chat")
public String chat(
@RequestParam(value = "prompt",
defaultValue = "What is the square root of the sum of the numbers of letters in the words \"hello\" and \"world\"?")
String prompt) {
return assistant.chat(prompt);
}
}
4.ChatExamplesApplication.java
package org.ivy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ChatExamplesApplication {
public static void main(String[] args) {
SpringApplication.run(ChatExamplesApplication.class, args);
}
}
5.application.yml
base-url与api-key填入自己的即可
server:
port: 8801
spring:
application:
name: chat-high-level-service
langchain4j:
open-ai:
chat-model:
api-key: xxxx
model-name: gpt-4o-mini
base-url:xxxx
log-requests: true
log-responses: true
streaming-chat-model:
api-key: xxxx
base-url: xxxx
model-name: gpt-4o-mini
标签:langchain4j,springboot,接入,springframework,chat,import,org,public,String
From: https://blog.csdn.net/weixin_57166266/article/details/143309618