Spring 接入 DeepSeek

DeepSeek Chat :: Spring AI Reference

调用OpenAI

新建项目

修改maven配置
        <repositories>
			<repository>
				<id>spring-milestones</id>
				<name>Spring Milestones</name>
				<url>https://repo.spring.io/milestone</url>
				<snapshots>
					<enabled>false</enabled>
				</snapshots>
			</repository>
		</repositories>

申请

首次调用 API | DeepSeek API Docs

创建API key

DeepSeek

修改application.properties
spring.ai.openai.api-key=<DEEPSEEK_API_KEY>
spring.ai.openai.base-url=https://api.deepseek.com
spring.ai.openai.chat.options.model=deepseek-chat
spring.ai.openai.chat.options.temperature=0.7

# The DeepSeek API doesn't support embeddings, so we need to disable it.
spring.ai.openai.embedding.enabled=false

ChatController
@RestController
public class ChatController {

    private final OpenAiChatModel chatModel;

    @Autowired
    public ChatController(OpenAiChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @GetMapping("/ai/generate")
    public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return Map.of("generation", this.chatModel.call(message));
    }

    @GetMapping("/ai/generateStream")
    public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return this.chatModel.stream(prompt);
    }
}

调用

http://localhost:8080/ai/generate

org.springframework.ai.retry.NonTransientAiException: 402 - {"error":
{"message":"Insufficient Balance","type":"unknown_error","param":null,
"code":"invalid_request_error"}}
余额不足,充值后再试

调用本地部署

修改依赖
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
        </dependency>


修改application.properties
spring.ai.ollama.base-url=http://localhost:11434/
spring.ai.ollama.chat.model=deepseek-r1:7b

ChatController
@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClient;

    public ChatController(ChatClient.Builder chatClient) {
        this.chatClient = chatClient.build();
    }

    @GetMapping("/chat")
    public ResponseEntity<Flux<String>> chat(@RequestParam(value = "message") String message) {
        try {
            Flux<String> response = chatClient.prompt(message).stream().content();
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
调用

http://localhost:8080/ai/chat?message=%E4%BD%A0%E6%98%AF%E8%B0%81

修改为

@GetMapping(value = "/chat", produces = "text/plain;charset=UTF-8")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值