Introduction & Lesson Overview

Welcome back! In the previous lesson, you learned the basics of the OpenAI Agents SDK in TypeScript. You discovered how agents differ from simple chat models, explored the agent loop, and practiced running agents. This foundation is essential, as it allows you to build agents that can reason, plan, and act in multiple steps using modern TypeScript code.

In this lesson, we'll take a closer look at what happens after you run an agent. Specifically, you'll learn how to interpret the results returned by the agent, understand the structure of the result object, and see how to use these results to chain agents together. By the end of this lesson, you'll be able to extract key information from an agent's run and use it to build more complex, multi-step workflows — such as having one agent generate a recipe and another agent write a blog post about it. This knowledge will prepare you for the hands-on practice exercises that follow.

Understanding The Result Object

When you run an agent using the OpenAI Agents SDK for TypeScript, the result is not just a simple string or message. Instead, the SDK returns a result object that contains detailed information about the agent's execution. This object is your window into what happened during the agent's run.

The most important properties of the result object are:

  • input: The original input you provided to the agent.
  • newItems: An array of events or actions that occurred during the run, such as tool calls, reasoning steps, or messages.
  • finalOutput: The last response produced by the agent. This is usually what you want to show to the user.
  • lastAgent: The last agent that was executed, which is useful if your workflow involves multiple agents.
  • history: An array representing the full conversation history, including all messages exchanged. This is especially useful for chaining agents or continuing a conversation, as it provides all the necessary context in the correct format.

These properties help you understand not just the answer, but also how the agent arrived at it. This is especially important when you want to chain agents together or keep track of the conversation's context.

Example: Creating a Recipe Agent

Before we look at the different properties of the result object, let's quickly revisit how you might define and run an agent that generates recipes. Suppose you want an agent that acts as a creative chef and provides detailed smoothie recipes. You can set this up as follows:

import { Agent, run } from '@openai/agents';

// Define a Recipe Chef agent
const recipeAgent = new Agent({
  name: 'Recipe Chef',
  instructions:
    'You are a creative chef. Provide a detailed healthy smoothie recipe with a title, a list of ingredients, ' +
    'and step-by-step instructions. Do not include extra commentary. Output only the recipe text.',
  model: 'o4-mini'
});

const result = await run(
  recipeAgent,
  'Give me a recipe for a healthy smoothie.'
);

// Process result...

In this example, the recipeAgent is set up with clear instructions and a model. When you run the agent with a prompt like "Give me a recipe for a healthy smoothie.", you receive a result object. Next, let's look at each part of the result object in more detail, using simple code snippets to illustrate how they work.

The input Property

The input property holds the original prompt or message you sent to the agent. This is the starting point for the agent's reasoning and response. For example, if you ask for a smoothie recipe, the input will simply be your request:

console.log(result.input);

When you print this property, you'll see exactly what was provided to the agent at the beginning of its run:

Give me a recipe for a healthy smoothie.

This is useful for logging, debugging, or when you want to confirm exactly what was asked of the agent.

The newItems Property

The newItems property is an array of all the events or actions that occurred during the agent's run. This includes messages generated by the agent, tool calls, and any intermediate reasoning steps. By inspecting newItems, you can see the agent's process and how it arrived at its answer.

console.log(JSON.stringify(result.newItems, null, 2));

The output reveals the internal steps and messages produced by the agent. For example:

