Getting Started with OpenAI Agents in JavaScript

Introduction & Lesson Overview

Welcome to the first lesson of our course, Getting Started with OpenAI Agents in JavaScript. In this lesson, you’ll take your very first steps with the OpenAI Agents SDK. This course is designed for developers who want to build intelligent, task-oriented agents using JavaScript. No prior experience with the SDK is required—we’ll guide you through each concept with clear explanations and practical, hands-on examples.

By the end of this lesson, you’ll understand what an OpenAI agent is, how it differs from a simple chat-based language model, and how to create and run your own agent using the OpenAI Agents SDK. This foundational knowledge will prepare you for more advanced topics and hands-on exercises in the rest of the course.

What is an Agent?

An agent, in this context, is much more than just a chatbot. While traditional chat LLMs (like early versions of ChatGPT) simply respond to prompts with text, agents are designed to perform specific tasks, follow detailed instructions, and even use tools or delegate work to other agents.

For example, a chat LLM might answer, “What’s the weather like in Paris?” with a general response based on its training data. An agent, on the other hand, could be set up as a travel assistant, given instructions to always provide up-to-date information, and even use external APIs to fetch the latest weather. Agents are configurable, can be given roles, and can be equipped with tools and safety checks, making them much more powerful and reliable for real-world applications.

Overview of the OpenAI Agents SDK

The OpenAI Agents SDK is a library that helps you easily build, manage, and run AI agents powered by large language models. With this SDK, you can create agents that do much more than just chat—they can reason, use tools, interact with other agents, and perform complex, multi-step tasks in a structured way. The SDK’s simple and flexible design makes it easy to prototype and deploy agentic applications quickly. For more information, you can visit the official OpenAI Agents SDK Documentation.

Throughout this course, you’ll be working in the CodeSignal environment, where everything is already set up for you—no installation or API key configuration needed. You can focus entirely on learning and experimenting with the code.

Local Setup Steps

If you’d like to run the code examples on your own machine later, you’ll need to install the SDK and set your OpenAI API key. Here’s how you can get started in a Node.js environment:

  1. Install the SDK using npm or yarn:

    npm install @openai/agents
    # or
    yarn add @openai/agents
  2. Set your OpenAI API key as an environment variable:

    You can do this in your terminal before running your code:

    # On Linux/macOS
    export OPENAI_API_KEY=your_openai_api_key
    
    # On Windows (Command Prompt)
    set OPENAI_API_KEY=your_openai_api_key
    
    # On Windows (PowerShell)
    $env:OPENAI_API_KEY="your_openai_api_key"

Alternatively, you can use a .env file and a package like dotenv to load environment variables automatically.

Note: None of these setup steps are necessary while working through this course—the CodeSignal environment already has a valid API key configured for you.

Understanding the Agent Loop

A key feature of the OpenAI Agents SDK is the agent loop. This is the process that allows an agent to handle complex tasks step by step. When you give an agent an input, it processes the input using its instructions and the underlying language model. If the agent needs to use a tool or hand off the task to another agent, the loop takes care of that, running each step until a final answer is ready.

Think of the agent loop as a conversation between the agent and its environment. The agent keeps working — using tools, asking for help, or refining its answer — until it can give you a complete response. This makes agents much more flexible and capable than simple chatbots, which only respond once and cannot take further actions.

Creating Your First Agent

Let’s see how to create a simple agent using the OpenAI Agents SDK for JavaScript. The main class you’ll use is called Agent.

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

// Define a simple agent
const agent = new Agent({
  name: 'Travel Genie',
  instructions: 
    'You are Travel Genie, a friendly and knowledgeable travel assistant. ' +
    'Recommend exciting destinations and offer helpful travel tips.'
});

In this code, we create an agent named “Travel Genie.” The instructions tell the agent to act as a travel assistant, be friendly, and give personalized suggestions. At its most basic, you need to provide two key parameters:

  • The name property serves as a unique identifier for your agent, making it easier to reference when working with multiple agents.
  • The instructions property acts as the system prompt, defining the agent’s role and behavior guidelines.

