提示工程模式

基于综合提示工程指南的提示工程技术实际应用。 本指南涵盖了有效提示工程的理论、原理和模式,而在这里我们演示如何利用Spring AI流畅的ChatClient API将这些概念转化为可运行的Java代码。 本文使用的演示源代码可在:提示工程模式示例中获取。spring-doc.cadn.net.cn

1. 配置

配置部分概述了如何用 Spring AI 设置和调优你的大型语言模型(LLM)。 它涵盖了为你的用例选择合适的LLM提供商,以及配置控制模型输出质量、样式和格式的重要生成参数。spring-doc.cadn.net.cn

LLM提供者选择

对于提示工程,你将从选择一个模型开始。 Spring AI 支持多个大型语言模型提供商(例如 OpenAI、Anthropic、Google Vertex AI、AWS Bedrock、Ollama 等),允许你在不更改应用代码的情况下切换服务提供商——只需更新配置即可。 只需添加选定的起始依赖spring-ai-starter-model-<MODEL-PROVIDER-NAME>. 例如,以下是启用 Anthropic Claude API 的方法:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-anthropic</artifactId>
</dependency>

你可以这样指定LLM模型名称:spring-doc.cadn.net.cn

.options(ChatOptions.builder()
        .model("claude-3-7-sonnet-latest")  // Use Anthropic's Claude model
        .build())

参考文档中查找启用每个模型的详细信息。spring-doc.cadn.net.cn

LLM 输出配置

聊天选项流程

在深入探讨提示工程技术之前,首先必须了解如何配置LLM的输出行为。Spring AI 提供了多种配置选项,让你可以通过 ChatOptions 构建器控制生成的各个方面。spring-doc.cadn.net.cn

所有配置都可以通过程序方式应用,如下面的示例所示,或通过 Spring 应用属性在启动时应用。spring-doc.cadn.net.cn

温度

温度控制模型响应的随机性或“创造力”。spring-doc.cadn.net.cn

  • 较低的数值(0.0-0.3):反应更具确定性和集中性。更适合事实问题、分类或一致性至关重要的任务。spring-doc.cadn.net.cn

  • 中等值(0.4-0.7):在决定论与创造力之间保持平衡。适合一般使用场景。spring-doc.cadn.net.cn

  • 更高数值(0.8-1.0):反应更具创意、变化,且可能带来惊喜。更适合创意写作、头脑风暴或产生多样化的选择。spring-doc.cadn.net.cn

.options(ChatOptions.builder()
        .temperature(0.1)  // Very deterministic output
        .build())

了解温度对于即时工程至关重要,因为不同技术会受益于不同的温度设置。spring-doc.cadn.net.cn

输出长度(MaxTokens)

maxTokens参数限制模型在响应中能生成的词(词块)数量。spring-doc.cadn.net.cn

.options(ChatOptions.builder()
        .maxTokens(250)  // Medium-length response
        .build())

设置合适的输出长度很重要,这样才能确保你得到完整的回答,避免不必要的冗长。spring-doc.cadn.net.cn

采样控制(Top-K 和 Top-P)

这些参数让你在生成时对Tokens选择过程进行细致控制。spring-doc.cadn.net.cn

  • Top-K:限制Tokens选择仅限于最可能的K个下一个Tokens。更高的数值(例如40-50)会带来更多的多样性。spring-doc.cadn.net.cn

  • Top-P(核抽样):动态选择累计概率超过P的最小Tokens集。常见的值如0.8-0.95。spring-doc.cadn.net.cn

.options(ChatOptions.builder()
        .topK(40)      // Consider only the top 40 tokens
        .topP(0.8)     // Sample from tokens that cover 80% of probability mass
        .build())

这些采样控制与温度对形状响应特性的配合。spring-doc.cadn.net.cn

结构化响应格式

