Mastering OpenAI Agents SDK: Build Agentic AI Workflows (with LangGraph Comparison)

MANOJ KUMARMANOJ KUMAR
26 min read

1. What is an agent?

A program that can make decisions and take actions to complete a task for you - like an assistant that can think, call tools (search, calendar, files), and act on results.

What is an agent?

2. What is a tool?

A specific capability an agent can use - e.g., a web search, a calculator, a file reader, or a calendar API. Tools are like the agent’s toolbox.

3. What is an LLM (Large Language Model)?

A very big neural network trained on lots of text that predicts and generates human like words. LLMs write, summarize, answer questions, and help agents “think.” like a brain.

3. What is an LLM (Large Language Model)?

4. What is Agentic AI?

AI built from agents - software pieces that plan, use tools, and act autonomously to solve tasks (not just answer a single question). It’s AI that can carry out multi-step work on its own.

What is Agentic AI?

5. What is a workflow in AI?

A sequence of steps the system follows to solve a problem for example: get user request → fetch documents → call LLM to summarize → run a tool to update a file → return result.

What is a workflow in AI?

6. What are autonomous & procedural flow in agentic AI?

Procedural flow: a fixed script of steps you write beforehand (if A then B then C).

Autonomous flow: the agent decides next steps itself based on goals and observations (it plans, adapts, and can loop until the goal is done).

Example: a procedural script sends the same weekly report. An autonomous agent figures out who needs what report, fetches data, and follows up where needed.

What are autonomous & procedural flow in agentic AI

7. What is an SDK (Software Development Kit)?

A package of code, libraries, tools, examples, and docs that helps developers build apps faster - like a starter kit for programmers.

What is an SDK (Software Development Kit)

8. What is LangChain?

LangChain is an open-source framework designed to build applications powered by Large Language Models (LLMs) like GPT.

It acts like a toolbox that makes it easier to connect an LLM with:

a.) Data sources (PDFs, VTTs/SRTs, databases, websites, APIs)

b.) Tools & APIs (search engines, calculators, plugins, website scrapper, vector embedding)

c.) Workflows (chains, agents, memory, retrieval)

Instead of writing everything from scratch, LangChain gives pre-built components to compose complex AI apps quickly.

What is LangChain

Why use LangChain?

  1. Easier Development: Ready-made modules (chains, prompts, memory, agents)

  2. Data-Aware Apps: Can retrieve and use private/company data (RAG systems)

  3. Reasoning Power: Supports agents that can “decide” which tools to use

  4. Integration Friendly: Works with vector DBs (Pinecone, Weaviate, FAISS), APIs, SQL, cloud storage

  5. Scalability: Helps move from prototype → production with monitoring, tracing, and deployment tools

Usecase of LangChain

  • Chat with Documents: Upload PDFs, and the AI answers questions from them.

  • Customer Support Bot: AI that uses internal knowledge base + tools.

  • AI Agents: LLMs that can search Google, query a DB, or call APIs.

  • Content Generation Workflows: Multi-step chains (research → draft → refine → final).

Important Articles You can read for better understanding to LangChain

  1. Build your own RAG system using Node.js with two main phases: Indexing and Retrieval/Chat https://bcapathshala.hashnode.dev/practical-guide-to-retrival-augmented-generation-from-scratch

  2. Where RAGs Fail - A Beginner Friendly Guide to Reliable RAG (Retrieval Augmented Generation) https://bcapathshala.hashnode.dev/where-rags-fail-a-beginner-friendly-guide-to-reliable-rag?source=more_articles_bottom_blogs

  3. Practical patterns & production recipes for accurate, scalable Retrieval‑Augmented Generation (RAG) https://bcapathshala.hashnode.dev/system-design-of-rags-pipeline?source=more_articles_bottom_blogs

9. What is a Graph?

A graph is a way to represent data as a network. In this network:

  • Nodes represent entities (like people, places, or objects).

  • Edges represent the relationships between these entities (one-to-one, one-to-many, many-to-many, etc.).

Examples:

  • Transportation system: cities as nodes, routes as edges

  • Social media: users as nodes, friendships/follows as edges

Types of Graphs:

  1. Edges have a direction (like A follows B on social media)

  2. Undirected Graph: Edges don’t have direction (like A is connected with B on LinkedIn)

Types of Graphs Directed Graph

10. What is LangGraph?

LangGraph is a graph-style framework (by the LangChain ecosystem) for building and running stateful, multi-step agent workflows. It models work as nodes and edges, keeps state across steps, and aims to give you strong control over complex agent flows.

What is LangGraph

11. How does LangGraph work?

You describe the work as a graph: nodes = actions/actors (LLMs, tools, logic), edges \= flow between steps. LangGraph runs the graph, keeps state across runs, helps coordinate many actors, and provides tooling (studio/platform) for debugging and deploying. It’s great when you need long-running, controlled agent behavior.

How does LangGraph work

12. LangGraph by Langchain Vs Agents SDK by OpenAI

LangGraph by Langchain

  1. LangGraph works on the principle of a directed graph. This means there is a flow between nodes, and as developers, we need to decide how that flow happens in our workflow when building AI agents.

  2. It feels like LangGraph often behaves like a linear graph. Why? Because by default, one node cannot automatically skip to another node or send a response back unless we explicitly program it.

