VOOZH about

URL: https://thenewstack.io/enhancing-ai-agents-adding-instructions-tasks-and-memory/

⇱ Enhancing AI Agents: Adding Instructions, Tasks and Memory - The New Stack


TNS
SUBSCRIBE
Join our community of software engineering leaders and aspirational developers. Always stay in-the-know by getting the most important news and exclusive content delivered fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter in the past. Click the button below to open the re-subscribe form in a new tab. When you're done, simply close that tab and continue with this form to complete your subscription.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!

We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.

What’s next?

Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.

Follow TNS on your favorite social media networks.

Become a TNS follower on LinkedIn.

Check out the latest featured and trending stories while you wait for your first TNS newsletter.

PREV
1 of 2
NEXT
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
Thanks for your opinion! Subscribe below to get the final results, published exclusively in our TNS Update newsletter:
NEW! Try Stackie AI
From clobbered drafts to real-time sync
Apr 14th 2026 10:00am, by David Moore
TypeScript 6.0 RC arrives as a bridge to a faster future
Mar 14th 2026 9:00am, by Darryl K. Taft
Mastra empowers web devs to build AI agents in TypeScript
Jan 28th 2026 11:00am, by Loraine Lawson
2024-11-17 06:00:30
Enhancing AI Agents: Adding Instructions, Tasks and Memory
tutorial,
AI / AI Engineering / Large Language Models

Enhancing AI Agents: Adding Instructions, Tasks and Memory

We show you three crucial enhancements to make your AI agents more sophisticated and effective: instructions, tasks, and conversation memory.
Nov 17th, 2024 6:00am by Janakiram MSV
👁 Featued image for: Enhancing AI Agents: Adding Instructions, Tasks and Memory
Image via Unsplash+. 

In our previous article on AI agents, we explored how to create a basic AI agent with a persona using system prompts. Now, we’ll delve into three crucial enhancements that make our agents more sophisticated and effective: instructions, tasks, and conversation memory.

Understanding Instructions vs. Persona

While a persona defines an agent’s core traits and role (like being a financial advisor), instructions provide specific guidelines for how the agent should operate. Think of the persona as like an employee’s job title and basic qualifications, while instructions are like the detailed operational manual they follow.

Let’s look at how instructions are implemented in our enhanced agent class:

@property
def instruction(self) -> str:
 return self._instruction

@instruction.setter
def instruction(self, value: str):
 self._instruction = value
 # Reset conversation history when instruction changes
 self._conversation_history = []

The separation between persona and instruction allows for more flexible and precise control over the agent’s behavior. For example, a financial advisor agent might have:

  • Persona: Core identity as a financial expert.
  • Instructions: Specific guidelines about never recommending individual stocks, always including disclaimers, etc.

Understanding Tasks

While personas define the role and instructions provide operational guidelines, tasks represent the specific queries or actions requested of the agent.

 @property
 def task(self) -> str:
 return self._task

 @task.setter
 def task(self, value: str):
 self._task = value

In our implementation, tasks are handled distinctly from instructions, allowing for clearer separation of concerns:

  • Instructions: Long-term guidelines that persist across conversations.
  • Tasks: Immediate requests that need to be addressed.

Tasks work together with instructions to form the complete user-side context in the prompt structure. Here’s how they combine in the message chain:

 def _build_messages(self) -> List[Dict[str, str]]:
 """Build the messages list for the API call including system, instruction and history."""
 messages = [{"role": "system", "content": self.persona}]
 
 if self.instruction:
 messages.append({"role": "user", "content": f"Global Instruction: {self.instruction}"})
 
 # Add conversation history
 messages.extend(self.history)
 
 # Add current task if exists
 if self.task:
 messages.append({"role": "user", "content": f"Current Task: {self.task}"})
 
 return messages

This structure ensures that:

  • Instructions provide the operational framework.
  • Tasks represent the immediate objective.
  • The agent maintains awareness of both the general guidelines and specific requests.

Task Processing Flow

When a task is executed, the following process takes place:

  • The agent first considers its persona (system role).
  • The agent then applies any global instructions.
  • Finally, it processes the specific task.
  • The response is stored in the conversation history.

This layered approach allows the agent to:

  • Maintain its professional identity (persona).
  • Follow consistent guidelines (instructions).
  • Address specific needs (tasks).
  • Build context over time (memory).

When to Use Instructions vs. Tasks

Understanding the distinction between instructions and tasks is fundamental to designing effective AI agents. Instructions serve as the foundational framework that guides an agent’s behavior across all interactions. Think of instructions as the operating manual for the agent — they define broad behavioral guidelines, establish persistent rules and boundaries, and set methodologies for handling various situations. Like a company’s standard operating procedures, instructions remain consistent across multiple interactions, ensuring the agent maintains reliable and has predictable behavior patterns.

While instructions provide the overarching framework, tasks are the practical implementation of that framework in response to specific user requests.