配合纯文本回复(使用.content()Spring AI 使得利用.entity()方法。spring-doc.cadn.net.cn

enum Sentiment {
    POSITIVE, NEUTRAL, NEGATIVE
}

Sentiment result = chatClient.prompt("...")
        .call()
        .entity(Sentiment.class);

当系统提示指示模型返回结构化数据时,这一功能尤为强大。spring-doc.cadn.net.cn

型号特定选项

而便携式ChatOptions提供跨不同LLM提供者的一致接口,Spring AI还提供模型特定的选项类,暴露提供者特有的功能和配置。这些模型特定的选项让你能够利用每个LLM提供商的独特能力。spring-doc.cadn.net.cn

// 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)在实现通用接口的同时,暴露了提供者特定的参数。这种方式让您灵活地使用便携选项实现跨运营商兼容性,或在需要访问特定提供商独特功能时使用特定型号选项。spring-doc.cadn.net.cn

请注意,使用特定型号的选项时,你的代码会绑定到该特定提供商,降低了可移植性。这是在访问高级服务提供者专属功能与保持应用中提供者独立性之间的权衡。spring-doc.cadn.net.cn

2. 提示工程技术

以下每个章节都实现了指南中特定的提示工程技术。 通过遵循“提示工程”指南和这些实现,你不仅能深入了解可用的提示工程技术,还能有效地在生产环境中实现它们。spring-doc.cadn.net.cn

2.1 零点提示

零样本提示是指让人工智能执行任务,但不提供任何示例。这种方法测试模型从零开始理解和执行指令的能力。大型语言模型训练于庞大的文本语料库,使其能够理解“翻译”、“摘要”或“分类”等任务的内容,而无需明确演示。spring-doc.cadn.net.cn

零射击很适合模型在训练中可能见过类似例子的简单任务,或者你想尽量减少提示时长。然而,性能可能因任务复杂度和指令的制定程度而有所不同。spring-doc.cadn.net.cn

// 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 枚举。spring-doc.cadn.net.cn

参考:Brown, T. B. 等(2020)。“语言模型是少数样本学习者。”arXiv:2005.14165。https://arxiv.org/abs/2005.14165spring-doc.cadn.net.cn

2.2 单次触发与少数触发提示

少数样本提示为模型提供一个或多个示例,帮助指导其响应,尤其适用于需要特定输出格式的任务。通过展示期望输入输出对的模型示例,它可以学习模式并将其应用于新输入,而无需显式参数更新。spring-doc.cadn.net.cn

单次游戏提供单一示例,适用于示例成本高或图案相对简单时。少数样本使用多个示例(通常为3-5个),帮助模型更好地理解复杂任务中的模式,或展示正确输出的不同变化。spring-doc.cadn.net.cn

// 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();
}

少数样本提示对于需要特定格式、处理边缘情况或任务定义可能模糊且缺乏示例的任务尤其有效。样本的质量和多样性显著影响性能。spring-doc.cadn.net.cn

参考:Brown, T. B. 等(2020)。“语言模型是少数样本学习者。”arXiv:2005.14165。https://arxiv.org/abs/2005.14165spring-doc.cadn.net.cn

2.3 系统、上下文与角色提示

系统提示

系统提示为语言模型设定整体语境和目的,定义模型应执行的“大局”。它建立了模型响应的行为框架、约束和高层目标,独立于具体用户查询之外。spring-doc.cadn.net.cn

系统提示作为贯穿整个对话的“使命声明”,允许你设置全局参数,如输出格式、语气、伦理界限或角色定义。与专注于特定任务的用户提示不同,系统提示框架了所有用户提示应如何解释。spring-doc.cadn.net.cn

// 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 的实体映射功能结合时尤为强大:spring-doc.cadn.net.cn

// 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 输出。spring-doc.cadn.net.cn

参考:OpenAI。(2022)。“系统消息。”https://platform.openai.com/docs/guides/chat/introductionspring-doc.cadn.net.cn

角色提示

角色提示指示模型采用特定角色或角色,这会影响其内容生成方式。通过赋予模特特定的身份、专长或视角,你可以影响其回答的风格、语气、深度和框架。spring-doc.cadn.net.cn

角色提示利用模型模拟不同专业领域和沟通风格的能力。常见角色包括专家(例如,“你是经验丰富的数据科学家”)、专业角色(例如,“作为旅行导游”)或风格角色(例如,“像你是莎士比亚一样解释”)。spring-doc.cadn.net.cn

// 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();
}

角色提示可以通过样式说明来增强:spring-doc.cadn.net.cn

// 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();
}

该技术对专业领域知识尤其有效,能够实现回复间的一致语气,并与用户互动更具吸引力和个性化。spring-doc.cadn.net.cn

参考:Shanahan, M. 等(2023)。“大型语言模型的角色扮演。”arXiv:2305.16367。https://arxiv.org/abs/2305.16367spring-doc.cadn.net.cn

