ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

5、Spring AI Prompt API(提示词)

2026/8/5 10:43:53 拓冰建站 浏览量
5、Spring AI Prompt API(提示词) 什么是 Spring AI Prompt APISpring AI Prompt API 是 Spring AI 框架中用于构建和管理 AI 模型输入即Prompt的核心模块。它提供了一套结构化的 API帮助开发者创建清晰、可维护的 AI 提示词。类比理解如果你熟悉 Spring MVC 或 JDBC可以这样理解Prompt API类似于 Spring MVC 中的View层负责构建和渲染动态内容Prompt API也类似于JDBC是与 AI 模型交互的基础层更高层的ChatClient类似于JdbcClient提供更高级的封装核心概念解析1. Prompt提示Prompt是发送给 AI 模型的请求对象包含一系列Message和可选的ChatOptions。publicclassPromptimplementsModelRequestListMessage{privatefinalListMessagemessages;// 消息列表privateChatOptionschatOptions;// 请求选项如温度、最大token等}关键方法方法功能getUserMessage()获取最后一条用户消息getSystemMessage()获取第一条系统消息getUserMessages()获取所有用户消息getSystemMessages()获取所有系统消息2. Message消息Message是 Prompt 的基本组成单元每条消息都有一个角色Role。publicinterfaceMessageextendsContent{MessageTypegetMessageType();// 获取消息类型角色}四种消息角色角色含义用途System系统设定 AI 的行为和风格定义 AI 的身份、语气、规则User用户用户的输入问题、命令、陈述Assistant助手AI 的回复保持对话连贯性Tool工具工具调用的返回结果当 AI 需要执行外部功能时使用publicenumMessageType{USER(user),ASSISTANT(assistant),SYSTEM(system),TOOL(tool);}3. PromptTemplate提示模板PromptTemplate用于创建带有占位符的模板支持动态替换内容。默认使用StringTemplate引擎占位符语法为{变量名}。publicinterfaceTemplateRendererextendsBiFunctionString,MapString,Object,String{Stringapply(Stringtemplate,MapString,Objectvariables);}基础用法示例示例 1简单的 PromptTemplate// 创建模板PromptTemplatepromptTemplatenewPromptTemplate(Tell me a {adjective} joke about {topic});// 替换占位符并创建 PromptPromptpromptpromptTemplate.create(Map.of(adjective,funny,topic,programming));// 发送给 AI 模型returnchatModel.call(prompt).getResult();示例 2使用 System 和 User 角色// 用户消息StringuserText Tell me about three famous pirates from the Golden Age of Piracy. Write at least a sentence for each pirate. ;MessageuserMessagenewUserMessage(userText);// 系统消息使用模板StringsystemText You are a helpful AI assistant that helps people find information. Your name is {name} You should reply to the users request with your name and also in the style of a {voice}. ;SystemPromptTemplatesystemPromptTemplatenewSystemPromptTemplate(systemText);MessagesystemMessagesystemPromptTemplate.createMessage(Map.of(name,Captain Jack,voice,a pirate));// 组合成 PromptPromptpromptnewPrompt(List.of(userMessage,systemMessage));// 获取响应ListGenerationresponsechatModel.call(prompt).getResults();高级用法自定义模板分隔符默认使用{}作为占位符如果提示词中包含 JSON 内容可以修改分隔符PromptTemplatepromptTemplatePromptTemplate.builder().renderer(StTemplateRenderer.builder().startDelimiterToken().endDelimiterToken().build()).template( Tell me the names of 5 movies whose soundtrack was composed by composer. ).build();StringpromptpromptTemplate.render(Map.of(composer,John Williams));从资源文件加载模板可以将模板内容放在单独的文件中// 在 Spring 组件中注入资源Value(classpath:/prompts/system-message.txt)privateResourcesystemResource;// 使用资源创建模板SystemPromptTemplatesystemPromptTemplatenewSystemPromptTemplate(systemResource);资源文件示例(system-message.st)You are a helpful AI assistant. Your name is {name}. You should always respond in {language}.Prompt 工程Prompt Engineering什么是 Prompt 工程Prompt 工程是设计和优化提示词的过程好的提示词能显著提升 AI 模型的输出质量。创建有效提示词的技巧清晰的指令像与人沟通一样给出明确的指示提供上下文给 AI 提供必要的背景信息设定输出格式指定期望的输出格式如 JSON、列表等使用示例提供少量示例帮助 AI 理解意图示例优化后的提示词StringsystemText You are an expert Java developer. Follow these rules: 1. Always write clean and well-documented code 2. Use Java 21 features where appropriate 3. Include error handling 4. Return only the code without explanations Format your response as JSON: { code: your code here } ;完整示例项目依赖配置在pom.xml中添加 Spring AI 依赖projectxmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.example/groupIdartifactIdspring-ai/artifactIdversion1.0-SNAPSHOT/version/parentartifactIdspring-ai-prompt/artifactIdpackagingjar/packagingnamespring-ai-prompt/nameurlhttp://maven.apache.org/urlpropertiesproject.build.sourceEncodingUTF-8/project.build.sourceEncoding/propertiesdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-logging/artifactId/dependencydependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-starter-model-openai/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactId/dependencydependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-vector-store-advisor/artifactId/dependency/dependencies/project配置文件spring:ai:openai:api-key:${OPENAI_API_KEY}#百炼平台base-url:https://ws-ydcwsgdlv1xyb60v.cn-beijing.maas.aliyuncs.com/compatible-mode/v1chat:model:qwen3.5-plusembedding:model:text-embedding-v4服务类示例packageorg.example.config;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;ConfigurationpublicclassChatConfig{BeanpublicChatClientchatClient(ChatClient.Builderbuilder){returnbuilder.defaultAdvisors(newSimpleLoggerAdvisor()).build();}}packageorg.example.controller;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.ai.chat.messages.Message;importorg.springframework.ai.chat.messages.UserMessage;importorg.springframework.ai.chat.prompt.Prompt;importorg.springframework.ai.chat.prompt.SystemPromptTemplate;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.core.io.Resource;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;importjava.util.List;importjava.util.Map;RestControllerRequestMapping(/chat)publicclassChatController{AutowiredChatClientchatClient;Value(classpath:prompts/system-message.txt)ResourcesystemTemplate;GetMapping(/call)publicStringcall(RequestParamStringquestion){// 使用资源创建模板SystemPromptTemplatesystemPromptTemplatenewSystemPromptTemplate(systemTemplate);MessagesystemMessagesystemPromptTemplate.createMessage(Map.of(name,张三,language,中文));MessageuserMessagenewUserMessage(question);// 组合成 PromptPromptpromptnewPrompt(List.of(userMessage,systemMessage));returnthis.chatClient.prompt(prompt).call().content();}}常见问题Q1: Prompt 和 Message 的关系是什么A:Prompt是一个容器包含多条Message。每条Message代表对话中的一个角色用户、系统、助手等。Q2: 什么时候使用 SystemMessageA:SystemMessage用于设定 AI 的行为模式和上下文通常放在对话的开头用于定义 AI 的身份、规则和回复风格。Q3: 如何处理多轮对话A:在多轮对话中需要保留历史消息。每次调用时将之前的UserMessage和AssistantMessage都包含在Prompt中。Q4: 可以自定义模板引擎吗A:可以。实现TemplateRenderer接口并注入到PromptTemplate中即可。总结✅Prompt的概念和结构✅Message的四种角色及其用途✅PromptTemplate的基础和高级用法✅Prompt 工程的基本原则✅ 完整的代码示例Spring AI Prompt API 提供了一套灵活、结构化的方式来构建 AI 提示词无论是简单的单轮对话还是复杂的多轮交互都能轻松应对。