Tasks, on the other hand, represent the specific actions an agent needs to perform at any given moment. They are the concrete, immediate objectives that change based on user needs and requirements. While instructions provide the overarching framework, tasks are the practical implementation of that framework in response to specific user requests. Tasks must always operate within the boundaries set by the instructions, much like how an employee performs specific assignments while adhering to company policies.

Building Conversation Memory

One of the most significant enhancements is the addition of conversation memory. This allows our agent to maintain context throughout an interaction, much like how a human professional would remember previous parts of a conversation with a client.

The implementation uses a history property to track the conversation history:

 @property
 def history(self) -> List[Dict[str, str]]:
 return self._history

The history, which acts as a short-term memory system, serves several purposes:

  • Contextual Understanding: The agent can reference previous interactions.
  • Consistency: Responses remain coherent across multiple exchanges.
  • Learning: The agent can build upon previous discussions.

Constructing Message Chains

The enhanced agent uses a sophisticated message-building system that combines persona, instructions, and conversation history.

 def execute(self, task: str = None) -> str:
 """
 Execute the agent with the given task or use existing task if none provided.
 Updates conversation history with the interaction.
 """
 if task:
 self.task = task

 if not self._api_key:
 return "API key not found. Please set the OPENAI_API_KEY environment variable."

 client = OpenAI(api_key=self._api_key)
 messages = self._build_messages()

 try:
 response = client.chat.completions.create(
 model=self._model,
 messages=messages
 )
 
 # Extract response content
 response_content = response.choices[0].message.content
 
 # Update history with the interaction
 if self.task:
 self._history.append({"role": "user", "content": self.task})
 self._history.append({"role": "assistant", "content": response_content})
 
 # Clear current task after execution
 self._task = ""
 
 return response_content
 except Exception as e:
 return f"An error occurred: {str(e)}"

This structured approach ensures that:

  • The persona remains the foundational context.
  • Instructions are clearly acknowledged.
  • Previous conversations provide additional context.
  • The current task is properly framed within the larger context.

Practical Implementation

Let’s look at a practical example using a financial advisor agent:

# Create a financial advisor agent
financial_advisor = Agent("FinancialAdvisorBot")

# Set the persona (core traits and role)
financial_advisor.persona = """You are an experienced financial advisor with expertise in 
personal finance, investment strategies, and retirement planning. Always maintain a 
professional and ethical approach to financial advice."""

# Set the global instruction (broader guidelines)
financial_advisor.instruction = """When providing financial advice:
1. Always emphasize the importance of individual circumstances and risk tolerance
2. Never recommend specific stocks or make promises about returns
3. Include disclaimers about consulting licensed professionals when appropriate
4. Break down complex concepts into simple, actionable steps
5. Consider both short-term and long-term implications in your advice"""

The agent now maintains context across multiple interactions while following specific guidelines:

task1 = "What are some key considerations for planning retirement in your 30s?"
response1 = financial_advisor.execute(task1)

task2 = "Based on those retirement considerations, what should my monthly savings target be?"
response2 = financial_advisor.execute(task2)

In this example, the second response would take into account the context from the first interaction, providing more relevant and connected advice.

The entire source code for the framework is available in a GitHub repository.

Benefits of Enhanced Agents

These enhancements bring several key advantages:

  • Improved Consistency: The combination of persona and instructions ensures that responses are consistently aligned with the agent’s role and guidelines.
  • Better Context Management: Conversation memory allows for more natural and coherent interactions across multiple exchanges.
  • Flexible Behavior Control: Separating a persona from instructions makes it easier to modify how the agent operates without changing its core identity.
  • Enhanced User Experience: Users receive more contextually appropriate responses that build upon previous interactions.

Limitations and Next Steps

These enhancements represent a significant step forward in creating more sophisticated AI agents. However, there’s still room for further improvements, such as:

  • Long-term memory storage and retrieval;
  • Task-specific instruction sets;
  • Dynamic persona adaptation based on user needs and
  • Enhanced error handling and edge case management.

By continuing to refine and enhance these components, we can create AI agents that are increasingly capable of handling complex, multi-step interactions while maintaining consistency and contextual awareness.

The combination of persona, instructions, and memory brings us closer to creating AI agents that can truly serve as effective digital assistants across a wide range of professional domains.

In the next part of this series, we will add reasoning to agents based on proven prompt engineering techniques. Stay tuned!

TRENDING STORIES
Janakiram MSV (Jani) is a practicing architect, research analyst, and advisor to Silicon Valley startups. He focuses on the convergence of modern infrastructure powered by cloud-native technology and machine intelligence driven by generative AI. Before becoming an entrepreneur, he spent...
Read more from Janakiram MSV
SHARE THIS STORY
TRENDING STORIES
TNS owner Insight Partners is an investor in: Persona, OpenAI.
SHARE THIS STORY
TRENDING STORIES
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.