情境提示

上下文提示通过传递上下文参数,为模型提供额外的背景信息。该技术丰富了模型对具体情境的理解,使得回答更相关且更个性化,同时避免主指令显得杂乱。spring-doc.cadn.net.cn

通过提供上下文信息,你帮助模型理解与当前查询相关的具体领域、受众、约束或背景事实。这会带来更准确、相关且结构恰当的回答。spring-doc.cadn.net.cn

// 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() 方法注入上下文变量,使上下文提示变得干净利落。当模型需要特定领域知识、调整响应以适应特定受众或场景,以及确保响应符合特定约束或需求时,这种技术尤为有价值。spring-doc.cadn.net.cn

参考:Liu, P. 等(2021)。“什么是适合GPT-3的上下文示例?”arXiv:2101.06804。https://arxiv.org/abs/2101.06804spring-doc.cadn.net.cn

2.4 退步提示

退步提示通过先获得背景知识,将复杂请求拆解为更简单的步骤。该技术鼓励模型先“退一步”,从眼前的问题中退一步,考虑与问题相关的更广泛背景、基本原则或一般知识,然后再回答具体问题。spring-doc.cadn.net.cn

通过将复杂问题分解为更易管理的组成部分,并先建立基础知识,模型能够对难题提供更准确的回答。spring-doc.cadn.net.cn

// 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();
}

退步提示在复杂推理任务、需要专业领域知识的问题,以及当你希望得到更全面、更有深度的回答而非立即答案时,尤其有效。spring-doc.cadn.net.cn

参考:Zheng, Z. 等(2023)。《退一步:通过大型语言模型中的抽象唤起推理。》arXiv:2310.06117。https://arxiv.org/abs/2310.06117spring-doc.cadn.net.cn

2.5 思维链(CoT)

思维链提示鼓励模型逐步推理问题,从而提高复杂推理任务的准确性。通过明确要求模型展示其工作或按逻辑步骤思考问题,你可以显著提升需要多步推理任务的表现。spring-doc.cadn.net.cn

CoT的工作原理是鼓励模型在给出最终答案前生成中间推理步骤,类似于人类解决复杂问题的方式。这使得模型的思维过程更加明确,有助于得出更准确的结论。spring-doc.cadn.net.cn

// 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();
}

关键短语“让我们一步步思考”触发模型展示其推理过程。CoT对于数学问题、逻辑推理任务以及任何需要多步推理的题目尤其有价值。它通过明确中级推理来帮助减少错误。spring-doc.cadn.net.cn

参考:Wei, J. 等(2022)。“思维链提示在大型语言模型中激发推理。”arXiv:2201.11903。https://arxiv.org/abs/2201.11903spring-doc.cadn.net.cn

2.6 自洽性

自洽性涉及多次运行模型并汇总结果以获得更可靠的答案。该技术通过抽样不同推理路径,并通过多数投票选择最一致的答案,解决LLM输出的变异性。spring-doc.cadn.net.cn

通过生成多条不同温度或采样设置的推理路径,然后汇总最终答案,自洽性提高了复杂推理任务的准确性。它本质上是一种集成方法用于LLM输出。spring-doc.cadn.net.cn

// 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 调用,计算成本和延迟增加。spring-doc.cadn.net.cn

参考:Wang, X. 等(2022)。“自洽性提升语言模型中的思维链推理。”arXiv:2203.11171。https://arxiv.org/abs/2203.11171spring-doc.cadn.net.cn

2.7 思绪(ToT)之树

思维(ToT)之树是一个高级推理框架,通过同时探索多条推理路径来扩展思维链。它将问题解决视为一种搜索过程,模型生成不同的中间步骤,评估其潜力,并探索最有前景的路径。spring-doc.cadn.net.cn

该技术对于具有多种可能方法的复杂问题,或需要在找到最优路径前探索多种方案时,尤为有效。spring-doc.cadn.net.cn

最初的“提示工程”指南没有提供《提示工程》的实现示例,可能是因为其复杂性。下面是一个简化的例子,展示了核心概念。spring-doc.cadn.net.cn

游戏解决 TOT 示例:spring-doc.cadn.net.cn

// 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.10601spring-doc.cadn.net.cn

2.8 自动提示工程