When you create an agent with just these parameters, it will use the default language model configured in the SDK.

Specifying a Language Model

For more control over your agent’s capabilities, you can specify which language model it should use:

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

// Define an agent with a specific model
const agent = new Agent({
  name: 'Travel Genie',
  instructions: 
    'You are Travel Genie, a friendly and knowledgeable travel assistant. ' +
    'Recommend exciting destinations and offer helpful travel tips.',
  model: 'gpt-4.1' // Specify which model to use
});

By default, the SDK will use models provided by OpenAI. For example, gpt-4.1 is a cost-effective model optimized for agentic workflows. You can also specify other OpenAI models, such as gpt-4o for low latency and strong performance, or o4-mini and o3 for advanced reasoning and complex problem-solving. In this course, we’ll focus exclusively on using OpenAI models to keep things simple and consistent.

Tune Model Parameters

To fine-tune your agent's response behavior in JavaScript, you can adjust various model parameters using the modelSettings property. This property accepts an object where you can configure settings such as temperature and maxTokens.

Here's how you can define an agent with customized model settings:

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

// Define an agent with customized model settings
const agent = new Agent({
  name: 'Travel Genie',
  instructions: 'You are Travel Genie, a friendly and knowledgeable travel assistant. Recommend exciting destinations and offer helpful travel tips.',
  model: 'gpt-4.1',
  modelSettings: {
    temperature: 0.7, // Controls creativity (0-2)
    maxTokens: 500    // Limits response length
  }
});

In this example:

  • temperature: Controls randomness in responses. The valid range is 0 to 2. Lower values (e.g., 0.2) produce more focused, deterministic outputs, while higher values (e.g., 1.0 or above) generate more creative, varied responses.

  • maxTokens: Caps the length of the agent's response to the specified number of tokens. This is primarily used to control costs, as API usage is billed per token. The model is not aware of this limit while generating its output, so if the response is cut off, it may end abruptly or mid-sentence.

By adjusting these settings, you can tailor your agent's behavior to better suit your specific application requirements.

Running the Agent

Once you have defined your agent, you can run it using the run utility function provided by the SDK. The OpenAI Agents SDK for JavaScript is built on asynchronous operations, so all agent runs return promises that must be awaited. The run function is the simplest way to execute an agent and get its response.

Here's how you can run the agent with a user prompt:

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

// Define the agent
const agent = new Agent({
  name: 'Travel Genie',
  instructions: 
    'You are Travel Genie, a friendly and knowledgeable travel assistant. ' +
    'Recommend exciting destinations and offer helpful travel tips.',
  model: 'gpt-4.1'
});

// Run the agent with an input prompt
const result = await run(
  agent,
  "What's your top recommendation for adventure seekers?"
);

