将下面的文章整理成10条关于产品经理的建议：<blockquote><p>文章通过实际源码详细介绍了Basic Reflection模式的实现方法，包括构建Generator和Reflector的过程。阅读本文可以帮助读者更好地理解Basic Reflection的概念和实现过程。</p>
</blockquote><p><img class="aligncenter" src="https://image.woshipm.com/2024/07/24/f8e4ff3c-4992-11ef-a43d-00163e142b65.png" /></p>
<p>在前面几篇文章中，风叔依次介绍了REWOO、Plan-and-Execute和LLM Compiler三种更侧重规划能力的AI Agent设计模式。</p>
<p>从最初的ReAct模式出发，加入规划能力即演变成REWOO；再加上Replan能力即演变成Plan-and-Execute；最后再加上DAG和并行处理能力，即演变成LLM Compiler。</p>
<p>从这篇文章开始，我们将转向另外几种侧重反思的AI Agent模式，我们首先从Basic Reflection开始。</p>
<p><img class="aligncenter" src="https://image.woshipm.com/2024/09/11/37870d0e-6ff2-11ef-ab80-00163e142b65.png" /></p>
<h2>一、Basic Reflection的概念</h2>
<p>Basic Reflection可以类比于左右互博。左手是Generator，负责根据用户指令生成结果；右手是Reflector，来审查Generator的生成结果并给出建议。在左右互搏的情况下，Generator生成的结果越来越好，Reflector的检查越来越严格，输出的结果也越来越有效。</p>
<div class="js-star yyp--fancyPost"></div>
<p>下图是Basic Reflection的原理，非常简单。</p>
<ul>
<li>Generator接收来自用户的输入，输出initial response</li>
<li>Reflector接收来自Generator的response，根据开发者设置的要求，给出Reflections，即评语、特征、建议</li>
<li>Generator再根据Reflector给出的反馈进行修改和优化，输出下一轮response</li>
<li>循环往复，直到循环次数</li>
</ul>
<p><img class="aligncenter" src="https://image.woshipm.com/2024/09/11/388aa51c-6ff2-11ef-ab80-00163e142b65.png" /></p>
<h2>二、Basic Reflection的实现过程</h2>
<p>下面，风叔通过实际的源码，详细介绍Basic Reflection模式的实现方法，具体的源代码地址在文章结尾处获取。</p>
<h3>第一步 构建Generator</h3>
<p>在下面的例子中，我们先构建一个能够生成5段话的文章生成器。</p>
<p>首先，我们给Generator约定了Prompt，告诉Generator具体的角色和目标，并且要求如果用户给出建议，需要给出修改后的版本</p>
<p>然后选择LLM模型，并构建Generator</p>
<p>最后要求输出Generator生成的内容</p>
<blockquote><p>from langchain_core.messages import AIMessage, BaseMessage, HumanMessage<br />from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br />from langchain_fireworks import ChatFireworks</p>
<p>prompt = ChatPromptTemplate.from_messages(<br /> &nbsp; &nbsp;[<br /> &nbsp; &nbsp; &nbsp; &nbsp;(<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#8220;system&#8221;,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#8220;You are an essay assistant tasked with writing excellent 5-paragraph essays.&#8221;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#8221; Generate the best essay possible for the user&#8217;s request.&#8221;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#8221; If the user provides critique, respond with a revised version of your previous attempts.&#8221;,<br /> &nbsp; &nbsp; &nbsp; &nbsp;),<br /> &nbsp; &nbsp; &nbsp; &nbsp;MessagesPlaceholder(variable_name=&#8221;messages&#8221;),<br /> &nbsp; &nbsp;]<br /> &nbsp; &nbsp;)<br />llm = ChatFireworks(<br /> &nbsp; &nbsp;model=&#8221;accounts/fireworks/models/mixtral-8x7b-instruct&#8221;,<br /> &nbsp; &nbsp;model_kwargs={&#8220;max_tokens&#8221;: 32768},<br /> &nbsp; &nbsp;)</p>
<p>generate = prompt | llm<br />essay = &#8220;&#8221;<br />request = HumanMessage(<br /> &nbsp; &nbsp;content=&#8221;Write an essay on why the little prince is relevant in modern childhood&#8221;<br /> &nbsp; &nbsp;)</p>
<p>for chunk in generate.stream({&#8220;messages&#8221;: [request]}):<br /> &nbsp; &nbsp;print(chunk.content, end=&#8221;&#8221;)<br /> &nbsp; &nbsp;essay += chunk.content</p></blockquote>
<p> &nbsp; &nbsp;下面是Generator的Initial Response，可以看出Generator虽然按照我们的要求生成了初始回复，但是回复的整体质量还有很大的提升空间。</p>
<blockquote><p>Title: The Relevance of The Little Prince in Modern Childhood</p>
<p>The Little Prince, a novella by Antoine de Saint-Exupéry, has been a childhood favorite for generations. Despite being published over seven decades ago, its timeless themes continue to resonate with modern children, making it highly relevant in contemporary childhood.</p>
<p>Firstly, the story explores the complex nature of human relationships, which is particularly relevant for modern children growing up in an increasingly connected yet impersonal world. Through the little prince&#8217;s encounters with various grown-ups on different planets, the book highlights the importance of genuine connections and understanding. In an age where digital communication often replaces face-to-face interaction, this message is more pertinent than ever. The Little Prince encourages children to look beyond superficial relationships and seek deeper connections, fostering empathy and emotional intelligence.</p>
<p>Secondly, the book deals with the concept of responsibility and self-discovery, elements that are integral to a child&#8217;s growth. The little prince&#8217;s journey is essentially a quest for self-discovery, leading him to realize his responsibility towards his beloved rose. This narrative encourages modern children to embrace their individuality while understanding the significance of their actions. In a society that often overlooks the emotional well-being of children, The Little Prince offers a refreshing perspective on personal growth and responsibility.</p>
<p>Thirdly, the book addresses the challenging theme of loss and bereavement. The little prince&#8217;s departure from his asteroid and his subsequent encounters with the fox and the snake are profound reflections on the inevitability of loss and the importance of cherishing relationships. In a time when children are exposed to various forms of loss, from the death of loved ones to environmental degradation, The Little Prince provides a gentle yet powerful way to understand and cope with these experiences.</p>
<p>However, some critics argue that the book&#8217;s pace and abstract concepts might be challenging for modern children with short attention spans. To address this, a revised version could incorporate more visual elements and interactive activities to engage young readers better. Additionally, supplementary materials explaining the book&#8217;s themes in simpler terms could be provided for parents and educators to use in discussions with children.</p>
<p>In conclusion, The Little Prince remains relevant in modern childhood due to its exploration of human relationships, self-discovery, and loss. These themes, wrapped in a captivating narrative, offer valuable lessons for modern children. While some adaptations may be necessary to cater to the preferences of today&#8217;s children, the essence of the story remains a powerful tool for teaching emotional intelligence, personal growth, and resilience.</p></blockquote>
<h3>第二步 构建Reflector</h3>
<p>针对Generator，我们构建一个专门的Reflector。</p>
<p>同样的，我们要先给Reflector约定Prompt，告诉Reflector“你是一名正在给论文评分的老师。请对用户的论文提出批评和建议，包括长度、深度、风格等要求。”</p>
<p>然后选择LLM模型，并构建Reflector</p>
<blockquote><p>reflection_prompt = ChatPromptTemplate.from_messages(<br /> &nbsp; &nbsp;[<br /> &nbsp; &nbsp; &nbsp; &nbsp;(<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#8220;system&#8221;,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#8220;You are a teacher grading an essay submission. Generate critique and recommendations for the user&#8217;s submission.&#8221;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#8221; Provide detailed recommendations, including requests for length, depth, style, etc.&#8221;,<br /> &nbsp; &nbsp; &nbsp; &nbsp;),<br /> &nbsp; &nbsp; &nbsp; &nbsp;MessagesPlaceholder(variable_name=&#8221;messages&#8221;),<br /> &nbsp; &nbsp;]<br /> &nbsp; &nbsp;)<br />reflect = reflection_prompt | llm</p></blockquote>
<p>下面是针对Generator的Initial Response，Reflector反馈的评语和建议。Reflector给出了B+的评级，并且按照我们的要求，从文章的长度、深度、风格等维度给出了具体的建议和总结。</p>
<blockquote><p>Essay Grade: B+</p>
<p>The essay you submitted provides a clear and well-structured argument about the relevance of The Little Prince in modern childhood. You have demonstrated a strong understanding of the text and its themes, and have effectively applied them to the context of contemporary childhood. However, there are some areas where improvement could be made to enhance the depth, style, and overall flow of your essay.</p>
<p>1. Length: While your essay is well-written and informative, it is relatively brief. Expanding on each point with more detailed analysis and examples would strengthen your argument and demonstrate a more comprehensive understanding of the text. Aim for a minimum of 500 words to allow for a more in-depth exploration of your ideas.</p>
<p>2. Depth: Although you have touched upon the relevance of the novel&#8217;s themes, further analysis is needed to truly establish its significance in modern childhood. For example, when discussing the complex nature of human relationships, delve into how the digital age affects children&#8217;s communication skills, and how The Little Prince addresses this issue. Providing concrete examples from the text and connecting them to real-world scenarios will make your argument more compelling.</p>
<p>3. Style: To engage your readers more effectively, consider varying your sentence structure and length. Using a mix of simple, compound, and complex sentences will improve the flow of your essay and make it more engaging to read. Additionally, watch your tense consistency. Ensure that you maintain the same tense throughout your essay to avoid confusion.</p>
<p>4. Recommendations: While your suggestions for adaptation are a good start, they could be expanded upon to provide more comprehensive recommendations. For example, you may want to discuss different methods of incorporating visual elements and interactive activities, such as illustrations, quizzes, or discussion questions. This will demonstrate that you have thoughtfully considered the needs of modern children and have developed strategies to address these challenges.</p>
<p>5. Conclusion: Your conclusion could benefit from a stronger summarization of your key points and an assertive final statement about the relevance of The Little Prince in modern childhood. Tying all your arguments together in a concise and powerful manner will leave a lasting impression on your readers and solidify your position.</p>
<p>Overall, your essay is well-researched and provides a solid foundation for a compelling argument about the relevance of The Little Prince in modern childhood. With some expansion, deeper analysis, and stylistic improvements, your essay can achieve an even higher level of excellence.</p></blockquote>
<h3>第三步 循环执行</h3>
<p>接下来，我们就可以循环执行这个“生成 &#8211; 检查”的过程，重复规定的次数，或者约定当Generator的生成结果达到多少分时，停止循环。</p>
<p>大家可以看到，在循环过程中，我们也加入了人类的反馈建议，有助于Generator和Reflector学习迭代。</p>
<blockquote><p>for chunk in generate.stream(<br /> &nbsp; &nbsp;{&#8220;messages&#8221;: [request, AIMessage(content=essay), HumanMessage(content=reflection)]}<br /> &nbsp; &nbsp;):<br /> &nbsp; &nbsp;print(chunk.content, end=&#8221;&#8221;)</p></blockquote>
<p> &nbsp; &nbsp;第四步 构建流程图</p>
<p>下面，我们构建流程图，将Generator、Reflector等节点添加进来，循环执行并输出结果。</p>
<blockquote><p>from typing import Annotated, List, Sequence<br />from langgraph.graph import END, StateGraph, START<br />from langgraph.graph.message import add_messages<br />from typing_extensions import TypedDict</p>
<p>class State(TypedDict):<br /> &nbsp; &nbsp;messages: Annotated[list, add_messages]</p>
<p> &nbsp; &nbsp;async def generation_node(state: Sequence[BaseMessage]):<br /> &nbsp; &nbsp;return await generate.ainvoke({&#8220;messages&#8221;: state})</p>
<p> &nbsp; &nbsp;async def reflection_node(messages: Sequence[BaseMessage]) -&gt; List[BaseMessage]:<br /> &nbsp; &nbsp;# Other messages we need to adjust<br /> &nbsp; &nbsp;cls_map = {&#8220;ai&#8221;: HumanMessage, &#8220;human&#8221;: AIMessage}<br /> &nbsp; &nbsp;# First message is the original user request. We hold it the same for all nodes<br /> &nbsp; &nbsp;translated = [messages[0]] + [<br /> &nbsp; &nbsp; &nbsp; &nbsp;cls_map[msg.type](content=msg.content) for msg in messages[1:]<br /> &nbsp; &nbsp;]<br /> &nbsp; &nbsp;res = await reflect.ainvoke({&#8220;messages&#8221;: translated})<br /> &nbsp; &nbsp;# We treat the output of this as human feedback for the generator<br /> &nbsp; &nbsp;return HumanMessage(content=res.content)</p>
<p> &nbsp; &nbsp;builder = StateGraph(State)<br />builder.add_node(&#8220;generate&#8221;, generation_node)<br />builder.add_node(&#8220;reflect&#8221;, reflection_node)<br />builder.add_edge(START, &#8220;generate&#8221;)</p>
<p>def should_continue(state: List[BaseMessage]):<br /> &nbsp; &nbsp;if len(state) &gt; 6:<br /> &nbsp; &nbsp; &nbsp; &nbsp;# End after 3 iterations<br /> &nbsp; &nbsp; &nbsp; &nbsp;return END<br /> &nbsp; &nbsp;return &#8220;reflect&#8221;</p>
<p> &nbsp; &nbsp;builder.add_conditional_edges(&#8220;generate&#8221;, should_continue)<br />builder.add_edge(&#8220;reflect&#8221;, &#8220;generate&#8221;)<br />graph = builder.compile()</p>
<p>async for event in graph.astream(<br /> &nbsp; &nbsp;[<br /> &nbsp; &nbsp; &nbsp; &nbsp;HumanMessage(<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;content=&#8221;Generate an essay on the topicality of The Little Prince and its message in modern life&#8221;<br /> &nbsp; &nbsp; &nbsp; &nbsp;)<br /> &nbsp; &nbsp;],<br /> &nbsp; &nbsp;):<br /> &nbsp; &nbsp;print(event)<br /> &nbsp; &nbsp;print(&#8220;&#8212;&#8220;)</p></blockquote>
<p> &nbsp; &nbsp;至此，Basic Reflection的完整流程就介绍完了，非常简单，相信哪怕是没有AI基础的同学也能看懂。</p>
<h2>三、总结</h2>
<p>Basic Reflection的架构，非常适合于进行相对比较发散的内容生成类工作，比如文章写作、图片生成、代码生成等等。</p>
<p>总体而言，Basic Reflection是一种非常高效的反思类AI Agent设计模式。Basic Reflection 的思路非常朴素，使用成本较低。但是在实际应用中，Basic Reflection也面临着一些缺陷：</p>
<p>对于一些比较复杂的问题，显然需要Generator具备更强大的推理能力</p>
<p>Generator生成的结果可能会过于发散，和我们要求的结果相去甚远</p>
<p>在一些复杂场景下，Generator和Reflector之间的循环次数不太好定义，如果次数太少，生成效果不够理想；如果次数太多，对token的消耗会很大。</p>
<p>我们有两种方法来优化Basic Reflection，一种是边推理边执行的Self Discover模式，一种是增加了强化学习的Reflexion模式。</p>
<div class="article--copyright"><p>本文由人人都是产品经理作者【风叔】，微信公众号：【风叔云】，原创/授权 发布于人人都是产品经理，未经许可，禁止转载。</p>
<p>题图来自Unsplash，基于 CC0 协议。</p>
</div>