---
schema_version: "1"
id: 2ae6d3fa2c1faf32423ba22a7c12fe61f08c1694af0f3af9e831825c46d709ed
title: An Agentforce Guide to Context Engineering
collection: admin
version: current
locale: en-us
portal_url: https://docs.salesforce.com/admin/current/en-us/ai/264-0-0/agent_context_engineering.md
canonical_url: https://help.salesforce.com/s/articleView?id=ai.agent_context_engineering.htm&release=264.0.0&type=5
source_site: help.salesforce.com
content_type: documentation
content_hash: d3e257371817baf5b1d027edcdbd526d4e12643da784f5f4b5e43cd267e544d6
description: Context engineering is the art and science of giving your AI agent the right information, tools, and instructions to achieve its goals.
products:
  - Agentforce
  - Cross Cloud
release: "264"
---
# An Agentforce Guide to Context Engineering

Context engineering is the art and science of giving your AI agent the right information, tools, and instructions to achieve its goals.

While prompt engineering focuses on direct instructions and RAG (Retrieval Augmented Generation) focuses on retrieving the right content, context engineering encompasses the full perspective of everything available to your model.

**Sample Context Components**

![Sample Context Components](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/generative_ai/images/generative_ai_context_engineering.png)

Let's highlight a few key components of the context.

