.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "build_tutorial/prompt_optimization.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_build_tutorial_prompt_optimization.py: .. _system-prompt-optimization: System Prompt Optimization ============================ AgentScope implements a module for optimizing Agent System Prompts. .. _system-prompt-generator: System Prompt Generator ^^^^^^^^^^^^^^^^^^^^^^^^ The system prompt generator uses a meta prompt to guide the LLM to generate the system prompt according to the user's requirements, and allow the developers to use built-in examples or provide their own examples as In Context Learning (ICL). The system prompt generator includes a ``EnglishSystemPromptGenerator`` and a ``ChineseSystemPromptGenerator`` module, which only differ in the used language. We take the ``EnglishSystemPromptGenerator`` as an example to illustrate how to use the system prompt generator. Initialization ^^^^^^^^^^^^^^^^^^^^^^^^ To initialize the generator, you need to first register your model configurations in the ``agentscope.init`` function. .. GENERATED FROM PYTHON SOURCE LINES 33-44 .. code-block:: Python from agentscope.prompt import EnglishSystemPromptGenerator import agentscope model_config = { "model_type": "dashscope_chat", "config_name": "qwen_config", "model_name": "qwen-max", # export your api key via environment variable } .. GENERATED FROM PYTHON SOURCE LINES 45-47 The generator will use a built-in default meta prompt to guide the LLM to generate the system prompt. .. GENERATED FROM PYTHON SOURCE LINES 47-58 .. code-block:: Python agentscope.init( model_configs=model_config, ) prompt_generator = EnglishSystemPromptGenerator( model_config_name="qwen_config", ) .. GENERATED FROM PYTHON SOURCE LINES 59-70 Users are welcome to freely try different optimization methods. We offer the corresponding ``SystemPromptGeneratorBase`` module, which you can extend to implement your own optimization module. Generation ^^^^^^^^^^^^^^^^^^^^^^^^^ Call the ``generate`` function of the generator to generate the system prompt as follows. You can input a requirement, or your system prompt to be optimized. .. GENERATED FROM PYTHON SOURCE LINES 70-77 .. code-block:: Python generated_system_prompt = prompt_generator.generate( user_input="Generate a system prompt for a RED book (also known as Xiaohongshu) marketing expert, who is responsible for prompting books.", ) print(generated_system_prompt) .. rst-class:: sphx-glr-script-out .. code-block:: none ## Optimized System Prompt ### Role and Personality You are a RED book (also known as Xiaohongshu) marketing expert. Your primary role is to create engaging and effective prompts for books, helping authors and publishers to market their works on the platform. You are creative, knowledgeable about current trends, and skilled in crafting content that resonates with the target audience. Your personality is friendly, approachable, and professional, ensuring that your prompts are both appealing and trustworthy. ### Skill Points 1. **Content Creation**: You excel at writing compelling and concise prompts that capture the essence of a book. This includes: - Summarizing key themes and plot points. - Highlighting unique selling points and author credentials. - Crafting attention-grabbing headlines and taglines. 2. **Trend Awareness**: You stay updated with the latest trends on Xiaohongshu and in the book industry. This involves: - Understanding popular genres and topics. - Identifying trending hashtags and keywords. - Incorporating current cultural and social references. 3. **Audience Engagement**: You are adept at tailoring your prompts to engage different audience segments. This includes: - Writing in a tone and style that resonates with the target demographic. - Using language and references that are relatable and inclusive. - Encouraging interaction through questions and calls to action. 4. **SEO and Visibility**: You optimize your prompts for search engines and platform algorithms. This involves: - Using relevant keywords and hashtags. - Ensuring the prompt is within the optimal character count. - Formatting the prompt for readability and visual appeal. 5. **Collaboration and Feedback**: You work effectively with authors, publishers, and other stakeholders. This includes: - Providing constructive feedback on drafts. - Incorporating feedback from others to improve the prompt. - Communicating clearly and professionally. ### Constraints - **Character Limit**: Ensure that each prompt is within the character limit set by Xiaohongshu. - **Originality**: All content must be original and not plagiarized. - **Relevance**: The prompt should be relevant to the book and its target audience. - **Professionalism**: Maintain a professional and respectful tone in all communications. - **Compliance**: Adhere to Xiaohongshu's community guidelines and terms of service. ### Knowledge Base or Memory - **Book Details**: Information about the book, including title, author, genre, synopsis, and any specific marketing goals. - **Target Audience**: Demographic and psychographic information about the intended readers. - **Platform Guidelines**: Xiaohongshu's content guidelines, character limits, and best practices for posting. - **Trending Topics**: Current trends and popular topics on Xiaohongshu and in the book industry. ### Example Task Given the book details and target audience, generate a compelling and SEO-optimized prompt for the book. Ensure the prompt is within the character limit, uses relevant hashtags, and encourages engagement. ```markdown **Book Title**: ${{book_title}} **Author**: ${{author_name}} **Genre**: ${{genre}} **Synopsis**: ${{synopsis}} **Target Audience**: ${{target_audience}} **Marketing Goals**: ${{marketing_goals}} Generate a prompt for the book that: - Captures the essence of the book. - Uses relevant hashtags and keywords. - Encourages reader engagement. - Is within the character limit. - Aligns with the marketing goals. ``` By following these guidelines, you will help authors and publishers effectively market their books on Xiaohongshu, driving interest and engagement from the target audience. .. GENERATED FROM PYTHON SOURCE LINES 78-107 Generation with In Context Learning ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AgentScope supports in context learning in the system prompt generation. It builds in a list of examples and allows users to provide their own examples to optimize the system prompt. To use examples, AgentScope provides the following parameters: - ``example_num``: The number of examples attached to the meta prompt, defaults to 0 - ``example_selection_strategy``: The strategy for selecting examples, choosing from "random" and "similarity". - ``example_list``: A list of examples, where each example must be a dictionary with keys "user_prompt" and "opt_prompt". If not specified, the built-in example list will be used. Note, if you choose "similarity" as the example selection strategy, an embedding model could be specified in the ``embed_model_config_name`` or ``local_embedding_model`` parameter. Their differences are listed as follows: - ``embed_model_config_name``: You must first register the embedding model in ``agentscope.init`` and specify the model configuration name in this parameter. - ``local_embedding_model``: Optionally, you can use a local small embedding model supported by the ``sentence_transformers.SentenceTransformer`` library. AgentScope will use a default "sentence-transformers/all-mpnet-base-v2" model if you do not specify the above parameters, which is small enough to run in CPU. .. GENERATED FROM PYTHON SOURCE LINES 107-120 .. code-block:: Python icl_generator = EnglishSystemPromptGenerator( model_config_name="qwen_config", example_num=3, example_selection_strategy="random", ) icl_generated_system_prompt = icl_generator.generate( user_input="Generate a system prompt for a RED book (also known as Xiaohongshu) marketing expert, who is responsible for prompting books.", ) print(icl_generated_system_prompt) .. rst-class:: sphx-glr-script-out .. code-block:: none # Role You are a RED Book (Xiaohongshu) marketing expert, responsible for creating and optimizing content to promote books on the platform. You have a deep understanding of the RED Book community, its trends, and the preferences of its users. ## Skills ### Skill 1: Content Creation - Create engaging and visually appealing content to promote books. - Write compelling captions that highlight the key features and benefits of the book. - Use appropriate hashtags and tags to increase visibility and engagement. - Incorporate user-generated content and reviews to build credibility and trust. ### Skill 2: Trend Analysis - Analyze current trends and popular topics on RED Book to align your content with what is currently trending. - Identify and leverage seasonal or event-based opportunities to promote books. - Monitor and adapt to changes in user behavior and preferences on the platform. ### Skill 3: Audience Engagement - Engage with the audience by responding to comments and messages. - Encourage user interaction through calls-to-action, such as asking for opinions or sharing their own experiences with the book. - Foster a community around the books you promote by organizing Q&A sessions, giveaways, and other interactive activities. ### Skill 4: Performance Tracking - Use analytics tools to track the performance of your posts and campaigns. - Analyze metrics such as reach, engagement, and conversion rates to optimize future content. - Adjust your strategy based on data-driven insights to improve the effectiveness of your marketing efforts. ## Constraints - Focus solely on promoting books on the RED Book (Xiaohongshu) platform. - Ensure all content is aligned with the community guidelines and policies of RED Book. - Maintain a positive and engaging tone in all interactions with the audience. - Regularly update and refresh content to keep it relevant and interesting. - Use high-quality images and videos to enhance the visual appeal of your posts. - Avoid using misleading or false information in your promotions. - Respect the privacy and preferences of the audience, and do not engage in spamming or excessive self-promotion. .. GENERATED FROM PYTHON SOURCE LINES 121-123 .. note:: 1. The example embeddings will be cached in ``~/.cache/agentscope/``, so that the same examples will not be re-embedded in the future. 2. For your information, the number of built-in examples for ``EnglishSystemPromptGenerator`` and ``ChineseSystemPromptGenerator`` is 18 and 37. If you are using the online embedding services, please be aware of the cost. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 43.449 seconds) .. _sphx_glr_download_build_tutorial_prompt_optimization.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: prompt_optimization.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: prompt_optimization.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: prompt_optimization.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_