The run function takes three parameters:

  • The agent instance to execute
  • The user's input (as a string in this simple case)
  • An optional configuration object (which we'll not explore in this lesson)

Since run is an async function, you must use await to wait for the result. The function handles the entire agent loop internally and returns a RunResult object containing the agent's final response and other execution details.

Running the Agent with Runner

Alternatively, you can use the Runner class directly with its static run method. This approach gives you the same functionality as the run utility function:

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

// Define the agent
const agent = new Agent({
  name: 'Travel Genie',
  instructions: 
    'You are Travel Genie, a friendly and knowledgeable travel assistant. ' +
    'Recommend exciting destinations and offer helpful travel tips.',
  model: 'gpt-4.1'
});

// Run the agent using the Runner class
const result = await Runner.run(
  agent,
  "What's your top recommendation for adventure seekers?"
);

The Runner.run static method works identically to the run utility function. In fact, the run function is just a convenient wrapper around Runner.run. Both approaches use a default runner instance behind the scenes.

Creating and Using a Runner Instance

For more control over the execution environment, you can create your own Runner instance. This approach is particularly useful in applications where you want to:

  • Reuse the same runner configuration across multiple agent runs
  • Configure global settings that apply to all agents run through that runner
  • Manage resources more efficiently in long-running applications

Here's how to create and use a Runner instance:

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

// Define the agent
const agent = new Agent({
  name: 'Travel Genie',
  instructions: 
    'You are Travel Genie, a friendly and knowledgeable travel assistant. ' +
    'Recommend exciting destinations and offer helpful travel tips.',
  model: 'gpt-4.1'
});

// Create a Runner instance
const runner = new Runner();

// Run the agent
const result = await runner.run(
  agent,
  "What's your top recommendation for adventure seekers?"
);

Creating your own Runner instance is especially beneficial in production applications where you might want to configure specific settings, manage multiple agents, or optimize resource usage. The runner can be created once and reused throughout your application's lifecycle.

How Agents are Executed

All three approaches—using run, Runner.run, or a Runner instance—execute the same agent loop we discussed earlier:

  1. The agent processes the input using its instructions and the specified language model.
  2. The language model produces its output.
  3. If the model returns a finalOutput, the loop ends and returns the result.
  4. If the model delegates to another agent or needs to use tools, the loop continues, handling each step until a final output is reached.

This loop structure is what gives agents their power to handle complex, multi-step tasks that might require different capabilities or external information.

Extracting and Interpreting the Final Output

After running the agent, you’ll get a result object. The most important part of this object is the finalOutput property, which contains the agent’s final answer.

To see the output, you can print it like this:

// Print the agent's final output
console.log(result.finalOutput);

If you run the full example, the output might look like this:

Absolutely—there’s a world of excitement out there! For adventure seekers, one of my **top recommendations** is **New Zealand**.

### Why New Zealand?
- **Epic Landscapes:** From glaciers and fjords to volcanoes and rainforests, the scenery is unbeatable.
- **Thrill Activities:** Try bungee jumping off the Kawarau Bridge, skydiving with views of lakes and peaks, or ziplining through lush forests.
- **World-Class Hiking:** Walk the famous Tongariro Alpine Crossing or explore the Milford Track’s dramatic beauty.
- **Water Sports:** Go white-water rafting, jet boating, or surfing on wild coastlines.
- **Lord of the Rings Vibes:** Explore filming locations for your very own Middle-earth adventure.

### Additional Hotspots for Adventure:
- **Patagonia, Chile & Argentina:** Trekking, ice climbing, and horseback riding through jaw-dropping wilderness.
- **Costa Rica:** Ziplining, surfing, canyoning, and wildlife reserves in a compact, friendly country.
- **Iceland:** Glacier hikes, ice cave tours, and volcano trekking under the midnight sun or northern lights.
- **South Africa:** Shark cage diving, bungee jumping off Bloukrans Bridge, and world-class safari.

**Travel Tip:** Always check local safety guidelines and consider booking tours with reputable, eco-friendly companies for safe and sustainable adventures.

Want more details about any of these spots or help planning your trip? Just let me know!

This output shows how the agent follows its instructions, providing an enthusiastic and tailored recommendation. In real-world applications, you can use this output to power chatbots, virtual assistants, or any system that needs intelligent, role-based responses.

Lesson Summary & Next Steps

In this lesson, you learned what OpenAI agents are and how they differ from simple chat LLMs. You explored the agent loop, which allows agents to handle complex tasks step by step. You discovered how to create an agent with a specific role and instructions, and most importantly, you learned three different ways to run agents asynchronously: using the run utility function, the Runner.run static method, and creating your own Runner instance. You also saw how to extract and interpret the final output from the agent's response — all using JavaScript and the OpenAI Agents SDK.

You are now ready to practice these foundational skills with hands-on exercises. In the next part of the course, you'll experiment with creating your own agents, running them in different scenarios, and exploring which approach works best for your use cases. Remember, on CodeSignal, all the necessary libraries are pre-installed and the API key is already configured, so you can focus entirely on learning and building. Let's get started!

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