- **Prompts and Instructions**: The context includes the instructions to the agent, such as the instructions found in each [subagent](https://help.salesforce.com/s/articleView?id=ai.agent_topics.htm&release=264.0.0&type=5 "A subagent is a job an agent can do. Learn about the parts of a subagent and how to use them to define an agent’s logic, reasoning, and conversational capabilities.") and the user's prompts.
- **Actions and Tools**: The capabilities your agent can use also affect the context, such as running [flows](https://help.salesforce.com/s/articleView?id=platform.flow.htm&language=en_US), calling [Apex](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dev_guide.htm) actions, or using [prompt templates](https://help.salesforce.com/s/articleView?id=ai.prompt_builder_intro.htm&release=264.0.0&type=5 "Use Prompt Builder to build, customize, and manage AI prompt templates that incorporate your CRM data to power generative AI features and Agentforce agents.").
- **Data Inputs**: The context includes relevant information that your agent obtains from structured and unstructured sources, including CRM data, [Data 360](https://help.salesforce.com/s/articleView?id=data.c360_a_data_cloud.htm&language=en_US), [knowledge articles](https://help.salesforce.com/s/articleView?id=service.knowledge_whatis.htm&language=en_US), uploaded documents, [Slack](https://slack.com/help/categories/360000049043), and other data sources.
- **Memory**: Both short-term (current conversation) and long-term (past interactions) memory can be part of the context.

The goal of context engineering is to optimize and tune this context to give the model the best chance at solving the problem. Getting context engineering right helps you avoid common AI agent problems like:

- **Context Clash**: Conflicting instructions, which can lead to unexpected performance or even errors.
- **Context Confusion**: Too much irrelevant content or too many unnecessary tools, which can cause your agent to behave inconsistently and increase agent latency.
- **Context Poisoning**: Incorrect or outdated information, which can affect users’ trust and adoption of your agent.

Any of these issues can reduce the accuracy and effectiveness of your agents. It's critical to give your AI model the right information in the right way to get the right answers.

Now let's discuss the steps to build reliable and effective Agentforce solutions by using some context engineering best practices.

1. **Define Clear Objectives**. Clearly state what your Agentforce agent should achieve. This step can help solidify your decisions across the rest of the process.
2. **Limit, Filter, and Route Subagents Effectively**. Optimize and limit [subagents](https://help.salesforce.com/s/articleView?id=ai.agent_topics.htm&release=264.0.0&type=5 "A subagent is a job an agent can do. Learn about the parts of a subagent and how to use them to define an agent’s logic, reasoning, and conversational capabilities.") and [actions](https://help.salesforce.com/s/articleView?id=ai.copilot_actions.htm&release=264.0.0&type=5 "Actions are how agents get things done. Agents include a library of actions, which are the tools an agent can use to do its job. For example, if a user asks an agent for help with writing an email, the agent first selects a subagent, then it launches an action that drafts and revises the email and grounds it in relevant Salesforce data.") to the essential jobs and tools needed for your agent. After you have the right list of subagents, use subagent classification effectively so that the agent is routed to the right subagent for the job.
    - **Limit Subagents**. Assign only the most essential subagents and actions to your agent. Add subagents gradually as needed.
    - **Filter Subagents**. Use filters to control access to subagents (using the Agent Router in Canvas view or the `start_agent` subagent in Script view).
        
        This screenshot demonstrates subagent filtering in Canvas view. These instructions use variables to filter out subagents that aren't applicable.
        
        ![Sample Subagent Routing](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/generative_ai/images/agent_topics_routing_filter.png)
        
        And here’s what the same filtering looks like in Agent Script.
        
        ```
        start_agent agent_router:
            description: "Welcome the user and determine the appropriate subagent based on user input"
            reasoning:
                instructions: |
                    You are an agent router for this assistant. Welcome the guest
                    and analyze their input to determine the most appropriate subagent 
                    to handle their request.
                actions:
                    go_to_identity: @utils.transition to @subagent.Identity_Verification
                        description: "Verifies user identity"
                        available when @variables.verified == False
                    go_to_order: @utils.transition to @subagent.Order_Management
                        description: "Handles order lookup, refunds, and order updates."
                        available when @variables.verified == True
                    go_to_faq: @utils.transition to @subagent.General_FAQ
                        description: "Handles various frequently asked questions."
                        available when @variables.verified == True
                    go_to_escalation: @utils.transition to @subagent.Escalation
                        description: "Handles escalation to a human rep."
                        available when @variables.verified == True and @variables.is_business_hours == True
        ```
        
        See [Subagent Classification and Routing](https://help.salesforce.com/s/articleView?id=ai.agent_topics_routing.htm&release=264.0.0&type=5 "Learn more about the Agent Router and how to customize it to control how your agent selects subagents in a conversation.").
    - **Route Subagent with Logic**. Use explicit references to subagents to deterministically route from one subagent to another, under certain conditions.
        
        This example illustrates how you can use logic instructions to strategically route from one subagent to another.
        
        ![Sample Subagent Routing](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/generative_ai/images/agent_topics_routing_logic.png)
        
        ```
        start_agent agent_router:
            reasoning:
                instructions:->
                    if @variables.approval_required:
                        transition to @subagent.approval_workflow
                    else:
                        transition to @subagent.management_workflow
        ```
        
        See [How Subagent Instructions are Resolved to Build a Prompt](https://help.salesforce.com/s/articleView?id=ai.agent_topics_instructions_resolve.htm&release=264.0.0&type=5 "Learn about how an agent executes programmatic expressions in a subagent’s reasoning instructions to prepare for reasoning.") in Salesforce Help and [Reasoning Instructions](https://developer.salesforce.com/docs/ai/agentforce/guide/ascript-ref-instructions.html) in the Agent Script Developer Guide.
3. **Review Your Actions**. Make sure that each subagent has relevant and effective actions to help complete the job.
    
    Keep in mind that some actions ([flows](https://help.salesforce.com/s/articleView?id=platform.flow.htm&language=en_US), [Apex](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dev_guide.htm) methods, APIs) are more deterministic, whereas actions that use AI models are more probabilistic ([prompt templates](https://help.salesforce.com/s/articleView?id=ai.prompt_builder_intro.htm&release=264.0.0&type=5 "Use Prompt Builder to build, customize, and manage AI prompt templates that incorporate your CRM data to power generative AI features and Agentforce agents.")). See [Agent Actions](https://help.salesforce.com/s/articleView?id=ai.copilot_actions.htm&release=264.0.0&type=5 "Actions are how agents get things done. Agents include a library of actions, which are the tools an agent can use to do its job. For example, if a user asks an agent for help with writing an email, the agent first selects a subagent, then it launches an action that drafts and revises the email and grounds it in relevant Salesforce data.").
    
    You should also think about how and when you want to use an action. For tips on how to do this, see **Balance Probabilistic and Deterministic Behavior** in the next step.
4. **Tune Your Subagent Instructions**. Whether you're [building agents in Canvas view](https://help.salesforce.com/s/articleView?id=ai.agent_canvas.htm&release=264.0.0&type=5 "Get to know the features of Agentforce Builder’s Canvas view that help you build powerful and reliable agents with Agent Script.") or [building them directly with Agent Script](https://developer.salesforce.com/docs/ai/agentforce/guide/agent-script.html), one of the most powerful ways to optimize the context is from your subagents' reasoning instructions. There are several aspects to these instructions that are critical for the context.
    - **Review the Runtime Flow**. Before making too many changes to your instructions, ensure that you understand the runtime behavior of an agent so you know which instructions get included in the context. See [How Agents Work](https://help.salesforce.com/s/articleView?id=ai.agent_builder_reasoning_engine.htm&release=264.0.0&type=5 "Follow the path of a user message through the Atlas reasoning engine to learn how Agentforce agents reason, take action, and generate responses.") and [How Subagent Instructions are Resolved to Build a Prompt](https://help.salesforce.com/s/articleView?id=ai.agent_topics_instructions_resolve.htm&release=264.0.0&type=5 "Learn about how an agent executes programmatic expressions in a subagent’s reasoning instructions to prepare for reasoning."). Developers can also refer to [Flow of Control](https://developer.salesforce.com/docs/ai/agentforce/guide/ascript-flow.html) in the Agent Script Developer Guide.
    - **Use Variables to Store Data**. Specify relevant data in variables so that you can use them directly in your instructions.
        
        This screenshot shows a variable definition in Canvas view.
        
        ![Agent variable](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/generative_ai/images/agent_variables_definition.png)
        
        And this code sample shows the same variable in Script view.
        
        ```
        user_name: mutable string = ""
            description: "The name of the user"
            label: "Name"
            visibility: "External"      
        ```
        
        There are several ways to effectively use variables to perform actions. This example demonstrates how to use a variable to filter an action.
        
        ![Agent variable with action filter](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/generative_ai/images/agent_variables_filter.png)
        
        ```
        get_order_details: @actions.GetOrderByOrderNumber
            available when @variables.verified == True 
        ```
        
        And this example demonstrates how to use variables for action inputs and outputs.
        
        ![Agent variables with action inputs and outputs](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/generative_ai/images/agent_variables_action.png)
        
        ```
        run @actions.GetOrderByOrderNumber
            with order_number = @variables.order_number
            set @variables.order_details = @outputs.orderDetails
        ```
        
        You can use variables throughout your agent definition. See [Variables](https://help.salesforce.com/s/articleView?id=ai.agent_builder_variables.htm&release=264.0.0&type=5 "To improve security and ensure consistent agent behavior, use variables throughout your agent’s reasoning and interactions, such as in filters, instructions, and logical expressions.").
    - **Balance Probabilistic and Deterministic Behavior**. Your subagent instructions include both logic-based instructions and prompt-based instructions. Take advantage of the logic in your instructions for critical business workflows to increase predictable, deterministic behavior. For example, before the prompt-based instructions run, you can check the loyalty tier for a user, use conditional logic to determine whether to thank a user for being a gold tier member, use a variable to customize the prompt, run an action to send an email. You can then focus the natural language prompt on what an AI model does best, without overloading the model’s context with unnecessary and unpredictable logic instructions.
        
        This sample demonstrates how to use logic-based instructions. In these instructions, we check a variable to see if the customer is ready to book a hotel. If so, we get account information using variables for the action inputs and outputs. We then run another action to get hotel info.
        
        ![Logic instructions](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/generative_ai/images/agent_context_eng_logic.png)
        
        ```
        if @variables.ready_to_book:
            run @actions.get_account_info
                with account_id = @variables.account_id
                set @variables.hotel_code = @outputs.hotel_code
        run @actions.get_hotel_info
            with hotel_code = @variables.hotel_code
            set @variables.hotel_info = @outputs.hotel_info
        ```
        
        See [How Subagent Instructions are Resolved to Build a Prompt](https://help.salesforce.com/s/articleView?id=ai.agent_topics_instructions_resolve.htm&release=264.0.0&type=5 "Learn about how an agent executes programmatic expressions in a subagent’s reasoning instructions to prepare for reasoning.") in Salesforce Help and [Reasoning Instructions](https://developer.salesforce.com/docs/ai/agentforce/guide/ascript-ref-instructions.html) in the Agent Script Developer Guide.
    - **Reference Resources Directly**. Whether you're building agents in Canvas view or Script view, you can directly reference subagents, actions, and variables in your instructions. This feature takes the ambiguity out of your instructions because you can specifically "@ mention" resources.
        
        This sample illustrates some of the ways to reference resources in your instructions.
        
        ![Using resources](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/generative_ai/images/agent_canvas_resources.png)
        
        ```
        instructions: |
            Refer to the user by name @variables.member_name.
            Show their current order summary: @variables.order_summary 
            when conversation starts or if requested.
            If they want past order info, ask for Order ID or Restaurant Name 
            and use @actions.lookup_order.
            If they ask for a service agent or seem upset, use @actions.go_to_escalation.
            If they want to make a return, confirm Order ID and use @actions.create_return.
            If returns are not eligible, explain politely.
        ```
        
        See [Building Agents in Canvas View](https://help.salesforce.com/s/articleView?id=ai.agent_canvas.htm&release=264.0.0&type=5 "Get to know the features of Agentforce Builder’s Canvas view that help you build powerful and reliable agents with Agent Script.") or [Get Started with Agent Script](https://developer.salesforce.com/docs/ai/agentforce/guide/agent-script.html).
5. **Use Accurate, Relevant Data**. Ensure that your inputs are based on the best possible information.
    - **Structured data,** such as CRM data, [Data 360](https://help.salesforce.com/s/articleView?id=data.c360_a_data_cloud.htm&language=en_US) data, external data, and other sources, must be correct, up to date, and relevant to the decision or task at hand. See [Strategies for Data Quality](https://trailhead.salesforce.com/content/learn/modules/data_quality) in Trailhead.
    - **Unstructured data**, such as data libraries and other input obtained with [RAG](https://help.salesforce.com/s/articleView?id=ai.generative_ai_rag.htm&release=264.0.0&type=5 "Use Retrieval Augmented Generation (RAG) in Data 360 to improve large language model (LLM) responses for agents and users. RAG is a framework for grounding prompts with relevant, accurate knowledge from unstructured data sources."), must be accurate and directly relevant to user requests. Successful RAG inputs start with a knowledge store of well-curated, high-quality content that’s accurate, complete, current, organized, and consistent. Other considerations include: search strategy ([hybrid](https://help.salesforce.com/s/articleView?id=data.c360_a_hybridsearch_index.htm&language=en_US) or [vector](https://help.salesforce.com/s/articleView?id=data.c360_a_search_index_vector_index.htm&language=en_US) search), content [parsing and pre-processing](https://help.salesforce.com/s/articleView?id=data.c360_a_llm_parsing_preprocessing.htm&language=en_US), [search index optimization](https://help.salesforce.com/s/articleView?id=data.c360_a_search_index_enriched_index.htm&language=en_US), a well-tuned [chunking strategy](https://help.salesforce.com/s/articleView?id=data.c360_a_search_index_supported_chunking_strategies.htm&language=en_US), and using [knowledge/RAG quality data and metrics](https://help.salesforce.com/s/articleView?id=ai.generative_ai_monitor_retrieval.htm&language=en_US) to identify areas to improve.
6. **Ensure Consistency**. Eliminate contradictions across [prompts](https://help.salesforce.com/s/articleView?id=ai.prompt_builder_intro.htm&release=264.0.0&type=5 "Use Prompt Builder to build, customize, and manage AI prompt templates that incorporate your CRM data to power generative AI features and Agentforce agents."), [subagents](https://help.salesforce.com/s/articleView?id=ai.copilot_topics.htm&release=264.0.0&type=5 "A subagent is a particular job an agent can do and an essential element of an agent’s reasoning. A subagent contains actions, which are the tools available for the job, and instructions, which tell the agent how to make decisions. Collectively, the subagents assigned to your agent define the capabilities your agent can handle. Salesforce provides a library of standard subagents for common use cases, and you can create custom subagents to meet your users’ specific business needs."), [actions](https://help.salesforce.com/s/articleView?id=ai.copilot_actions.htm&release=264.0.0&type=5 "Actions are how agents get things done. Agents include a library of actions, which are the tools an agent can use to do its job. For example, if a user asks an agent for help with writing an email, the agent first selects a subagent, then it launches an action that drafts and revises the email and grounds it in relevant Salesforce data."), [RAG](https://help.salesforce.com/s/articleView?id=ai.generative_ai_rag.htm&release=264.0.0&type=5 "Use Retrieval Augmented Generation (RAG) in Data 360 to improve large language model (LLM) responses for agents and users. RAG is a framework for grounding prompts with relevant, accurate knowledge from unstructured data sources.") data, instructions, and Salesforce configuration.
7. **Test, Iterate, Refine**. [Preview your agent in Agentforce Builder](https://help.salesforce.com/s/articleView?id=ai.agent_preview_and_test.htm&release=264.0.0&type=5 "Manual testing, like you do in Agentforce Builder, is the starting point for validating your agent’s performance. It offers a detailed, step-by-step evaluation of your agent's interactions and utterances and is especially effective for confirming configurations and exploring how the agent responds to different inputs. Throughout the agent lifecycle, plan to revisit manual testing in Agentforce Builder, especially after making changes to your agent."). Build tests with [Agentforce Testing Center](https://help.salesforce.com/s/articleView?id=ai.agent_testing_center.htm&release=264.0.0&type=5 "Build confidence in your AI agents and deliver seamless, effective interactions with thorough testing. Easily generate custom test scenarios and leverage our expert evaluation tools to assess response accuracy, conversation quality, subagent recognition, action execution, and knowledge retrieval. Identify issues early and fine-tune your agent’s behavior with precision.") and [monitor your agents](https://help.salesforce.com/s/articleView?id=ai.agent_parent_monitor.htm&release=264.0.0&type=5 "When you review and update your agentic solution, it has a higher chance of success. Review Agentforce analytics to report on key indicators such as performance, usage, quality, trust, cost, and ROI.") with analytics. Use feedback from conversation transcripts to refine your context. Be sure to re-test your agents when any aspect of your solution changes, such as a model update.

By carefully managing your agent's context, you can build reliable and effective AI solutions with Agentforce.

#### See Also

- [How Agents Work](https://help.salesforce.com/s/articleView?id=ai.agent_builder_reasoning_engine.htm&release=264.0.0&type=5 "Follow the path of a user message through the Atlas reasoning engine to learn how Agentforce agents reason, take action, and generate responses.")
- [_Agentforce Developer Guide_: Get Started with Agent Script](https://developer.salesforce.com/docs/ai/agentforce/guide/agent-script.html)
- [_Trailhead_: Prompt Engineering Techniques](https://trailhead.salesforce.com/content/learn/modules/prompt-engineering-techniques)
- [_Trailhead_: Agentforce: Agent Planning](https://trailhead.salesforce.com/content/learn/modules/agentforce-agent-planning)
- [_Trailhead_: Unstructured Data in Data 360](https://trailhead.salesforce.com/content/learn/projects/unstructured-data-in-data-cloud)
- [_Trailhead_: AI Strategy](https://trailhead.salesforce.com/content/learn/modules/ai-strategy)