提示工程模式
本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。 |
基于《提示工程综合指南》的实用实现。该指南涵盖有效提示工程的理论、原则和模式,而此处我们演示如何通过 Spring AI Fluent 式的 ChatClient API 将这些概念转化为可运行的 Java 代码。本文使用的演示源代码位于:提示工程模式示例库。
1. 配置
配置章节详细说明如何使用 Spring AI 设置和调优大语言模型(LLM)。内容包括:根据用例选择合适的 LLM 供应商,以及配置控制模型输出质量、风格和格式的关键生成参数。
选择 LLM 提供商
进行提示工程时,首先需选择模型。Spring AI 支持多种 LLM 供应商(如 OpenAI、Anthropic、Google Vertex AI、AWS Bedrock、Ollama 等),只需更新配置即可切换供应商,无需修改应用代码。只需添加对应的 Starter 依赖 spring-ai-starter-model-<供应商名称>
。例如,启用 Anthropic Claude API 的方式如下:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-anthropic</artifactId>
</dependency>
你可以通过以下方式指定 LLM 模型名称:
.options(ChatOptions.builder()
.model("claude-3-7-sonnet-latest") // Use Anthropic's Claude model
.build())
各模型的启用详情请参阅 参考文档。
LLM 输出配置

在深入提示工程技术前,掌握如何配置 LLM 输出行为至关重要。Spring AI 通过 ChatOptions Builder 提供多种配置选项,用于控制生成的各个方面。
所有配置均可如以下示例所示以编程方式应用,也可通过 Spring application properties 在启动时设置。
Temperature
温度(Temperature)控制着模型响应的随机性或 “创造性”。
-
较低值(0.0-0.3):响应更确定且集中。适合事实性问题、分类或需要高度一致性的任务。
-
中间值(0.4-0.7):确定性与创造性的平衡。适合通用场景。
-
较高值(0.8-1.0):响应更具创造性、多样性和潜在惊喜。适合创意写作、头脑风暴或生成多样化选项。
.options(ChatOptions.builder()
.temperature(0.1) // Very deterministic output
.build())
理解温度参数对提示工程至关重要,因为不同技术需要匹配不同的温度配置才能发挥最佳效果。
MaxTokens
maxTokens
参数限制模型响应中可生成的 Token 数量。
-
低值(5-25):适用于生成单词、短短语或分类标签。
-
中值(50-500):适用于生成段落或简短说明。
-
高值(1000+):适用于长文本内容、故事或复杂解释。
.options(ChatOptions.builder()
.maxTokens(250) // Medium-length response
.build())
设置合适的输出长度对确保获得完整响应且避免冗余内容非常重要。
采样控制(Top-K 与 Top-P)
这些参数提供生成过程中 Token 选择机制的细粒度控制。
-
Top-K:将 token 选择限制为最可能的前 K 个候选项。较高值(如 40-50)会增加多样性。
-
Top-P(核采样):动态选择概率累积超过 P 的最小 token 集合。常用值为 0.8-0.95。
.options(ChatOptions.builder()
.topK(40) // Consider only the top 40 tokens
.topP(0.8) // Sample from tokens that cover 80% of probability mass
.build())
这些采样控制与温度参数协同作用,共同塑造响应特征。
结构化响应格式
除纯文本响应(使用 .content()
)外,Spring AI 通过 .entity()
方法支持将 LLM 响应直接映射为 Java 对象。
enum Sentiment {
POSITIVE, NEUTRAL, NEGATIVE
}
Sentiment result = chatClient.prompt("...")
.call()
.entity(Sentiment.class);
当与要求模型返回结构化数据的系统提示结合使用时,此功能尤为强大。
模型专属选项
虽然可移植的 ChatOptions
提供了跨 LLM 供应商的统一接口,但 Spring AI 还提供模型专属选项类,用于暴露供应商特定的功能和配置。这些专属选项可充分发挥各 LLM 供应商的独特能力。
// Using OpenAI-specific options
OpenAiChatOptions openAiOptions = OpenAiChatOptions.builder()
.model("gpt-4o")
.temperature(0.2)
.frequencyPenalty(0.5) // OpenAI-specific parameter
.presencePenalty(0.3) // OpenAI-specific parameter
.responseFormat(new ResponseFormat("json_object")) // OpenAI-specific JSON mode
.seed(42) // OpenAI-specific deterministic generation
.build();
String result = chatClient.prompt("...")
.options(openAiOptions)
.call()
.content();
// Using Anthropic-specific options
AnthropicChatOptions anthropicOptions = AnthropicChatOptions.builder()
.model("claude-3-7-sonnet-latest")
.temperature(0.2)
.topK(40) // Anthropic-specific parameter
.thinking(AnthropicApi.ThinkingType.ENABLED, 1000) // Anthropic-specific thinking configuration
.build();
String result = chatClient.prompt("...")
.options(anthropicOptions)
.call()
.content();
每个模型供应商都有各自的聊天选项实现(如 OpenAiChatOptions
、AnthropicChatOptions
、MistralAiChatOptions
),在实现通用接口的同时暴露供应商特定参数。这种方式既可通过可移植选项保持跨供应商兼容性,也能在需要特定供应商独有功能时使用模型专属选项。
需注意,使用模型专属选项会使代码与特定供应商绑定,降低可移植性。这是在获取高级供应商特性与保持应用供应商独立性之间的权衡。
2. 提示工程技术
以下每个章节实现了指南中的特定提示工程技术。结合《提示工程指南》与这些实现,你不仅能全面了解可用技术,还能掌握如何在实际 Java 应用中高效实现它们。
2.1 零样本提示
零样本提示(Zero-Shot Prompting)要求 AI 在不提供任何示例的情况下执行任务,测试模型从零开始理解并执行指令的能力。大语言模型通过海量文本训练,使其无需显式示范即可理解 “翻译”、“摘要” 或 “分类” 等任务内涵。
零样本提示适合简单任务(模型训练中可能已见过类似示例)且需最小化提示长度的场景。但性能会因任务复杂度和指令表述清晰度而异。
// Implementation of Section 2.1: General prompting / zero shot (page 15)
public void pt_zero_shot(ChatClient chatClient) {
enum Sentiment {
POSITIVE, NEUTRAL, NEGATIVE
}
Sentiment reviewSentiment = chatClient.prompt("""
Classify movie reviews as POSITIVE, NEUTRAL or NEGATIVE.
Review: "Her" is a disturbing study revealing the direction
humanity is headed if AI is allowed to keep evolving,
unchecked. I wish there were more movies like this masterpiece.
Sentiment:
""")
.options(ChatOptions.builder()
.model("claude-3-7-sonnet-latest")
.temperature(0.1)
.maxTokens(5)
.build())
.call()
.entity(Sentiment.class);
System.out.println("Output: " + reviewSentiment);
}
此示例演示如何在不提供样本的情况下对电影评论进行情感分类。注意:低温度值 (0.1) 确保更确定的结果,并通过直接 .entity(Sentiment.class)
映射到 Java 枚举。
参考文献:Brown, T. B. 等 (2020). 《语言模型是少样本学习者》. arXiv:2005.14165. https://arxiv.org/abs/2005.14165
2.2 单样本与少样本提示
少样本提示通过提供一个或多个示例引导模型响应,特别适用于需要特定输出格式的任务。通过展示期望的输入-输出对示例,模型可学习模式并应用于新输入,而无需显式参数更新。
单样本提示提供单个示例,适用于示例获取成本高或模式较简单的情况。少样本提示使用多个示例(通常 3-5 个),可帮助模型更好理解复杂任务的模式或展示正确输出的不同变体。
// Implementation of Section 2.2: One-shot & few-shot (page 16)
public void pt_one_shot_few_shots(ChatClient chatClient) {
String pizzaOrder = chatClient.prompt("""
Parse a customer's pizza order into valid JSON
EXAMPLE 1:
I want a small pizza with cheese, tomato sauce, and pepperoni.
JSON Response:
```
{
"size": "small",
"type": "normal",
"ingredients": ["cheese", "tomato sauce", "pepperoni"]
}
```
EXAMPLE 2:
Can I get a large pizza with tomato sauce, basil and mozzarella.
JSON Response:
```
{
"size": "large",
"type": "normal",
"ingredients": ["tomato sauce", "basil", "mozzarella"]
}
```
Now, I would like a large pizza, with the first half cheese and mozzarella.
And the other tomato sauce, ham and pineapple.
""")
.options(ChatOptions.builder()
.model("claude-3-7-sonnet-latest")
.temperature(0.1)
.maxTokens(250)
.build())
.call()
.content();
}
少样本提示对需要特定格式、处理边缘案例或任务定义可能模糊的情况特别有效。示例的质量和多样性显著影响性能。
参考文献:Brown, T. B. 等 (2020). 《语言模型是少样本学习者》. arXiv:2005.14165. https://arxiv.org/abs/2005.14165
2.3 系统、上下文与角色提示
系统提示
系统提示(System Prompting)为语言模型设定整体上下文和目的,定义模型行为的 “宏观框架”。它独立于具体用户查询,建立响应行为的约束条件与高层目标。
系统提示作为对话中持续的 “任务声明”,可设置输出格式、语气、伦理边界或角色定义等全局参数。与关注具体任务的用户提示不同,系统提示框定所有用户提示的解释方式。
// Implementation of Section 2.3.1: System prompting
public void pt_system_prompting_1(ChatClient chatClient) {
String movieReview = chatClient
.prompt()
.system("Classify movie reviews as positive, neutral or negative. Only return the label in uppercase.")
.user("""
Review: "Her" is a disturbing study revealing the direction
humanity is headed if AI is allowed to keep evolving,
unchecked. It's so disturbing I couldn't watch it.
Sentiment:
""")
.options(ChatOptions.builder()
.model("claude-3-7-sonnet-latest")
.temperature(1.0)
.topK(40)
.topP(0.8)
.maxTokens(5)
.build())
.call()
.content();
}
系统提示与 Spring AI 的实体映射功能结合时尤为强大:
// Implementation of Section 2.3.1: System prompting with JSON output
record MovieReviews(Movie[] movie_reviews) {
enum Sentiment {
POSITIVE, NEUTRAL, NEGATIVE
}
record Movie(Sentiment sentiment, String name) {
}
}
MovieReviews movieReviews = chatClient
.prompt()
.system("""
Classify movie reviews as positive, neutral or negative. Return
valid JSON.
""")
.user("""
Review: "Her" is a disturbing study revealing the direction
humanity is headed if AI is allowed to keep evolving,
unchecked. It's so disturbing I couldn't watch it.
JSON Response:
""")
.call()
.entity(MovieReviews.class);
系统提示对多轮对话特别重要,能确保跨查询的行为一致性,并为所有响应建立如 JSON 输出等格式约束。
参考文献:OpenAI. (2022). 《系统消息》. https://platform.openai.com/docs/guides/chat/introduction
角色提示
角色提示(Role Prompting)要求模型采用特定角色或人格,从而影响其内容生成方式。通过赋予特定身份、专业背景或视角,可控制响应的风格、语气、深度和框架。
角色提示利用模型模拟不同专业领域和沟通风格的能力。常见角色包括专家(如 “作为资深数据科学家”)、专业人士(如 “扮演旅行向导”)或风格化角色(如 “用莎士比亚风格解释”)。
// Implementation of Section 2.3.2: Role prompting
public void pt_role_prompting_1(ChatClient chatClient) {
String travelSuggestions = chatClient
.prompt()
.system("""
I want you to act as a travel guide. I will write to you
about my location and you will suggest 3 places to visit near
me. In some cases, I will also give you the type of places I
will visit.
""")
.user("""
My suggestion: "I am in Amsterdam and I want to visit only museums."
Travel Suggestions:
""")
.call()
.content();
}
角色提示可通过风格指令增强:
// Implementation of Section 2.3.2: Role prompting with style instructions
public void pt_role_prompting_2(ChatClient chatClient) {
String humorousTravelSuggestions = chatClient
.prompt()
.system("""
I want you to act as a travel guide. I will write to you about
my location and you will suggest 3 places to visit near me in
a humorous style.
""")
.user("""
My suggestion: "I am in Amsterdam and I want to visit only museums."
Travel Suggestions:
""")
.call()
.content();
}
此技术对专业领域知识特别有效,可实现跨响应的统一语气,并创建更具吸引力的个性化用户交互。
参考文献:Shanahan, M. 等 (2023). 《大语言模型角色扮演》. arXiv:2305.16367. https://arxiv.org/abs/2305.16367
上下文提示
上下文提示(Contextual Prompting)通过传递上下文参数为模型提供额外背景信息。该技术在不干扰主指令的情况下,增强模型对特定情境的理解,从而生成更相关和定制化的响应。
通过提供上下文信息,可帮助模型理解与当前查询相关的特定领域、受众、限制或背景事实,从而产生更准确、相关且框架恰当的响应。
// Implementation of Section 2.3.3: Contextual prompting
public void pt_contextual_prompting(ChatClient chatClient) {
String articleSuggestions = chatClient
.prompt()
.user(u -> u.text("""
Suggest 3 topics to write an article about with a few lines of
description of what this article should contain.
Context: {context}
""")
.param("context", "You are writing for a blog about retro 80's arcade video games."))
.call()
.content();
}
Spring AI 通过 param()
方法注入上下文变量实现简洁的上下文提示。该技术对以下场景特别有价值:模型需要特定领域知识时、为特定受众或场景调整响应时、以及确保响应符合特定约束或要求时。
参考文献:Liu, P. 等 (2021). 《什么是 GPT-3 的良好上下文示例?》. arXiv:2101.06804. https://arxiv.org/abs/2101.06804
2.4 分步回溯提示
分步回溯提示(Step-Back Prompting)通过先获取背景知识将复杂请求分解为简单步骤。该技术促使模型从具体问题 “回溯” 一步,先考虑更广泛的上下文、基本原理或与问题相关的常识,再处理具体查询。
通过将复杂问题分解为更易处理的组件并先建立基础知识,模型可为难题提供更准确的响应。
// Implementation of Section 2.4: Step-back prompting
public void pt_step_back_prompting(ChatClient.Builder chatClientBuilder) {
// Set common options for the chat client
var chatClient = chatClientBuilder
.defaultOptions(ChatOptions.builder()
.model("claude-3-7-sonnet-latest")
.temperature(1.0)
.topK(40)
.topP(0.8)
.maxTokens(1024)
.build())
.build();
// First get high-level concepts
String stepBack = chatClient
.prompt("""
Based on popular first-person shooter action games, what are
5 fictional key settings that contribute to a challenging and
engaging level storyline in a first-person shooter video game?
""")
.call()
.content();
// Then use those concepts in the main task
String story = chatClient
.prompt()
.user(u -> u.text("""
Write a one paragraph storyline for a new level of a first-
person shooter video game that is challenging and engaging.
Context: {step-back}
""")
.param("step-back", stepBack))
.call()
.content();
}
分步回溯提示对复杂推理任务、需要专业领域知识的问题特别有效,且当你需要更全面、深思熟虑的响应而非即时答案时尤为适用。
参考文献:Zheng, Z. 等 (2023). 《分步回溯:通过抽象激发大语言模型的推理能力》. arXiv:2310.06117. https://arxiv.org/abs/2310.06117
2.5 思维链(CoT)
思维链提示鼓励模型逐步推理问题,提升复杂推理任务的准确性。通过明确要求模型展示其思考过程或按逻辑步骤解决问题,可显著改善需要多步推理的任务表现。
思维链通过促使模型在生成最终答案前产生中间推理步骤来工作(类似人类解决复杂问题的方式)。这使得模型的思考过程显式化,帮助其得出更准确的结论。
// Implementation of Section 2.5: Chain of Thought (CoT) - Zero-shot approach
public void pt_chain_of_thought_zero_shot(ChatClient chatClient) {
String output = chatClient
.prompt("""
When I was 3 years old, my partner was 3 times my age. Now,
I am 20 years old. How old is my partner?
Let's think step by step.
""")
.call()
.content();
}
// Implementation of Section 2.5: Chain of Thought (CoT) - Few-shot approach
public void pt_chain_of_thought_singleshot_fewshots(ChatClient chatClient) {
String output = chatClient
.prompt("""
Q: When my brother was 2 years old, I was double his age. Now
I am 40 years old. How old is my brother? Let's think step
by step.
A: When my brother was 2 years, I was 2 * 2 = 4 years old.
That's an age difference of 2 years and I am older. Now I am 40
years old, so my brother is 40 - 2 = 38 years old. The answer
is 38.
Q: When I was 3 years old, my partner was 3 times my age. Now,
I am 20 years old. How old is my partner? Let's think step
by step.
A:
""")
.call()
.content();
}
关键短语 “让我们逐步思考” 会触发模型展示其推理过程。思维链对数学问题、逻辑推理任务及任何需要多步推理的提问特别有价值。通过显式化中间推理步骤,有助于减少错误。
参考文献:Wei, J. 等 (2022). 《思维链提示激发大语言模型推理能力》. arXiv:2201.11903. https://arxiv.org/abs/2201.11903
2.6 自我一致性
自我一致性(Self-Consistency,又称自洽性)通过多次运行模型并聚合结果来获得更可靠的答案。该技术通过为同一问题采样多样化的推理路径,并通过多数表决选择最一致的答案,解决大语言模型输出的可变性问题。
通过以不同温度或采样设置生成多条推理路径,再聚合最终答案,自我一致性(Self-consistency)能提升复杂推理任务的准确性。这本质上是一种针对大语言模型输出的集成方法。
// Implementation of Section 2.6: Self-consistency
public void pt_self_consistency(ChatClient chatClient) {
String email = """
Hi,
I have seen you use Wordpress for your website. A great open
source content management system. I have used it in the past
too. It comes with lots of great user plugins. And it's pretty
easy to set up.
I did notice a bug in the contact form, which happens when
you select the name field. See the attached screenshot of me
entering text in the name field. Notice the JavaScript alert
box that I inv0k3d.
But for the rest it's a great website. I enjoy reading it. Feel
free to leave the bug in the website, because it gives me more
interesting things to read.
Cheers,
Harry the Hacker.
""";
record EmailClassification(Classification classification, String reasoning) {
enum Classification {
IMPORTANT, NOT_IMPORTANT
}
}
int importantCount = 0;
int notImportantCount = 0;
// Run the model 5 times with the same input
for (int i = 0; i < 5; i++) {
EmailClassification output = chatClient
.prompt()
.user(u -> u.text("""
Email: {email}
Classify the above email as IMPORTANT or NOT IMPORTANT. Let's
think step by step and explain why.
""")
.param("email", email))
.options(ChatOptions.builder()
.temperature(1.0) // Higher temperature for more variation
.build())
.call()
.entity(EmailClassification.class);
// Count results
if (output.classification() == EmailClassification.Classification.IMPORTANT) {
importantCount++;
} else {
notImportantCount++;
}
}
// Determine the final classification by majority vote
String finalClassification = importantCount > notImportantCount ?
"IMPORTANT" : "NOT IMPORTANT";
}
自我一致性(Self-consistency)特别适用于高风险决策、复杂推理任务,以及当你需要比单一响应更可靠的答案时。代价是由于多次 API 调用导致的计算成本增加和延迟。
参考文献:Wang, X. 等 (2022). 《自我一致性提升语言模型中的思维链推理能力》. arXiv:2203.11171. https://arxiv.org/abs/2203.11171
2.7 思维树(ToT)
思维树(ToT)是思维链的高级扩展框架,通过同步探索多条推理路径将问题解决建模为搜索过程。模型会生成不同中间步骤、评估其潜力,并沿最有希望的路径深入探索。
该技术对存在多种解决路径的复杂问题特别有效,或在需要探索不同方案才能找到最优解时尤为强大。
原版《提示工程指南》未提供 ToT 的实现示例(可能因其复杂性)。以下演示核心概念的简化实现。 |
游戏解决方案 ToT 示例:
// Implementation of Section 2.7: Tree of Thoughts (ToT) - Game solving example
public void pt_tree_of_thoughts_game(ChatClient chatClient) {
// Step 1: Generate multiple initial moves
String initialMoves = chatClient
.prompt("""
You are playing a game of chess. The board is in the starting position.
Generate 3 different possible opening moves. For each move:
1. Describe the move in algebraic notation
2. Explain the strategic thinking behind this move
3. Rate the move's strength from 1-10
""")
.options(ChatOptions.builder()
.temperature(0.7)
.build())
.call()
.content();
// Step 2: Evaluate and select the most promising move
String bestMove = chatClient
.prompt()
.user(u -> u.text("""
Analyze these opening moves and select the strongest one:
{moves}
Explain your reasoning step by step, considering:
1. Position control
2. Development potential
3. Long-term strategic advantage
Then select the single best move.
""").param("moves", initialMoves))
.call()
.content();
// Step 3: Explore future game states from the best move
String gameProjection = chatClient
.prompt()
.user(u -> u.text("""
Based on this selected opening move:
{best_move}
Project the next 3 moves for both players. For each potential branch:
1. Describe the move and counter-move
2. Evaluate the resulting position
3. Identify the most promising continuation
Finally, determine the most advantageous sequence of moves.
""").param("best_move", bestMove))
.call()
.content();
}
参考文献:Yao, S. 等 (2023). 《思维树:大语言模型的审慎问题解决框架》. arXiv:2305.10601. https://arxiv.org/abs/2305.10601
2.8 自动提示工程
自动提示工程(Automatic Prompt Engineering,APE)利用 AI 生成并评估替代提示。这种元技术通过语言模型自身创建、优化和基准测试不同提示变体,以寻找特定任务的最佳表述。
通过系统化生成和评估提示变体,自动提示工程(APE)能比人工设计找到更高效的提示,尤其对复杂任务。这是利用 AI 自我提升性能的方法。
// Implementation of Section 2.8: Automatic Prompt Engineering
public void pt_automatic_prompt_engineering(ChatClient chatClient) {
// Generate variants of the same request
String orderVariants = chatClient
.prompt("""
We have a band merchandise t-shirt webshop, and to train a
chatbot we need various ways to order: "One Metallica t-shirt
size S". Generate 10 variants, with the same semantics but keep
the same meaning.
""")
.options(ChatOptions.builder()
.temperature(1.0) // High temperature for creativity
.build())
.call()
.content();
// Evaluate and select the best variant
String output = chatClient
.prompt()
.user(u -> u.text("""
Please perform BLEU (Bilingual Evaluation Understudy) evaluation on the following variants:
----
{variants}
----
Select the instruction candidate with the highest evaluation score.
""").param("variants", orderVariants))
.call()
.content();
}
自动提示工程(APE)对以下场景尤为重要:优化生产系统提示、解决人工提示工程已达极限的挑战性任务,以及系统化大规模提升提示质量。
参考文献:Zhou, Y. 等 (2022). 《大语言模型达到人类水平的提示工程能力》. arXiv:2211.01910. https://arxiv.org/abs/2211.01910
2.9 代码提示
代码提示指针对代码相关任务的专项技术,利用大语言模型理解和生成编程语言的能力,使其能够编写新代码、解释现有代码、调试问题以及进行语言间转换。
有效的代码提示通常需要:清晰的规范说明、适当的上下文(库/框架/风格指南),有时还需类似代码示例。温度值通常设为较低范围(0.1 - 0.3)以获得更确定的输出。
// Implementation of Section 2.9.1: Prompts for writing code
public void pt_code_prompting_writing_code(ChatClient chatClient) {
String bashScript = chatClient
.prompt("""
Write a code snippet in Bash, which asks for a folder name.
Then it takes the contents of the folder and renames all the
files inside by prepending the name draft to the file name.
""")
.options(ChatOptions.builder()
.temperature(0.1) // Low temperature for deterministic code
.build())
.call()
.content();
}
// Implementation of Section 2.9.2: Prompts for explaining code
public void pt_code_prompting_explaining_code(ChatClient chatClient) {
String code = """
#!/bin/bash
echo "Enter the folder name: "
read folder_name
if [ ! -d "$folder_name" ]; then
echo "Folder does not exist."
exit 1
fi
files=( "$folder_name"/* )
for file in "${files[@]}"; do
new_file_name="draft_$(basename "$file")"
mv "$file" "$new_file_name"
done
echo "Files renamed successfully."
""";
String explanation = chatClient
.prompt()
.user(u -> u.text("""
Explain to me the below Bash code:
```
{code}
```
""").param("code", code))
.call()
.content();
}
// Implementation of Section 2.9.3: Prompts for translating code
public void pt_code_prompting_translating_code(ChatClient chatClient) {
String bashCode = """
#!/bin/bash
echo "Enter the folder name: "
read folder_name
if [ ! -d "$folder_name" ]; then
echo "Folder does not exist."
exit 1
fi
files=( "$folder_name"/* )
for file in "${files[@]}"; do
new_file_name="draft_$(basename "$file")"
mv "$file" "$new_file_name"
done
echo "Files renamed successfully."
""";
String pythonCode = chatClient
.prompt()
.user(u -> u.text("""
Translate the below Bash code to a Python snippet:
{code}
""").param("code", bashCode))
.call()
.content();
}
代码提示对以下场景尤为有用:自动生成代码文档、快速原型开发、编程概念学习及编程语言间转换。结合少样本提示或思维链等技术可进一步提升效果。
参考文献:Chen, M. 等 (2021). 《评估基于代码训练的大语言模型》. arXiv:2107.03374. https://arxiv.org/abs/2107.03374
总结
Spring AI 提供简洁的 Java API 实现所有主流提示工程技术。结合 Spring 强大的实体映射与 Fluent 式 API,开发者能以清晰、可维护的代码构建复杂 AI 应用。
最有效的方法通常需组合多种技术 —— 例如系统提示搭配少样本示例,或思维链结合角色提示。Spring AI 的灵活 API 使这些组合易于实现。
在生产环境中使用时需注意:
-
使用不同参数(温度值、top-k、top-p)测试提示词效果
-
关键决策时建议采用自我一致性验证
-
利用 Spring AI 的实体映射实现类型安全响应
-
通过上下文提示注入应用专属知识
结合这些技术与 Spring AI 的强大抽象能力,可构建出输出稳定、高质量的健壮型 AI 应用。
参考引用
-
Brown, T. B., et al. (2020). "语言模型是少样本学习者。" arXiv:2005.14165.
-
Wei, J., et al. (2022). "思维链提示激发大型语言模型的推理能力。" arXiv:2201.11903.
-
Wang, X., et al. (2022). "自我一致性改进了语言模型中的思维链推理。" arXiv:2203.11171.
-
Yao, S., et al. (2023). "思想之树: 利用大型语言模型慎重解决问题。" arXiv:2305.10601.
-
Zhou, Y., et al. (2022). "大型语言模型是人类级别的提示工程师。" arXiv:2211.01910.
-
Zheng, Z., et al. (2023). "分步回溯: 在大型语言模型中通过抽象唤起推理。" arXiv:2310.06117.
-
Liu, P., et al. (2021). "怎样才能为 GPT-3 提供好的上下文示例?" arXiv:2101.06804.
-
Shanahan, M., et al. (2023). "使用大型语言模型进行角色扮演。" arXiv:2305.16367.
-
Chen, M., et al. (2021). "评估基于代码训练的大型语言模型。" arXiv:2107.03374.