# ⌨︎ DIY

**Running Swarm.js**

Start by creating a Swarm client that interacts with OpenAI’s API.

Copy

Copy

```
const { Swarm } = require('openai-swarm-node');

const client = new Swarm(process.env.OPENAI_API_KEY);
```

**`client.run()`**

The `run()` function in Swarm.js is similar to OpenAI's `chat.completions.create()` function but with additional features like agent function execution, handoffs, context variables, and multi-turn conversations.

**Arguments**

ArgumentTypeDescriptionDefault

**agent**

`Agent`

The (initial) agent to be called.

(required)

**messages**

`Array`

A list of message objects, similar to [Chat Completions API messages](https://platform.openai.com/docs/api-reference/chat/create#chat-create-messages).

(required)

**contextVariables**

`Object`

Additional context variables available to agents.

`{}`

**maxTurns**

`Number`

Maximum number of conversational turns before returning.

`Infinity`

**debug**

`Boolean`

Enables debug logging if `true`.

`false`

**`Response` Fields**

FieldTypeDescription

**messages**

`Array`

The list of messages generated during the conversation.

**agent**

`Agent`

The last agent to handle the conversation.

**contextVariables**

`Object`

The most up-to-date context variables, including any changes during the conversation.

**Agents**

An `Agent` encapsulates instructions and functions (tools). These agents drive the conversation and can decide whether to hand off to another agent.

Copy

Copy

```
const agentA = new Agent({
  name: "Agent A",
  instructions: "You are a helpful agent.",
});
```

**Functions**

Functions enable agents to perform actions like processing transactions, looking up information, or transferring control to other agents. Functions are called when the agent needs to perform a specific task.

Copy

Copy

```
const transferToAgentB = () => agentB;

const agentA = new Agent({
  name: "Agent A",
  instructions: "You are a helpful agent.",
  tools: [{ name: 'transferToAgentB', fn: transferToAgentB }],
});
```

**Handoffs and Context Variables**

Agents can transfer control to other agents or update `contextVariables` based on the conversation flow.

Copy

Copy

```
const salesAgent = new Agent({ name: "Sales Agent" });

const agent = new Agent({
  functions: [
    () => new Result({ agent: salesAgent, contextVariables: { department: "sales" } }),
  ],
});
```

**Function Schemas**

Swarm.js automatically converts functions into JSON schemas, allowing OpenAI’s API to call the appropriate function based on the tool name.

Copy

Copy

```
function lookUpItem(searchQuery) {
    /**
     * @description Use to find item ID. Search query can be a description or keywords.
     * @param {string} searchQuery - Description or keywords to search for the item.
     * @returns {string} - The found item ID.
     */

    return console.log(`Searching for item: ${searchQuery}`);
}
```

**Streaming**

You can enable streaming in Swarm.js to receive real-time responses from agents.

Copy

Copy

```
const stream = client.run({ agent, messages, stream: true });
for await (const chunk of stream) {
    console.log(chunk);
}
```

**Evaluations**

Swarm.js supports various evaluation methods to test and validate your multi-agent systems. You can find example evaluations in the `/examples` directory.

**Utils**

Use the `run_demo_loop` utility to test your agents interactively in a REPL environment.

Copy

Copy

```
const { run_demo_loop } = require('openai-swarm-node/utils');

run_demo_loop(agent);
```

***

**Core Contributors**

* Pulkit Garg (Node.js adaptation)
* OpenAI (original Python framework)

***

This README now emphasizes that **Swarm.js** is a **Node.js implementation** of OpenAI Swarm, while maintaining a high standard for documentation and usage clarity.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://eralize.gitbook.io/eralize-ai/undefined/diy.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