For example, if Node A calls Node B, Node B won’t automatically return a response back to Node A unless we handle it in the code.

LangGraph by Langchain

  1. So, the flow is not autonomous but procedural. We, as developers, have to manually control how the nodes are connected and how data moves.

    LangGraph by Langchain

Real World Example: Suppose the user query is already perfect. Ideally, the “Rewrite Query” step should be skipped automatically. But LangGraph doesn’t skip it by itself, so we have to code this behavior manually.

langchain

👉 That’s why we say LangGraph follows a non-autonomous, procedure-driven flow instead of an automatic one.

Agents SDK by OpenAI

Agent SDK is like a wrapper on top of OpenAI. It provides everything needed to turn an LLM into a fully functional agent

Agents SDK by OpenAI

What it includes:

  1. Tool calling Human-in-the-loop

  2. Tracing/monitoring

  3. Multi-agent interactions

  4. Networking between agents

    Key difference from LangGraph:

    1. LangGraph = procedural flow (developer controls each step, like a script)

    2. Agent SDK = autonomous, non-linear flow (agents decide what to do themselves)

    Agents SDK by OpenAI

How OpenAI Agent SDK works

Step 1: You (the developer) create agents for specific tasks (e.g., a Search Agent, Coding Agent, Summarizer Agent) and equip them with the right tools.

Step 2: Agent SDK automatically handles the flow, decisions, and communication between agents and tools. In short, Agent SDK takes over and automatically manages the workflow:

  • a.) Agents can handoff tasks to other agents when needed.

  • b.) Each agent independently decides where to go, how deep to go, and when to stop without you having to manually define every path.

How Agent SDK works

Analogy: Bank Example

LangGraph (procedural): Imagine you visit a bank to open an account. You go from one counter to another based on instructions from the previous counter. As a developer, you must define each step: Counter 1 → Counter 2 → Counter 3.

Agent SDK (autonomous): Imagine you have a known person in the bank. You just tell him, “I need to open an account.”

He automatically:

  • Collects your documents

  • Decides which counter to go to

  • Handles the full process

  • Finally gives you the account details when everything is done.

👉 This is how Agent SDK works — agents handle the workflow automatically without needing step-by-step developer instructions.

13. Coding phase (building agents with OpenAI Agents SDK)

Basic Rules of OpenAI Agents SDK for Coding

Step 1: Create an Agent with all the necessary tools, but only for a specific task.

Step 2: Interact with the Agent and its tools in two ways:

Way 1: Use the Runner function to run the Agent for simple text/chat interactions.

Way 2: Use a real-time session (via voice call, WebSocket, or WebRTC) for interactive or live use cases.

Coding phase (building agents with OpenAI Agents SDK)

A.) Level 1 (Create a Cooking Agent with two tools)

A tool to get the current time & A tool to get the menu

// level1.js
import "dotenv/config";
import { Agent, tool, run } from "@openai/agents";
import { z } from "zod";

// Step 1: Create an agent with these tools

// Tool to get the current time
const getCurrentTimeTool = tool({
  name: "get_current_time",
  description: "This tool returns the current date and time as a string.",
  parameters: z.object({}),
  execute: async () => {
    return new Date().toString();
  },
});

// Tool to get the manu
const getMenuTool = tool({
  name: "get_menu",
  description:
    "This tool fethes and returns the menu of a restaurant given its name.",
  parameters: z.object({
    restaurant_name: z.string().describe("The name of the restaurant"),
  }),
  execute: async ({ restaurant_name }) => {
    const menu = {
      "restaurant a": [
        {
          Drinks: {
            Chai: "INR 50",
            Coffee: "INR 70",
          },
          Veg: {
            DalMakhni: "INR 250",
            Panner: "INR 400",
          },
        },
      ],
      "restaurant b": [
        {
          Drinks: {
            Lemonade: "INR 40",
            Mojito: "INR 120",
            Lahori: "INR 150",
          },
          NonVeg: {
            ChickenCurry: "INR 350",
            MuttonBiryani: "INR 500",
          },
          Veg: {
            VegBiryani: "INR 300",
            MixVeg: "INR 200",
          },
        },
      ],
    };
    return (
      menu[restaurant_name.toLowerCase()] ||
      "Menu not found for this restaurant."
    );
  },
});

// Create the cooking agent
export const cookingAgent = new Agent({
  name: "Cooking Agent",
  model: "gpt-4.1-mini",
  tools: [getCurrentTimeTool, getMenuTool],
  instructions: `
    You are a cooking assistant who is speacialized in cooking food. Help users with recipes, cooking tips, and meal ideas. Always help them to cook the foods they want to cook.

    Your Responsibilities for Cooking-Related Queries:
    If the user asks for a recipe, provide a detailed recipe with ingredients and step-by-step instructions.
    If the user asks for cooking tips, provide useful and practical advice.
    If the user asks for meal ideas, suggest creative and delicious meal options based on their preferences and dietary restrictions.

    Your Responsibilities for Restaurant Menu Queries:
    If the user asks for the menu of a restaurant, use the get_menu tool to fetch the menu.
    If the user asks for the price of a specific dish or drink in a restaurant, use the get_menu tool to fetch the menu and provide the price.
    If the user asks for recommendations based on the menu, use the get_menu tool to fetch the menu and suggest dishes or drinks.
    If the user asks for the current time to suggest a meal, use the get_current_time tool to fetch the current time and suggest a meal accordingly.

    Important Notes:
    If the user asks for something unrelated to cooking or restaurant menus, politely inform them that you can only assist with cooking and restaurant menu-related queries.
    Always use the provided tools to fetch real-time information when needed.

    Tone and Style:
    Always respond in a friendly and helpful manner.
    Use clear and concise language that is easy to understand.
    `,
});

