# 02. User-required port-based meta prompt generation agent

## User-required port-based meta prompt generation agent <a href="#id-1" id="id-1"></a>

This tutorial explains how to create a chatbot that helps users create prompts. The chatbot first collects the requirements from the user, then creates a prompt based on this and modifies it according to the user input. The process is divided into two separate states, where LLM determines when to switch states.

The graphical representation of this system can be found below.

**Mainly covered**

* **Gather information** : Define graphs for collecting user requirements
* **Generate Prompt** : Set the status above prompt creation
* **Define the state logic** : Define the state logic of the chatbot
* **Create the graph** : Create graphs and save conversation history
* **Use the graph** : How to use the chatbot created

In this example, we create a chatbot that helps users create prompts.

The chatbot first collects the requirements from the user, then creates a prompt based on this and modifies it according to the user input.

The process is divided into two separate states, where LLM determines when to switch states.

The graphical representation of the system can be found below.

![](https://wikidocs.net/images/page/267817/meta-prompt-generator.png)

### Preferences <a href="#id-2" id="id-2"></a>

```python
# Configuration file for managing API keys as environment variables
from dotenv import load_dotenv

# Load API key information
load_dotenv()
```

```
 True 
```

```python
# Set up LangSmith tracking. https://smith.langchain.com
# !pip install -qU langchain-teddynote
from langchain_teddynote import logging

# Enter a project name.
logging.langsmith("CH17-LangGraph-Use-Cases")
```

```
 Start tracking LangSmith. 
[Project name] 
CH17-LangGraph-Use-Cases 
```

### Collection of ports from users <a href="#id-3" id="id-3"></a>

First, it defines a node that collects user requirements.

During this process, you can ask the user for specific information. All the information you need **Meet** It requires the user to need the information until it becomes.

```python
from typing import List
from langchain_core.messages import SystemMessage
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
from langchain_teddynote.models import get_model_name, LLMs

# System message templates for gathering user requirements
template = """Your job is to get information from a user about what type of prompt template they want to create.

You should get the following information from them:

- What the objective of the prompt is
- What variables will be passed into the prompt template
- Any constraints for what the output should NOT do
- Any requirements that the output MUST adhere to

If you are not able to discern this info, ask them to clarify! Do not attempt to wildly guess.

After you are able to discern all the information, call the relevant tool.

[IMPORTANT] Your conversation should be in Korean. Your generated prompt should be in English."""


# Gets a list of user messages and combines them with system messages and returns them.
def get_messages_info(messages):
    # Combining system messages with existing messages to gather user requirements
    return [SystemMessage(content=template)] + messages


# Data model defining prompt guidelines for LLM
class PromptInstructions(BaseModel):
    """Instructions on how to prompt the LLM."""

    # Goal of the prompt
    objective: str
    # A list of variables to be passed to the prompt template.
    variables: List[str]
    # List of constraints to avoid in output
    constraints: List[str]
    # A list of requirements that the output must follow.
    requirements: List[str]


# Get the latest LLM model name
MODEL_NAME = get_model_name(LLMs.GPT4)
# LLM Initialization
llm = ChatOpenAI(temperature=0, model=MODEL_NAME)
# Binding a PromptInstructions structure
llm_with_tool = llm.bind_tools([PromptInstructions])


# Generate message chains based on state information and call LLM
def info_chain(state):
    # Get message information from the state and combine it with system messages
    messages = get_messages_info(state["messages"])
    # Generate a response by calling LLM
    response = llm_with_tool.invoke(messages)
    # Return the generated response as a list of messages.
    return {"messages": [response]}
```

### Prompt generation <a href="#id-4" id="id-4"></a>

Now set the state to create the prompt.

A separate system message is required for this, and a function that filters all messages before the tool call is also required.

```python
Copy
```

* The last message `tool call` In the case of "prompt creator" ( `prompt` ) Is in a state to respond to.
* The last message `HumanMessage` If not, the user will have to respond next `END` In state.
* The last message `HumanMessage` If it is, before `tool call` If there was `prompt` In state.
* Otherwise, "collect information" ( `info` ) In a state.

Describe the logic that determines the state of the chatbot.

### State logic definition <a href="#id-5" id="id-5"></a>

````python
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage, SystemMessage

# Defining a meta prompt that generates a prompt
META_PROMPT = """Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.

# Guidelines

- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
    - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
    - Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
   - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
    - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
    - JSON should never be wrapped in code blocks (```) unless explicitly requested.

The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")

[Concise instruction describing the task - this should be the first line in the prompt, no section header]

[Additional details as needed.]

[Optional sections with headings or bullet points for detailed steps.]

# Steps [optional]

[optional: a detailed breakdown of the steps necessary to accomplish the task]

# Output Format

[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]

[User given variables should be wrapped in {{brackets}}]

<Question>
{{question}}
</Question>

<Answer>
{{answer}}
</Answer>

# Examples [optional]

[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]

# Notes [optional]

[optional: edge cases, details, and an area to call or repeat out specific important considerations]

# Based on the following requirements, write a good prompt template:

{reqs}
"""


# Function to get message for generating prompt
# Get only messages after tool call
def get_prompt_messages(messages: list):
    # Initialize variables to store tool call information
    tool_call = None
    # Initialize the list to store messages after tool call
    other_msgs = []
    # Iterate through the message list, calling tools and processing other messages.
    for m in messages:
        # Save tool call information when there is a tool call in the AI ​​message
        if isinstance(m, AIMessage) and m.tool_calls:
            tool_call = m.tool_calls[0]["args"]
        # ToolMessage is skipped
        elif isinstance(m, ToolMessage):
            continue
        # Add message to list after tool call
        elif tool_call is not None:
            other_msgs.append(m)
    # Combines system messages and messages after tool calls and returns them.
    return [SystemMessage(content=META_PROMPT.format(reqs=tool_call))] + other_msgs


# Define a prompt generation chain function
def prompt_gen_chain(state):
    # Get prompt message from state
    messages = get_prompt_messages(state["messages"])
    # Generate a response by calling LLM
    response = llm.invoke(messages)
    # Return the generated response as a list of messages.
    return {"messages": [response]}
````

1. **Goal-oriented structure**\
   Meta prompts clearly define the information you want to obtain as a result, and include a step-by-step design process for this.
2. **Adaptive design**\
   Includes an approach to correct or repeatedly optimize the prompt, taking into account the model's answer characteristics, limitations, and strengths.
3. **Prompt engineering**\
   Adjust the model's response in detail, including conditional statements, guides, and role instructions.
4. **Multilayer approach**\
   Adopt a way to gradually refine answers through sub-questions, not just a single question.
5. Note: [OpenAI Meta Prompt Engineering Guide](https://platform.openai.com/docs/guides/prompt-generation?context=text-out)

**Main features**

Meta Prompt **Methodology or strategy to optimize prompt design and creation itself** A concept referring to, used to make more effective and efficient use of the artificial language model (LLM). Beyond simply entering text, **A structured and creative approach needed to induce a model's response in a specific way or to increase the quality of the results.** Includes.

**Definition of Meta Prompt**

The definition of the meta prompt we use here is as follows.

```python
Copyfrom langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import StateGraph, START, END
from langchain_core.messages import ToolMessage
from langgraph.graph.message import add_messages
from typing import Annotated
from typing_extensions import TypedDict


# State Definition
class State(TypedDict):
    messages: Annotated[list, add_messages]


# Initialize MemorySaver to store conversation history in memory
memory = MemorySaver()

# Initialize state graph
workflow = StateGraph(State)

# Add node
workflow.add_node("info", info_chain)
workflow.add_node("prompt", prompt_gen_chain)


# Define a status node to add a tool message
@workflow.add_node
def add_tool_message(state: State):
    return {
        "messages": [
            ToolMessage(
                content="Prompt generated!",
                tool_call_id=state["messages"][-1].tool_calls[0][
                    "id"
                ],  # Get the tool call ID from the state and add it to the message
            )
        ]
    }


# Defining conditional state transitions
workflow.add_conditional_edges("info", get_state, ["add_tool_message", "info", END])

# Edge definition
workflow.add_edge("add_tool_message", "prompt")
workflow.add_edge("prompt", END)
workflow.add_edge(START, "info")

# Compile the graph
graph = workflow.compile(checkpointer=memory)
```

Now you can create a graph. To save conversation history `MemorySaver` Will use

### Graph generation <a href="#id-6" id="id-6"></a>

```python
from langgraph.graph import END


# Defining a state decision function
# Get a list of messages from a state
def get_state(state):
    messages = state["messages"]
    # If the last message is an AIMessage and there is a tool call
    if isinstance(messages[-1], AIMessage) and messages[-1].tool_calls:
        # Returns the status that the tool message should be added to.
        return "add_tool_message"
    # If the last message is not a HumanMessage
    elif not isinstance(messages[-1], HumanMessage):
        # Returns conversation end status
        return END
    # Basically returns the information collection status
    return "info"
```

Visualize the graph.

```
Copyfrom langchain_teddynote.graphs import visualize_graph

visualize_graph(graph)
```

### Execution <a href="#id-7" id="id-7"></a>

Now run the generated graph to generate a prompt.

```python
import uuid
from langchain_teddynote.messages import stream_graph

# Initialize configuration settings (generate unique thread_id)
config = {"configurable": {"thread_id": str(uuid.uuid4())}}

# Infinite loop start
while True:
    try:
        # Get user input
        user = input("User (q/Q to quit): ")
    except:
        pass

    # User Input Output
    print(f"\n[사용자] {user}")

    # End loop when 'q' or 'Q' is entered
    if user in {"q", "Q"}:
        print("AI: See you next time!")
        break

    # Initialize output variables
    output = None

    stream_graph(
        graph,
        {"messages": [HumanMessage(content=user)]},
        config=config,
        node_names=["info", "prompt"],
    )
```

```
 [User] I want to create a RAG prompt. 

================================================== 
🔄 Node: info🔄 
- - - - - - - - - - - - - - - - - - - - - - - - - - - -  
I need some more information to generate RAG prompts. 

One. What is the purpose of the prompt? 
2. What variables will be passed to the prompt template? 
3. What are the constraints you shouldn't do in the output? 
4. What are the requirements that the output must comply with? 

Please provide this information and it will help you create a suitable prompt. 
[User] The purpose of the prompt is to create a document (PDF) based RAG prompt. The variable is question, context 2. Output does not include abusive, non-slang, and sexual harassment remarks. 

================================================== 
🔄 Node: info🔄 
- - - - - - - - - - - - - - - - - - - - - - - - - - - -  
good! I would like to check one more. 

What are the requirements that must be followed in the output? For example, please let me know if there is a specific format or length limit. 
[User] Please make the output as concise as possible. Please answer in Korean. And, be sure to include the source. 

================================================== 
🔄 Node: info🔄 
- - - - - - - - - - - - - - - - - - - - - - - - - - - -  

================================================== 
🔄 Node: prompt🔄 
- - - - - - - - - - - - - - - - - - - - - - - - - - - -  
Create a document (PDF) based on a Retrieval-Augmented Generation (RAG) prompt. 

The document should answer the provided question using the given context. Ensure that the response is concise and includes relevant sources. Avoid any profanity, vulgar language, or sexual harassment remarks. 

# Steps 

One. Analyze the {context} provided to extract relevant information. 
2. Formulate a clear and concise answer to the {question} based on the extracted information. 
3. Cite all sources used in the response to ensure credibility. 

# Output Format 

The output should be be structured as follows: 


{question} 



{answer} 


Include a list of sources at the end of the document. 

# Examples 

**Example 1:** 


What are the benefits of regular exercise? 



Regular exercise improves physical health, enhances mental well-being, and increases longevity. It helps in weight management, reduces the risk of chronic disease, and boosts mood through the release of endorphins. 


Sources: 
One. Healthline. (2022). Benefits of Exercise. 
2. Mayo Clinic. (2023). Exercise: 7 benefits of regular physical activity. 

**Example 2:** 


How does climate change effect biodiversity? 



Climate change leads to habitat loss, altered ecosystems, and increased extension rates among species. It disrupts migration patterns and breeding seasons, thatening biodiversity globally. 


Sources: 
One. IPCC. (2021). Climate Change and Biodiversity. 
2. WWF. (2022). The Impact of Climate Change on Biodiversity. 

# Notes 

Ensure that the answer is as concise as possible while still provisioning a comprehensionive response. Always include sources to back up the information provided. 
[User] q 
AI: See you again next time! 
```
