领先一步
VMware 提供培训和认证,助您加速进步。
了解更多这篇博文演示了如何使用 Spring AI 来实现提示词工程技术的实际应用。
本文中的示例和模式基于全面的 提示词工程指南,该指南涵盖了有效提示词工程的理论、原则和模式。
这篇博文展示了如何使用 Spring AI 流畅的 ChatClient API 将这些概念转化为可运行的 Java 代码。
为方便起见,示例的结构遵循了原始指南中概述的相同模式和技术。
本文中使用的演示源代码可从以下地址获取: https://github.com/spring-projects/spring-ai-examples/tree/main/prompt-engineering/prompt-engineering-patterns
配置部分概述了如何使用 Spring AI 设置和调整您的大型语言模型 (LLM)。它涵盖了为您的用例选择合适的 LLM 提供商,以及配置控制模型输出质量、风格和格式的重要生成参数。
对于提示词工程,您将首先选择一个模型。Spring AI 支持 多个 LLM 提供商(例如 OpenAI、Anthropic、Google Vertex AI、AWS Bedrock、Ollama 等),这允许您无需更改应用程序代码即可切换提供商——只需更新您的配置即可。只需添加选定的启动器依赖项 spring-ai-starter-model-<MODEL-PROVIDER-NAME>
。例如,以下是如何启用 Anthropic Claude API
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-anthropic</artifactId>
</dependency>
以及一些连接属性: spring.ai.anthropic.api-key=${ANTHROPIC_API_KEY}
您可以像这样指定特定的 LLM 模型名称
.options(ChatOptions.builder()
.model("claude-3-7-sonnet-latest") // Use Anthropic's Claude model
.build())
有关启用和配置首选 AI 模型的详细信息,请参阅 参考文档。
在我们深入探讨提示词工程技术之前,了解如何配置 LLM 的输出行为至关重要。Spring AI 提供了几个配置选项,允许您通过 ChatOptions 构建器控制生成的各个方面。
所有配置都可以按以下示例所示通过编程方式应用,或者在启动时通过 Spring 应用程序属性应用。
Temperature 参数控制模型响应的随机性或“创造力”。
.options(ChatOptions.builder()
.temperature(0.1) // Very deterministic output
.build())
理解 Temperature 参数对于提示词工程至关重要,因为不同的技术会受益于不同的 Temperature 设置。
maxTokens
参数限制了模型在其响应中可以生成的 token(词片段)数量。
.options(ChatOptions.builder()
.maxTokens(250) // Medium-length response
.build())
设置适当的输出长度很重要,以确保您获得完整的响应而不会出现不必要的冗余。
这些参数允许您对生成过程中的 token 选择进行细粒度控制。
.options(ChatOptions.builder()
.topK(40) // Consider only the top 40 tokens
.topP(0.8) // Sample from tokens that cover 80% of probability mass
.build())
这些采样控制与 Temperature 协同工作,以塑造响应特征。
除了纯文本响应(使用 .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
),它们暴露了提供商特定的参数,同时仍然实现了通用接口。这种方法让您可以灵活地使用可移植选项来实现跨提供商兼容性,或者在需要访问特定提供商的独特功能时使用模型特定选项。
请注意,当使用模型特定选项时,您的代码将绑定到特定的提供商,从而降低了可移植性。这是在访问提供商高级功能与在应用程序中保持提供商独立性之间的权衡。
以下各节实现了指南中的特定提示词工程技术。通过结合遵循《提示词工程》指南和这些实现,您将对可用的提示词工程技术有透彻的理解,并了解如何在生产 Java 应用程序中有效地实现它们。
零样本提示(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);
}
此示例展示了如何在不提供示例的情况下对电影评论的情感进行分类。请注意,为了获得更具确定性的结果,使用了较低的 temperature (0.1),并且通过直接的 .entity(Sentiment.class)
映射到 Java 枚举类型。
参考文献:Brown, T. B., 等。(2020)。《Language Models are Few-Shot Learners》。arXiv:2005.14165。 https://arxiv.org/abs/2005.14165
少样本提示(Few-shot prompting)为模型提供一个或多个示例,以帮助指导其响应,这对于需要特定输出格式的任务特别有用。通过向模型展示期望的输入-输出对示例,它可以学习模式并将其应用于新的输入,而无需显式参数更新。
单样本(One-shot)提供单个示例,这在示例成本较高或模式相对简单时很有用。少样本(Few-shot)使用多个示例(通常 3-5 个)来帮助模型更好地理解更复杂任务中的模式或展示正确输出的不同变体。
// Implementation of Section 2.2: One-shot & few-shot (page 16)
public void pt_ones_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)。《Language Models are Few-Shot Learners》。arXiv:2005.14165。 https://arxiv.org/abs/2005.14165
系统提示(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)。《System Message》。 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)。《Role-Play with Large Language Models》。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)。《What Makes Good In-Context Examples for GPT-3?》。arXiv:2101.06804。 https://arxiv.org/abs/2101.06804
退一步提示(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)。《Take a Step Back: Evoking Reasoning via Abstraction in Large Language Models》。arXiv:2310.06117。 https://arxiv.org/abs/2310.06117
思维链提示(Chain of Thought prompting)鼓励模型逐步推理问题,这提高了复杂推理任务的准确性。通过明确要求模型展示其工作或按逻辑步骤思考问题,您可以显著提高需要多步骤推理的任务的性能。
思维链的工作原理是鼓励模型在生成最终答案之前生成中间推理步骤,类似于人类解决复杂问题的方式。这使得模型的思维过程显式化,并帮助它得出更准确的结论。
// 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)。《Chain-of-Thought Prompting Elicits Reasoning in Large Language Models》。arXiv:2201.11903。 https://arxiv.org/abs/2201.11903
自我一致性(Self-consistency)涉及多次运行模型并聚合结果以获得更可靠的答案。这项技术通过对同一问题采样不同的推理路径,并通过多数投票选择最一致的答案来解决 LLM 输出的变异性。
通过使用不同的 temperature 或采样设置生成多个推理路径,然后聚合最终答案,自我一致性提高了复杂推理任务的准确性。它本质上是一种用于 LLM 输出的集成方法。
// 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";
}
自我一致性对于高风险决策、复杂推理任务以及当您需要比单个响应更能确信的答案时特别有价值。其权衡是由于多次 API 调用而增加的计算成本和延迟。
参考文献:Wang, X., 等。(2022)。《Self-Consistency Improves Chain of Thought Reasoning in Language Models》。arXiv:2203.11171。 https://arxiv.org/abs/2203.11171
思之树(Tree of Thoughts, 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)。《Tree of Thoughts: Deliberate Problem Solving with Large Language Models》。arXiv:2305.10601。 https://arxiv.org/abs/2305.10601
自动提示词工程(Automatic Prompt Engineering)利用 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)。《Large Language Models Are Human-Level Prompt Engineers》。arXiv:2211.01910。 https://arxiv.org/abs/2211.01910
代码提示(Code prompting)是指用于代码相关任务的专门技术。这些技术利用 LLM 理解和生成编程语言的能力,使其能够编写新代码、解释现有代码、调试问题以及在不同语言之间进行翻译。
有效的代码提示通常涉及清晰的规范、适当的上下文(库、框架、代码风格指南)以及有时提供类似代码的示例。为了获得更具确定性的输出,Temperature 设置通常较低(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)。《Evaluating Large Language Models Trained on Code》。arXiv:2107.03374。 https://arxiv.org/abs/2107.03374
Spring AI 提供了一个优雅的 Java API,用于实现所有主要的提示词工程技术。通过将这些技术与 Spring 强大的实体映射和流畅的 API 相结合,开发者可以构建具有简洁、可维护代码的复杂 AI 驱动应用程序。
最有效的方法通常涉及结合多种技术——例如,将系统提示与少样本示例结合使用,或将思维链与角色提示结合使用。Spring AI 灵活的 API 使这些组合易于实现。
对于生产应用程序,请记住:
通过这些技术和 Spring AI 强大的抽象能力,您可以创建提供一致、高质量结果的强大 AI 驱动应用程序。