自动提示工程利用人工智能生成和评估替代提示。这种元技术利用语言模型本身创建、优化和基准不同的提示变体,以寻找特定任务的最佳表达方式。spring-doc.cadn.net.cn

通过系统生成和评估提示变化,APE能够找到比手工工程更有效的提示,尤其是在复杂任务中。这是一种利用AI提升自身性能的方法。spring-doc.cadn.net.cn

// 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对于优化制作系统的提示、解决手工提示工程已达到极限的挑战任务以及系统性地大规模提升提示质量尤其有价值。spring-doc.cadn.net.cn

参考: 周, Y. 等(2022)。“大型语言模型是人类层级的提示工程师。”arXiv:2211.01910。https://arxiv.org/abs/2211.01910spring-doc.cadn.net.cn

2.9 代码提示

代码提示指的是用于代码相关任务的专业技术。这些技术利用大型语言模型理解和生成编程语言的能力,使其能够编写新代码、解释现有代码、调试问题以及语言间的转换。spring-doc.cadn.net.cn

有效的代码提示通常需要明确的规范、适当的上下文(库、框架、风格指南),有时还会用类似代码的示例。温度设置通常较低(0.1-0.3),以适应更确定的输出。spring-doc.cadn.net.cn

// 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();
}

代码提示对于自动化代码文档、原型设计、编程概念学习以及编程语言间的转换尤其有价值。通过结合少数提示法或思维链法等技巧,效果还可以进一步提升。spring-doc.cadn.net.cn

参考:陈M.等(2021)。“评估基于代码训练的大型语言模型。”arXiv:2107.03374。https://arxiv.org/abs/2107.03374spring-doc.cadn.net.cn

结论

Spring AI 提供了一个优雅的 Java API,用于实现所有主要的提示工程技术。通过将这些技术与Spring强大的实体映射和流畅API结合,开发者可以构建带有简洁、易维护代码的复杂AI应用。spring-doc.cadn.net.cn

最有效的方法通常是结合多种技术——例如,使用系统提示和少量示例,或使用思维链与角色提示。Spring AI 灵活的 API 使这些组合易于实现。spring-doc.cadn.net.cn

对于生产应用,请记住:spring-doc.cadn.net.cn

  1. 测试提示,参数不同(温度、top-k、top-p)spring-doc.cadn.net.cn

  2. 考虑在关键决策中使用自洽性spring-doc.cadn.net.cn

  3. 利用 Spring AI 的实体映射实现类型安全响应spring-doc.cadn.net.cn

  4. 使用上下文提示来提供应用特定的知识spring-doc.cadn.net.cn

借助这些技术和Spring AI强大的抽象,你可以创建强大的AI驱动应用,提供稳定且高质量的结果。spring-doc.cadn.net.cn

引用

  1. Brown, T. B. 等(2020)。“语言模型是少数样本学习者。”arXiv:2005.14165。spring-doc.cadn.net.cn

  2. Wei, J. 等(2022)。“思维链提示在大型语言模型中激发推理。”arXiv:2201.11903。spring-doc.cadn.net.cn

  3. Wang, X. 等(2022)。“自洽性提升语言模型中的思维链推理。”arXiv:2203.11171。spring-doc.cadn.net.cn

  4. Yao, S. 等(2023)。“思维之树:利用大型语言模型进行有意识的问题解决。”arXiv:2305.10601。spring-doc.cadn.net.cn

  5. 周,Y. 等(2022)。“大型语言模型是人类层级的提示工程师。”arXiv:2211.01910。spring-doc.cadn.net.cn

  6. Zheng, Z. 等(2023)。《退一步:通过大型语言模型中的抽象唤起推理。》arXiv:2310.06117。spring-doc.cadn.net.cn

  7. Liu, P. 等(2021)。“什么是适合GPT-3的上下文示例?”arXiv:2101.06804。spring-doc.cadn.net.cn

  8. Shanahan, M. 等(2023)。“大型语言模型的角色扮演。”arXiv:2305.16367。spring-doc.cadn.net.cn

  9. 陈M.等(2021)。“评估基于代码训练的大型语言模型。”arXiv:2107.03374。spring-doc.cadn.net.cn

  10. 春季AI文档spring-doc.cadn.net.cn

  11. ChatClient API 参考spring-doc.cadn.net.cn

  12. 谷歌提示工程指南spring-doc.cadn.net.cn