[
  {
    "type": "reasoning_item",
    "rawItem": {
      "type": "reasoning",
      "id": "rs_686b959d21d8819ba2b833b61231aed70de453a2671cd7a3",
      "content": [],
      "providerData": {
        "type": "reasoning"
      }
    },
    "agent": {
      "name": "Recipe Chef"
    }
  },
  {
    "type": "message_output_item",
    "rawItem": {
      "type": "message",
      "id": "msg_686b95a209a8819b94395dda48fabfe00de453a2671cd7a3",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "**Green Energy Breakfast Smoothie**\n\n**Ingredients:**\n- 1 cup unsweetened almond milk\n- 1 cup fresh spinach leaves, packed\n- 1/2 cup frozen mango chunks\n- 1/2 frozen banana\n- 1 tablespoon chia seeds\n- 1 tablespoon almond butter\n- 1/4 teaspoon ground cinnamon\n- 1/2 teaspoon fresh grated ginger (optional)\n- 1 teaspoon honey or maple syrup (optional)\n- 4-5 ice cubes\n\n**Instructions:**\n1. Add the almond milk and spinach to a blender. Blend until smooth and no leafy chunks remain.\n2. Add the frozen mango, frozen banana, chia seeds, almond butter, cinnamon, ginger, honey or maple syrup (if using), and ice cubes.\n3. Blend until creamy and smooth, about 30-45 seconds.\n4. Pour into a glass and serve immediately.",
          "annotations": [],
          "logprobs": []
        }
      ],
      "status": "completed",
      "providerData": {}
    },
    "agent": {
      "name": "Recipe Chef"
    }
  }
]

This property is especially helpful for understanding the agent's reasoning, debugging, or building features that need to explain the agent's steps.

The finalOutput Property

The finalOutput property contains the agent's final answer or response. This is typically what you want to display to the user or use as the result of the agent's work. For a recipe agent, this would be the complete recipe text:

console.log(result.finalOutput);

When you print this property, you get the main output from the agent, ready to be shown to the user or passed to another agent:

**Green Energy Breakfast Smoothie**

**Ingredients:**
- 1 cup unsweetened almond milk
- 1 cup fresh spinach leaves, packed
- 1/2 cup frozen mango chunks
- 1/2 frozen banana
- 1 tablespoon chia seeds
- 1 tablespoon almond butter
- 1/4 teaspoon ground cinnamon
- 1/2 teaspoon fresh grated ginger (optional)
- 1 teaspoon honey or maple syrup (optional)
- 4-5 ice cubes

**Instructions:**
1. Add the almond milk and spinach to a blender. Blend until smooth and no leafy chunks remain.
2. Add the frozen mango, frozen banana, chia seeds, almond butter, cinnamon, ginger, honey or maple syrup (if using), and ice cubes.
3. Blend until creamy and smooth, about 30-45 seconds.
4. Pour into a glass and serve immediately.

This is the main output you'll use in your application or pass to another agent.

The history Property for Chaining Agents

The history property provides the full conversation history as an array of messages. This is especially useful for chaining agents or continuing a conversation, as it provides all the necessary context in the correct format.

For example, you can inspect the history like this:

console.log(JSON.stringify(result.history, null, 2));

The output will look like:

[
  {
    "type": "message",
    "role": "user",
    "content": "Give me a recipe for a healthy smoothie."
  },
  {
    "type": "reasoning",
    "id": "rs_686b959d21d8819ba2b833b61231aed70de453a2671cd7a3",
    "content": [],
    "providerData": {
      "type": "reasoning"
    }
  },
  {
    "type": "message",
    "id": "msg_686b95a209a8819b94395dda48fabfe00de453a2671cd7a3",
    "role": "assistant",
    "content": [
      {
        "type": "output_text",
        "text": "**Green Energy Breakfast Smoothie**\n\n**Ingredients:**\n- 1 cup unsweetened almond milk\n...",
        "annotations": [],
        "logprobs": []
      }
    ],
    "status": "completed",
    "providerData": {}
  }
]

When you want to pass context to another agent, you can use the history array and append new user messages as needed. This ensures that the next agent has access to the full context, leading to more accurate and relevant responses.

Chaining Agents Using Results

A powerful feature of the OpenAI Agents SDK is the ability to chain agents together, passing the output and context from one agent directly into another. This allows you to build multi-step workflows where each agent builds on the work of the previous one.

Let's look at a practical example. Suppose you have a recipeAgent that generates a smoothie recipe and a blogAgent that writes a blog post about that recipe. After running the first agent, you can use its history to provide full context to the second agent. Here's how you can do this in TypeScript:

import { Agent, run, user } from '@openai/agents';

// Define a Recipe Chef agent
const recipeAgent = new Agent({
  name: 'Recipe Chef',
  instructions:
    'You are a creative chef. Provide a detailed healthy smoothie recipe with a title, a list of ingredients, ' +
    'and step-by-step instructions. Do not include extra commentary. Output only the recipe text.',
  model: 'o4-mini'
});