// Step 2: Run the agent with runner (text input/chat input)
const chatWithCookingAgent = async (query) => {
  const result = await run(cookingAgent, query);
  console.log("History :", result.history);
  console.log("Final Output :", result.finalOutput);
};

// Example usage
chatWithCookingAgent(
   "In Restaurant B, what is good to eat and drink based on current time?"
 );

Query Example 1: Depending on the current time, suggest a meal I can cook right now. (Read History Carefully How To Manage The Workflow (focus on function call) by OpenAI Agents SDK Automatically)

History : [
  {
    type: 'message',
    role: 'user',
    content: 'Depending on the current time, suggest a meal I can cook right now.'
  },
  {
    type: 'function_call',
    id: 'fc_68ad7b9e3678819294e8900edea8cfe206ff8bd043e3fa4b',
    callId: 'call_HECMovmERyBQpgisdL0BaMVK',
    name: 'get_current_time',
    status: 'completed',
    arguments: '{}',
    providerData: {
      id: 'fc_68ad7b9e3678819294e8900edea8cfe206ff8bd043e3fa4b',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_current_time',
    callId: 'call_HECMovmERyBQpgisdL0BaMVK',
    status: 'completed',
    output: {
      type: 'text',
      text: 'Tue Aug 26 2025 14:47:18 GMT+0530 (India Standard Time)'
    }
  },
  {
    id: 'msg_68ad7b9f844c819291e8cc2311bbbc4b06ff8bd043e3fa4b',
    type: 'message',
    role: 'assistant',
    content: [ [Object] ],
    status: 'completed',
    providerData: {}
  }
]
Final Output : It's around 2:47 PM right now, which is a great time for a delicious lunch or an early snack. How about making a quick and tasty Chicken Caesar Salad? It's light, refreshing, and easy to prepare.

Here's a simple recipe for you:

Ingredients:
- 2 cups romaine lettuce, chopped
- 1 grilled chicken breast, sliced
- 1/4 cup grated Parmesan cheese
- Croutons (a handful)
- Caesar dressing (to taste)
- Salt and pepper to taste

Instructions:
1. Wash and chop the romaine lettuce.
2. Grill or pan-fry the chicken breast with a little salt and pepper until cooked through, then slice it.
3. In a large bowl, combine the lettuce, sliced chicken, Parmesan cheese, and croutons.
4. Drizzle Caesar dressing over the salad and toss everything together until well coated.
5. Serve immediately and enjoy!

Would you like a recipe for something else or maybe a warm meal suggestion?

Query Example 2: In Restaurant B, what is the price of Mojito and MuttonBiryani? (Read History Carefully How To Manage The Workflow (focus on function call) by OpenAI Agents SDK Automatically)

History : [
  {
    type: 'message',
    role: 'user',
    content: 'In Restaurant B, what is the price of Mojito and MuttonBiryani?'
  },
  {
    type: 'function_call',
    id: 'fc_68ad81f0aa2081a39053a59e434d218a05322192b8e9d303',
    callId: 'call_fMACOTWA6FRTQrjQgBRORfeN',
    name: 'get_menu',
    status: 'completed',
    arguments: '{"restaurant_name":"Restaurant B"}',
    providerData: {
      id: 'fc_68ad81f0aa2081a39053a59e434d218a05322192b8e9d303',
      type: 'function_call'
    }
  },
  {
    type: 'function_call',
    id: 'fc_68ad81f166b881a38df424d98cc7c8ca05322192b8e9d303',
    callId: 'call_xrvMU3HSjXWhKO8Ff9DoFwdD',
    name: 'get_menu',
    status: 'completed',
    arguments: '{"restaurant_name":"Restaurant B"}',
    providerData: {
      id: 'fc_68ad81f166b881a38df424d98cc7c8ca05322192b8e9d303',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_fMACOTWA6FRTQrjQgBRORfeN',
    status: 'completed',
    output: {
      type: 'text',
      text: '[{"Drinks":{"Lemonade":"INR 40","Mojito":"INR 120","Lahori":"INR 150"},"NonVeg":{"ChickenCurry":"INR 350","MuttonBiryani":"INR 500"},"Veg":{"VegBiryani":"INR 300","MixVeg":"INR 200"}}]'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_xrvMU3HSjXWhKO8Ff9DoFwdD',
    status: 'completed',
    output: {
      type: 'text',
      text: '[{"Drinks":{"Lemonade":"INR 40","Mojito":"INR 120","Lahori":"INR 150"},"NonVeg":{"ChickenCurry":"INR 350","MuttonBiryani":"INR 500"},"Veg":{"VegBiryani":"INR 300","MixVeg":"INR 200"}}]'
    }
  },
  {
    id: 'msg_68ad81f33cbc81a3b5c672c650be88b605322192b8e9d303',
    type: 'message',
    role: 'assistant',
    content: [ [Object] ],
    status: 'completed',
    providerData: {}
  }
]
Final Output : In Restaurant B, the price of a Mojito is INR 120, and the price of Mutton Biryani is INR 500. If you need any more information or recommendations, feel free to ask!

Query Example 3: In Restaurant B, what is good to eat and drink based on current time? (Read History Carefully How To Manage The Workflow (focus on function call) by OpenAI Agents SDK Automatically)

History : [
  {
    type: 'message',
    role: 'user',
    content: 'In Restaurant B, what is good to eat and drink based on current time?'
  },
  {
    type: 'function_call',
    id: 'fc_68ad8339f724819e83cf10bdc802519008da3c1baf38c22f',
    callId: 'call_P9gE6PIzh5MRtEhUwouM57Ti',
    name: 'get_menu',
    status: 'completed',
    arguments: '{"restaurant_name":"Restaurant B"}',
    providerData: {
      id: 'fc_68ad8339f724819e83cf10bdc802519008da3c1baf38c22f',
      type: 'function_call'
    }
  },
  {
    type: 'function_call',
    id: 'fc_68ad833a54bc819e9c357712d468828008da3c1baf38c22f',
    callId: 'call_3ojoXE8IlIvLmrObnCZkKZdF',
    name: 'get_current_time',
    status: 'completed',
    arguments: '{}',
    providerData: {
      id: 'fc_68ad833a54bc819e9c357712d468828008da3c1baf38c22f',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_P9gE6PIzh5MRtEhUwouM57Ti',
    status: 'completed',
    output: {
      type: 'text',
      text: '[{"Drinks":{"Lemonade":"INR 40","Mojito":"INR 120","Lahori":"INR 150"},"NonVeg":{"ChickenCurry":"INR 350","MuttonBiryani":"INR 500"},"Veg":{"VegBiryani":"INR 300","MixVeg":"INR 200"}}]'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_current_time',
    callId: 'call_3ojoXE8IlIvLmrObnCZkKZdF',
    status: 'completed',
    output: {
      type: 'text',
      text: 'Tue Aug 26 2025 15:19:46 GMT+0530 (India Standard Time)'
    }
  },
  {
    id: 'msg_68ad833c143c819e8ba39cd7d8b6527908da3c1baf38c22f',
    type: 'message',
    role: 'assistant',
    content: [ [Object] ],
    status: 'completed',
    providerData: {}
  }
]
Final Output : It's currently around 3:19 PM. At this time, a light yet satisfying meal might be ideal. From Restaurant B, I recommend trying the Veg Biryani or Mix Veg if you prefer a vegetarian option. For non-vegetarian, the Chicken Curry is a great choice.

To drink, you could enjoy a refreshing Lemonade or a Mojito to complement your meal.

Would you like recipes or tips on how to enjoy these dishes, or any other assistance?

B.) Level 2 (Handoffs)

Create a gateway agent to route between different agents (As a receptionist🍽️)

Handoffs - OpenAI Agents SDK

// level2.js
import "dotenv/config";
import { Agent, webSearchTool, run } from "@openai/agents";
import { z } from "zod";
import { cookingAgent } from "./level1.js";

// Step 1: Create an agent with these tools

// Create the coding agent
const codingAgent = new Agent({
  name: "Coding Agent",
  tools: [webSearchTool("https://developer.mozilla.org/en-US")],
  instructions: `
        You are a coding assistant particularly skilled in JavaScript. You can help users with coding-related queries, including writing code snippets, debugging, and explaining programming concepts.

        Your Responsibilities:
        1. Understand the user's coding-related queries.
        2. Provide accurate and efficient code snippets or explanations in JavaScript.
        3. If the query is unrelated to coding, politely inform the user that you can only assist with coding-related queries.
        4. Use the web search tool to look up information on MDN Web Docs when necessary to provide accurate and up-to-date information.

        Important Notes:
        - Always ensure that your responses are clear and concise.
        - Maintain a friendly and helpful tone in all interactions.
        - Explain complex coding concepts in a simple manner and provide in simple text format include bullet points if necessary.

        Output Format: { code: "your code snippet here", explanation: "your explanation here", references: ["list of references"] }
        - if your response does not require code, return { code: "N/A", explanation: "your explanation here", references: [] }
        - if the query is unrelated to coding, return { code: "N/A", explanation: "I'm sorry, I can only assist with coding-related queries.", references: [] }
        `,
});

// Handoffs: Create a gateway agent to route between different agents (As a receptionist🍽️)
const getewayAgent = Agent.create({
  name: "Gateway Agent",
  handoffs: [cookingAgent, codingAgent],
  instructions: `
      You are a gateway agent who routes user queries to the appropriate specialized agents. You have access to the following agents:
      1. Cooking Agent: Specializes in cooking-related queries and restaurant menu inquiries.
      2. Coding Agent: Specializes in coding-related queries, particularly in JavaScript.

      Your Responsibilities:
      1. Analyze the user's query to determine its nature (cooking-related or coding-related).
      2. Route the query to the appropriate agent based on its content.
      3. If the query is ambiguous or does not clearly fall into either category, use your best judgment to choose the most relevant agent.

      Important Notes:
      - Always ensure that the user's query is directed to the most appropriate agent based on its content.
      - Maintain a friendly and helpful tone in all interactions.
    `,
});

// Step 2: Run the agent with runner (text input/chat input)
const chatWithAgent = async (query) => {
  const result = await run(getewayAgent, query);
  console.log("History :", result.history);
  console.log("Last Agent :", result.lastAgent.name);
  console.log("Final Output :", result.finalOutput);
};

// Example usage
chatWithAgent(
  "I am a biginner in JavaScript. Can you help me understand closures with a simple example?"
);

Query Example 1: In Restaurant B, what is good to eat and drink based on current time? (Read History Carefully How To Manage The Workflow (focus on function call) by OpenAI Agents SDK Automatically

History : [
  {
    type: 'message',
    role: 'user',
    content: 'In Restaurant B, what is good to eat and drink based on current time?'
  },
  {
    type: 'function_call',
    id: 'fc_68ad8997e3d081a08ec8f6902a18a9430b89597c9cb1697b',
    callId: 'call_HIKkgsbyheKojkHfUQOGzIXP',
    name: 'transfer_to_Cooking_Agent',
    status: 'completed',
    arguments: '{}',
    providerData: {
      id: 'fc_68ad8997e3d081a08ec8f6902a18a9430b89597c9cb1697b',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'transfer_to_Cooking_Agent',
    callId: 'call_HIKkgsbyheKojkHfUQOGzIXP',
    status: 'completed',
    output: { type: 'text', text: '{"assistant":"Cooking Agent"}' }
  },
  {
    type: 'function_call',
    id: 'fc_68ad8999fd7081a0bebde9e720e4c8250b89597c9cb1697b',
    callId: 'call_lToeySGlGTOPpJ46pa89B9Oi',
    name: 'get_current_time',
    status: 'completed',
    arguments: '{}',
    providerData: {
      id: 'fc_68ad8999fd7081a0bebde9e720e4c8250b89597c9cb1697b',
      type: 'function_call'
    }
  },
  {
    type: 'function_call',
    id: 'fc_68ad899a270881a09c61de6d75388a050b89597c9cb1697b',
    callId: 'call_bhwuqu6pCMhl1SmggvvqDxLB',
    name: 'get_menu',
    status: 'completed',
    arguments: '{"restaurant_name":"Restaurant B"}',
    providerData: {
      id: 'fc_68ad899a270881a09c61de6d75388a050b89597c9cb1697b',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_current_time',
    callId: 'call_lToeySGlGTOPpJ46pa89B9Oi',
    status: 'completed',
    output: {
      type: 'text',
      text: 'Tue Aug 26 2025 15:46:58 GMT+0530 (India Standard Time)'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_bhwuqu6pCMhl1SmggvvqDxLB',
    status: 'completed',
    output: {
      type: 'text',
      text: '[{"Drinks":{"Lemonade":"INR 40","Mojito":"INR 120","Lahori":"INR 150"},"NonVeg":{"ChickenCurry":"INR 350","MuttonBiryani":"INR 500"},"Veg":{"VegBiryani":"INR 300","MixVeg":"INR 200"}}]'
    }
  },
  {
    id: 'msg_68ad899bced881a0b821d80af24a87320b89597c9cb1697b',
    type: 'message',
    role: 'assistant',
    content: [ [Object] ],
    status: 'completed',
    providerData: {}
  }
]
Last Agent : Cooking Agent
Final Output : It's currently around 3:46 PM. For a meal at Restaurant B during this time, you might enjoy something light and refreshing. Here are some good options to eat and drink:

To Eat:
- Veg Biryani (INR 300)
- Mix Veg (INR 200)

To Drink:
- Lemonade (INR 40) for a refreshing choice
- Mojito (INR 120) if you want something a bit more special

If you're looking for something more filling, you can also consider:
- Chicken Curry (INR 350)
- Mutton Biryani (INR 500)

Would you like a recipe or cooking tips for any of these dishes?

Query Example 2: I am a biginner in JavaScript. Can you help me understand closures with a simple example? (Read History Carefully How To Manage The Workflow (focus on function call) by OpenAI Agents SDK Automatically

History : [
  {
    type: 'message',
    role: 'user',
    content: 'I am a biginner in JavaScript. Can you help me understand closures with a simple example?'
  },
  {
    type: 'function_call',
    id: 'fc_68ad8db29fb8819dbe138dfa4644cc2f02d61c89154cc386',
    callId: 'call_lzzyRA9sVJN9ekSnOKZ9owv9',
    name: 'transfer_to_Coding_Agent',
    status: 'completed',
    arguments: '{}',
    providerData: {
      id: 'fc_68ad8db29fb8819dbe138dfa4644cc2f02d61c89154cc386',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'transfer_to_Coding_Agent',
    callId: 'call_lzzyRA9sVJN9ekSnOKZ9owv9',
    status: 'completed',
    output: { type: 'text', text: '{"assistant":"Coding Agent"}' }
  },
  {
    id: 'msg_68ad8db4428c819db7a214926040c09002d61c89154cc386',
    type: 'message',
    role: 'assistant',
    content: [ [Object] ],
    status: 'completed',
    providerData: {}
  }
]
Last Agent : Coding Agent
Final Output : { code: `function outerFunction() {
    let outerVariable = "I'm from the outer scope!";

    function innerFunction() {
        console.log(outerVariable); // innerFunction can access outerVariable!
    }

    return innerFunction;
}

const closureExample = outerFunction();
closureExample(); // Output: "I'm from the outer scope!"
`, explanation: `
A closure in JavaScript is created when a function (inner function) is defined inside another function (outer function), and the inner function "remembers" the variables from the outer function's scope even after the outer function has finished executing.

**How this example works:**
- \`outerFunction\` creates a variable called \`outerVariable\`.
- \`innerFunction\` is declared inside \`outerFunction\` and uses \`outerVariable\`.
- \`outerFunction\` returns \`innerFunction\`.
- When you call \`closureExample()\` (which is really \`innerFunction\`), it still has access to \`outerVariable\` that was defined in \`outerFunction\`.
- This "remembering" is what we call a **closure**.

**Why is this useful?**
- It allows functions to have "private" variables.
- It enables powerful patterns like data encapsulation, factories, and more.

`, references: ["https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures"] }

C.) Level 3 (Agent as Tool)

Create the agent as tool (cookingAgent is as tool here) Sometimes you want an Agent to assist another Agent without fully handing off the conversation

Note: in production, 99% companies don't focus on agent as tool but its good to know😒

Agent as Tool - OpenAI Agents SDK

// level3.js
import "dotenv/config";
import { Agent, webSearchTool, run } from "@openai/agents";
import { z } from "zod";
import { cookingAgent } from "./level1.js";

// Step 1: Create an agent with these tools

// create the agent as tool (cookingAgent is as tool here)
// Sometimes you want an Agent to assist another Agent without fully handing off the conversation
// Note: in production, 99% companies dont focus on agent as tool but its good to know😒
const cookingAgentAsTool = cookingAgent.asTool({
  name: "cooking_agent_as_tool",
  description:
    "This tool handles cooking-related queries and restaurant menu inquiries.",
});

// Create the coding agent
const codingAgent = new Agent({
  name: "Coding Agent",
  tools: [
    webSearchTool("https://developer.mozilla.org/en-US"),
    cookingAgentAsTool,
  ],
  instructions: `
        You are a coding assistant particularly skilled in JavaScript. You can help users with coding-related queries, including writing code snippets, debugging, and explaining programming concepts.

        Your Responsibilities:
        1. Understand the user's coding-related queries.
        2. Provide accurate and efficient code snippets or explanations in JavaScript.
        3. If the query is unrelated to coding, politely inform the user that you can only assist with coding-related queries.
        4. Use the web search tool to look up information on MDN Web Docs when necessary to provide accurate and up-to-date information.
        5. If the user has cooking-related queries, use the cooking agent tool to handle those queries.

        Important Notes:
        - Always ensure that your responses are clear and concise.
        - Maintain a friendly and helpful tone in all interactions.
        - Explain complex coding concepts in a simple manner and provide in simple text format include bullet points if necessary.

        Output Format: { code: "your code snippet here", explanation: "your explanation here", references: ["list of references"] }
        - if your response does not require code, return { code: "N/A", explanation: "your explanation here", references: [] }
        - if the query is unrelated to coding, return { code: "N/A", explanation: "I'm sorry, I can only assist with coding-related queries.", references: [] }
        - if the query is related to cooking, use the cooking agent tool to handle the query and return its response in the different output format: { response: "response from cooking agent here" }
        `,
});

// Handoffs: Create a gateway agent to route between different agents (As a receptionist🍽️)
const getewayAgent = Agent.create({
  name: "Gateway Agent",
  handoffs: [codingAgent, cookingAgent],
  instructions: `
      You are a gateway agent who routes user queries to the appropriate specialized agents. You have access to the following agents:
      1. Cooking Agent: Specializes in cooking-related queries and restaurant menu inquiries.
      2. Coding Agent: Specializes in coding-related queries, particularly in JavaScript.

      Your Responsibilities:
      1. Analyze the user's query to determine its nature (cooking-related or coding-related).
      2. Route the query to the appropriate agent based on its content.
      3. If the query is ambiguous or does not clearly fall into either category, use your best judgment to choose the most relevant agent.

      Important Notes:
      - Always ensure that the user's query is directed to the most appropriate agent based on its content.
      - Maintain a friendly and helpful tone in all interactions.
    `,
});

// Step 2: Run the agent with runner (text input/chat input)
const chatWithAgent = async (query) => {
  const result = await run(getewayAgent, query);
  console.log("History :", result.history);
  console.log("Last Agent :", result.lastAgent.name);
  console.log("Final Output :", result.finalOutput);
};

// Example usage
chatWithAgent("In Restaurant A, give me the drink menu price list.");

Query Example 1: In Restaurant A, give me the drink menu price list. (Read History Carefully How To Manage The Workflow (focus on function call) by OpenAI Agents SDK Automatically

History : [
  {
    type: 'message',
    role: 'user',
    content: 'In Restaurant A, give me the drink menu price list.'
  },
  {
    type: 'function_call',
    id: 'fc_68ad93993e9c81a1ac478c9c79c6a79c016cb475a557bb1d',
    callId: 'call_kTbN7eg2PoOyzdiYSaglbWwL',
    name: 'transfer_to_Cooking_Agent',
    status: 'completed',
    arguments: '{}',
    providerData: {
      id: 'fc_68ad93993e9c81a1ac478c9c79c6a79c016cb475a557bb1d',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'transfer_to_Cooking_Agent',
    callId: 'call_kTbN7eg2PoOyzdiYSaglbWwL',
    status: 'completed',
    output: { type: 'text', text: '{"assistant":"Cooking Agent"}' }
  },
  {
    type: 'function_call',
    id: 'fc_68ad939aa0e481a1bfea0a80d13fb5ed016cb475a557bb1d',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    name: 'get_menu',
    status: 'completed',
    arguments: '{"restaurant_name":"Restaurant A"}',
    providerData: {
      id: 'fc_68ad939aa0e481a1bfea0a80d13fb5ed016cb475a557bb1d',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    name: 'transfer_to_Cooking_Agent',
    callId: 'call_kTbN7eg2PoOyzdiYSaglbWwL',
    status: 'completed',
    output: { type: 'text', text: '{"assistant":"Cooking Agent"}' }
  },
  {
    type: 'function_call',
    id: 'fc_68ad939aa0e481a1bfea0a80d13fb5ed016cb475a557bb1d',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    name: 'get_menu',
    status: 'completed',
    arguments: '{"restaurant_name":"Restaurant A"}',
    providerData: {
      id: 'fc_68ad939aa0e481a1bfea0a80d13fb5ed016cb475a557bb1d',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    status: 'completed',
    output: { type: 'text', text: '{"assistant":"Cooking Agent"}' }
  },
  {
    type: 'function_call',
    id: 'fc_68ad939aa0e481a1bfea0a80d13fb5ed016cb475a557bb1d',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    name: 'get_menu',
    status: 'completed',
    arguments: '{"restaurant_name":"Restaurant A"}',
    providerData: {
      id: 'fc_68ad939aa0e481a1bfea0a80d13fb5ed016cb475a557bb1d',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
  },
  {
    type: 'function_call',
    id: 'fc_68ad939aa0e481a1bfea0a80d13fb5ed016cb475a557bb1d',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    name: 'get_menu',
    status: 'completed',
    arguments: '{"restaurant_name":"Restaurant A"}',
    providerData: {
      id: 'fc_68ad939aa0e481a1bfea0a80d13fb5ed016cb475a557bb1d',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    name: 'get_menu',
    status: 'completed',
    arguments: '{"restaurant_name":"Restaurant A"}',
    providerData: {
      id: 'fc_68ad939aa0e481a1bfea0a80d13fb5ed016cb475a557bb1d',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    status: 'completed',
    output: {
      type: 'text',
      text: '[{"Drinks":{"Chai":"INR 50","Coffee":"INR 70"},"Veg":{"DalMakhni":"INR 250","Panner":"INR 400"}}]'
    providerData: {
      id: 'fc_68ad939aa0e481a1bfea0a80d13fb5ed016cb475a557bb1d',
      type: 'function_call'
    }
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    status: 'completed',
    output: {
      type: 'text',
      text: '[{"Drinks":{"Chai":"INR 50","Coffee":"INR 70"},"Veg":{"DalMakhni":"INR 250","Panner":"INR 400"}}]'
  },
  {
    type: 'function_call_result',
    name: 'get_menu',
    callId: 'call_yRA59j9FGTGG9oVdDMt7OUAz',
    status: 'completed',
    output: {
      type: 'text',
      text: '[{"Drinks":{"Chai":"INR 50","Coffee":"INR 70"},"Veg":{"DalMakhni":"INR 250","Panner":"INR 400"}}]'
    }
  },
  {
    status: 'completed',
    output: {
      type: 'text',
      text: '[{"Drinks":{"Chai":"INR 50","Coffee":"INR 70"},"Veg":{"DalMakhni":"INR 250","Panner":"INR 400"}}]'
    }
  },
  {
    }
  },
  {
    id: 'msg_68ad939b924081a1abf699281e8def83016cb475a557bb1d',
    type: 'message',
    role: 'assistant',
    content: [ [Object] ],
    status: 'completed',
    id: 'msg_68ad939b924081a1abf699281e8def83016cb475a557bb1d',
    type: 'message',
    role: 'assistant',
    content: [ [Object] ],
    status: 'completed',
    providerData: {}
  }
    content: [ [Object] ],
    status: 'completed',
    providerData: {}
  }
]
    status: 'completed',
    providerData: {}
  }
]
    providerData: {}
  }
]
Last Agent : Cooking Agent
]
Last Agent : Cooking Agent
Final Output : In Restaurant A, the drink menu price list is as follows:
Last Agent : Cooking Agent
Final Output : In Restaurant A, the drink menu price list is as follows:
Final Output : In Restaurant A, the drink menu price list is as follows:
- Chai: INR 50
- Chai: INR 50
- Coffee: INR 70
- Coffee: INR 70

Let me know if you need information on any other menu items or help with anything else!

D.) Level 4 (Text Streaming by OpenAI Agent SDK)

Create a Storytelling Agent - this agent takes a topic and tells a short, engaging story about it & create Weather Agent - this agent uses the weatherTool to answer weather-related queries.

// streamtext.js
import "dotenv/config";
import { Agent, Runner, tool } from "@openai/agents";
import chalk from "chalk";
import { z } from "zod";
import axios from "axios";

// Create a simple storytelling agent
const storytellerAgent = new Agent({
  name: "Storyteller",
  instructions:
    "You are a storyteller. You will be given a topic and you will tell a story about it. Make it engaging and interesting. and give short and concise story.",
});

// Create the weather tool
const weatherTool = tool({
  name: "get_weather",
  description: "Get the current weather for a given city.",
  parameters: z.object({
    city: z.string().describe("The city to get the weather for."),
  }),
  execute: async ({ city }) => {
    const url = `https://wttr.in/${city.toLowerCase()}?format=%C+%t`;
    const { data } = await axios.get(url, { responseType: "text" });
    return `The current weather in ${city} is ${data}`;
  },
});

// Add the weather tool to weather agent
const weatherAgent = new Agent({
  name: "Weather Agent",
  tools: [weatherTool],
  instructions:
    "You are a weather assistant. You can provide the current weather for a given city using the get_weather tool.",
});

// Create a runner to run the agent 😁
const runner = new Runner({
  model: "gpt-4o-mini",
});

// Main function to run the agent with streaming enabled
const init = async () => {
  console.log(chalk.bgCyan("  ● Story teller streaming  \n"));

  // Run the agent with streaming enabled
  const storytellerStream = await runner.run(
    storytellerAgent,
    "Tell me a story about a manoj nishad (he is a software engineer).",
    {
      stream: true, // Enable streaming
    }
  );

  // If you only care about the text you can use the transformed textStream
  storytellerStream
    .toTextStream({
      compatibleWithNodeStreams: true,
    })
    .pipe(process.stdout);

  // waiting to make sure that we are done with handling the stream
  await storytellerStream.completed;

  console.log(chalk.bgCyan("\n\n  ● Weather streaming  \n"));

  const weatherStream = await runner.run(
    weatherAgent,
    "What is the weather in Bangalore?",
    {
      stream: true, // Enable streaming
    }
  );

  weatherStream
    .toTextStream({
      compatibleWithNodeStreams: true,
    })
    .pipe(process.stdout);

  await weatherStream.completed;
};

init().catch((error) => {
  console.error("Error:", error);
  process.exit(1);
});

Output: check the video output in this folder: agents-sdk-openai

Human in loop while streaming

Human-in-the-loop: Approve or reject tool calls

import "dotenv/config";
import { Agent, run } from "@openai/agents";

const agent = new Agent({
  name: "Storyteller",
  instructions:
    "You are a storyteller. You will be given a topic and you will tell a story about it.",
});

let stream = await run(
  agent,
  "What is the weather in San Francisco and Oakland?",
  { stream: true }
);
stream.toTextStream({ compatibleWithNodeStreams: true }).pipe(process.stdout);
await stream.completed;

// Human-in-the-loop: Approve or reject tool calls
console.log("\n\n\n stream.interruptions:", stream.interruptions);
while (stream.interruptions?.length) {
  console.log(
    "Human-in-the-loop: approval required for the following tool calls:"
  );
  const state = stream.state;
  for (const interruption of stream.interruptions) {
    const approved = confirm(
      `Agent ${interruption.agent.name} would like to use the tool ${interruption.rawItem.name} with "${interruption.rawItem.arguments}". Do you approve?`
    );
    if (approved) {
      state.approve(interruption);
    } else {
      state.reject(interruption);
    }
  }

  // Resume execution with streaming output
  stream = await run(agent, state, { stream: true });
  const textStream = stream.toTextStream({ compatibleWithNodeStreams: true });
  textStream.pipe(process.stdout);
  await stream.completed;
}

Output

Certainly! Here's a quick story about the weather in San Francisco and Oakland:

---

Once upon a recent afternoon, the cities of San Francisco and Oakland were like two slightly different personalities sharing a bay.

In San Francisco, the famous fog named Karl was feeling a little lazy. He lounged just offshore, sending wisps along the coastline. Downtown, it was cool and breezy, a gentle 61°F, perfect for a light hoodie. Residents bustled along the Embarcadero, their cheeks tinged pink from the crisp air.

A bridge away, Oakland basked under clearer skies. Sunshine poured over Lake Merritt, and the air held a comfortable warmth, about 68°F. Families picnicked while street musicians played jazz, and the late afternoon light made everything glow golden.

Despite sharing the same patch of the world, these two neighbors wore different weather, as they often do. But in both cities, the people looked up and smiled, enjoying the day in their own unique ways.

---

If you want a real-time weather update, let me know!
 stream.interruptions: []

Final Takeaway

OpenAI Agents SDK makes it easier to move from just using LLMs to building complete Agentic AI systems. By combining agents, tools, and workflows, developers can create intelligent applications that handle real-world tasks from simple chat interactions to complex multi-step autonomous flows. Start small, experiment with tools, and scale your agents step by step the SDK is designed to grow with your needs.

0
Subscribe to my newsletter

Read articles from MANOJ KUMAR directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

MANOJ KUMAR
MANOJ KUMAR

Haan Ji, I am Manoj Kumar a product-focused Full Stack Developer passionate about crafting and deploying modern web apps, SaaS solutions, and Generative AI applications using Node.js, Next.js, databases, and cloud technologies, with 10+ real-world projects delivered including AI-powered tools and business applications.