// Define a Blog Writer agent
const blogAgent = new Agent({
  name: 'Blog Writer',
  instructions:
    'You are an engaging blog writer. Given the recipe text for a healthy smoothie, write an inspiring blog post ' +
    'that includes an introduction, a detailed description of the recipe, and a conclusion. Output only the blog post text.',
  model: 'gpt-4.1'
});

// Run the Recipe Chef agent
const recipeResult = await run(
  recipeAgent,
  'Give me a recipe for a healthy smoothie.'
);

// Run the Blog Writer agent with the Recipe Chef agent's results
const blogResult = await run(
  blogAgent,
  recipeResult.history.concat(user('Write a blog post about the recipe.'))
);

// Process the blogResult...

In this workflow, after the recipeAgent generates a recipe, we use the history property to capture the full conversation context. We then append a new user message asking for a blog post about the recipe using the user() helper, which creates a properly formatted user message object for the agent. This combined input is passed to the blogAgent, ensuring it has all the information it needs to write a relevant and accurate blog post.

Viewing the Final Output (Blog Post)

After running the blogAgent, you can access the final blog post text using the finalOutput property:

console.log(blogResult.finalOutput);

This will output something like:

### Energize Your Morning with the Ultimate Green Breakfast Smoothie

There's something empowering about starting the day off on a healthy note. For me, nothing sets the tone quite like a vibrant, nutrient-packed smoothie that fuels my morning with energy, flavor, and a little bit of zen. That's why I'm excited to share my go-to recipe: the Green Energy Breakfast Smoothie! This wholesome blend of greens, fruits, and superfoods is perfect for busy mornings or as a quick pick-me-up any time of day.

#### Why You'll Love This Smoothie

This recipe is more than just a pretty green drink — it's a powerhouse of vitamins, fiber, and healthy fats to keep you full and focused. Fresh spinach loads you up on antioxidants and iron, while frozen mango and banana give natural sweetness and a creamy, dreamy texture. Chia seeds add a boost of omega-3s and protein, almond butter offers a touch of richness, and warming cinnamon and ginger give it a spicy kick. The best part? It's incredibly easy to make and delicious enough for the whole family to enjoy.

#### Recipe: Green Energy Breakfast Smoothie

**Ingredients:**
- 1 cup unsweetened almond milk
...
Viewing the Last Agent Executed

The lastAgent property contains information about the last agent that was executed during the run. This is particularly useful when working with multi-agent workflows or when you need to track which agent produced the final output.

console.log(blogResult.lastAgent);

This will show you the details of the agent that generated the blog post:

Agent {
  eventEmitter: EventEmitter {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    [Symbol(shapeMode)]: false,
    [Symbol(kCapture)]: false
  },
  name: 'Blog Writer',
  instructions: 'You are an engaging blog writer. Given the recipe text for a healthy smoothie, write an inspiring blog post that includes an introduction, a detailed description of the recipe, and a conclusion. Output only the blog post text.',
  handoffDescription: '',
  handoffs: [],
  model: 'gpt-4.1',
  modelSettings: {},
  tools: [],
  mcpServers: [],
  inputGuardrails: [],
  outputGuardrails: [],
  outputType: 'text',
  toolUseBehavior: 'run_llm_again',
  resetToolChoice: true
}

This is useful for debugging or for tracking which agent handled the final step in a multi-agent workflow.

Summary & Preparation For Practice

In this lesson, you learned how to interpret the results of an agent run using the result object in the OpenAI Agents SDK for TypeScript. You explored its key properties — input, newItems, finalOutput, lastAgent, and history — and saw how to use them to chain agents together in a multi-step workflow. By understanding how to extract and use these results, you are now ready to build more advanced applications that combine the strengths of multiple agents.

In the next set of practice exercises, you'll get hands-on experience working with agent results and chaining agents together. This will help you solidify your understanding and prepare you for even more powerful agentic workflows. Well done on reaching this point — let's continue building your skills!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal