> **Building with AI coding agents?** Install the authstack plugin with one command. This equips your agent with accurate Scalekit implementation patterns.
>
> **Recommended** (the `-y` flags skip prompts, so the command runs without an interactive terminal):
> ```bash
> npx -y @scalekit-inc/cli setup -y
> ```
>
> Global:
> ```bash
> npm install -g @scalekit-inc/cli
> scalekit setup -y
> ```
>
> Supports Claude Code, Cursor, GitHub Copilot, Codex + skills for other Agent Skills-compatible agents in `~/.agents/skills`.
> Skills: integrate-agentkit, implement-saaskit, add-mcp-oauth, implement-sso, implement-scim.
> [Full setup guide](https://docs.scalekit.com/dev-kit/build-with-ai/)

---

# OpenAI

Build an OpenAI agent with Scalekit-authenticated tools. Convert Scalekit's tool schemas to OpenAI's function calling format in one step.
Build an agent using OpenAI's GPT models that reads a user's Gmail inbox. Scalekit's tool schemas use `input_schema`: rename it to `parameters` and wrap it in OpenAI's function format.

## Before you start

- Create a Gmail connection in **AgentKit** > **Connections**. The samples use the connection name `gmail`, so change it if yours differs. See [Set up a connection](/agentkit/connections/).
- Have the `.env` file from the [Quickstart](/agentkit/quickstart/), and add your OpenAI API key as `OPENAI_API_KEY` to it.
- The samples load `.env` with `load_dotenv()` from `python-dotenv` in Python, and `import 'dotenv/config'` in Node.js.

## Install

  **Python**

  ```sh
  pip install scalekit-sdk-python python-dotenv openai
  ```

  **Node.js**

  ```sh
  npm install @scalekit-sdk/node openai dotenv
  ```

For Node.js, save the code in a `.mts` file, such as `agent.mts`, and run it with `npx tsx agent.mts`. The `.mts` extension makes the file an ES module, so it can use top-level `await`.

## Initialize

  **Python**

  ```python
  import os, json
  import scalekit.client
  from dotenv import load_dotenv
  from openai import OpenAI
  from google.protobuf.json_format import MessageToDict

  load_dotenv()

  scalekit_client = scalekit.client.ScalekitClient(
      client_id=os.getenv("SCALEKIT_CLIENT_ID"),
      client_secret=os.getenv("SCALEKIT_CLIENT_SECRET"),
      env_url=os.getenv("SCALEKIT_ENVIRONMENT_URL"),
  )
  actions = scalekit_client.actions
  client = OpenAI()
  ```

  **Node.js**

  ```typescript
  import 'dotenv/config';
  import { ScalekitClient } from '@scalekit-sdk/node';
  import OpenAI from 'openai';

  const scalekit = new ScalekitClient(
    process.env.SCALEKIT_ENVIRONMENT_URL!,
    process.env.SCALEKIT_CLIENT_ID!,
    process.env.SCALEKIT_CLIENT_SECRET!,
  );
  const openai = new OpenAI();
  ```

## Connect the user to Gmail

  **Python**

  ```python
  # Connect the user's Gmail account, and wait until it's ACTIVE before calling tools
  connection_name = "gmail"
  identifier = "user_123"  # your app's unique user ID

  response = actions.get_or_create_connected_account(
      connection_name=connection_name, identifier=identifier
  )
  if response.connected_account.status != "ACTIVE":
      link = actions.get_authorization_link(
          connection_name=connection_name, identifier=identifier
      )
      print("Authorize Gmail:", link.link)
      input("Press Enter after authorizing...")
      # Fetch the account again to pick up the new status
      response = actions.get_or_create_connected_account(
          connection_name=connection_name, identifier=identifier
      )

  if response.connected_account.status != "ACTIVE":
      raise RuntimeError(
          f"Gmail is {response.connected_account.status}, not ACTIVE. Authorize it and run again."
      )
  ```

  **Node.js**

  ```typescript
  import { createInterface } from 'node:readline/promises';
  import { ConnectorStatus } from '@scalekit-sdk/node';

  // Connect the user's Gmail account, and wait until it's ACTIVE before calling tools
  const connectionName = 'gmail';
  const identifier = 'user_123'; // your app's unique user ID

  let { connectedAccount } = await scalekit.actions.getOrCreateConnectedAccount({
    connectionName,
    identifier,
  });
  if (connectedAccount?.status !== ConnectorStatus.ACTIVE) {
    const { link } = await scalekit.actions.getAuthorizationLink({ connectionName, identifier });
    console.log('Authorize Gmail:', link);
    const rl = createInterface({ input: process.stdin, output: process.stdout });
    await rl.question('Press Enter after authorizing...');
    rl.close();
    // Fetch the account again to pick up the new status
    ({ connectedAccount } = await scalekit.actions.getOrCreateConnectedAccount({
      connectionName,
      identifier,
    }));
  }

  if (connectedAccount?.status !== ConnectorStatus.ACTIVE) {
    throw new Error(`Gmail is not ACTIVE (status ${connectedAccount?.status}). Authorize it and run again.`);
  }
  ```

See [Authorize a user](/agentkit/tools/authorize/) for production auth handling.

## Run the agent

Fetch tools scoped to this user, convert to OpenAI's function format, then run the tool-calling loop. [Use built-in tools](/agentkit/tools/scalekit-optimized-tools/) explains the scoped tool list, paging past 100 tools, and how to read `data` when the app returns an error.

  **Python**

  ```python
  # Fetch and convert tools to OpenAI format
  scoped_response, _ = actions.tools.list_scoped_tools(
      identifier="user_123",
      filter={"connection_names": ["gmail"]},
      page_size=100,  # up to 100 tools per page; page with next_page_token for more
  )
  llm_tools = [
      {
          "type": "function",
          "function": {
              "name": MessageToDict(t.tool).get("definition", {}).get("name"),
              "description": MessageToDict(t.tool).get("definition", {}).get("description", ""),
              "parameters": MessageToDict(t.tool).get("definition", {}).get("input_schema", {}),
          },
      }
      for t in scoped_response.tools
  ]

  # Run the agent loop
  messages = [{"role": "user", "content": "Fetch my last 5 unread emails and summarize them"}]

  while True:
      response = client.chat.completions.create(
          model="gpt-4o",
          tools=llm_tools,
          messages=messages,
      )
      message = response.choices[0].message
      if not message.tool_calls:
          print(message.content)
          break

      messages.append(message)
      for tc in message.tool_calls:
          result = actions.execute_tool(
              tool_name=tc.function.name,
              identifier="user_123",
              connection_name="gmail",
              tool_input=json.loads(tc.function.arguments),
          )
          messages.append({
              "role": "tool",
              "tool_call_id": tc.id,
              "content": str(result.data),
          })
  ```

  **Node.js**

  ```typescript
  // Fetch and convert tools to OpenAI format
  const { tools } = await scalekit.tools.listScopedTools('user_123', {
    filter: { connectionNames: ['gmail'] },
    pageSize: 100, // up to 100 tools per page; page with nextPageToken for more
  });
  // Tool definitions are typed as generic JSON, so read each field explicitly
  const definitions = tools.flatMap((t) => (t.tool?.definition ? [t.tool.definition] : []));
  const llmTools: OpenAI.ChatCompletionTool[] = definitions.map((definition) => ({
    type: 'function',
    function: {
      name: String(definition.name),
      description: String(definition.description ?? ''),
      parameters: definition.input_schema as OpenAI.FunctionParameters,
    },
  }));

  // Run the agent loop
  const messages: OpenAI.ChatCompletionMessageParam[] = [
    { role: 'user', content: 'Fetch my last 5 unread emails and summarize them' },
  ];

  while (true) {
    const response = await openai.chat.completions.create({
      model: 'gpt-4o',
      tools: llmTools,
      messages,
    });
    const message = response.choices[0].message;
    if (!message.tool_calls?.length) {
      console.log(message.content);
      break;
    }
    messages.push(message);
    for (const tc of message.tool_calls) {
      if (tc.type !== 'function') continue; // only function tools are registered
      const result = await scalekit.actions.executeTool({
        toolName: tc.function.name,
        identifier: 'user_123',
        connector: 'gmail',
        toolInput: JSON.parse(tc.function.arguments),
      });
      messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result.data) });
    }
  }
  ```

## Use the Responses API

OpenAI's [Responses API](https://platform.openai.com/docs/api-reference/responses) is a stateful alternative to Chat Completions. Instead of managing conversation history yourself, you pass `previous_response_id` to continue a session. It takes tools in a flat shape, `{type, name, description, parameters}`, without the `function` wrapper that Chat Completions uses, so convert the tools first.

> note: Using a proxy or gateway
>
> The Responses API works with an OpenAI API key. Many OpenAI-compatible proxies and gateways support only Chat Completions, so check yours before you switch, or use the Chat Completions loop above.

  **Python**

  ```python
  # Responses API tools are flat: no "function" wrapper.
  # strict=False because Scalekit schemas don't follow strict mode's rules.
  response_tools = [{"type": "function", **t["function"], "strict": False} for t in llm_tools]

  response = client.responses.create(
      model="gpt-4o",
      input="Fetch my last 5 unread emails and summarize them",
      tools=response_tools,
  )

  while any(item.type == "function_call" for item in response.output):
      tool_results = [
          {
              "type": "function_call_output",
              "call_id": item.call_id,
              "output": str(actions.execute_tool(
                  tool_name=item.name,
                  identifier="user_123",
                  connection_name="gmail",
                  tool_input=json.loads(item.arguments),
              ).data),
          }
          for item in response.output
          if item.type == "function_call"
      ]
      response = client.responses.create(
          model="gpt-4o",
          previous_response_id=response.id,
          input=tool_results,
          tools=response_tools,
      )

  for item in response.output:
      if item.type == "message":
          print(item.content[0].text)
  ```

  **Node.js**

  ```typescript
  // Responses API tools are flat: no `function` wrapper.
  // strict: false because Scalekit schemas don't follow strict mode's rules.
  const responseTools: OpenAI.Responses.FunctionTool[] = definitions.map((definition) => ({
    type: 'function',
    name: String(definition.name),
    description: String(definition.description ?? ''),
    parameters: definition.input_schema as Record<string, unknown>,
    strict: false,
  }));

  let response = await openai.responses.create({
    model: 'gpt-4o',
    input: 'Fetch my last 5 unread emails and summarize them',
    tools: responseTools,
  });

  while (response.output.some(item => item.type === 'function_call')) {
    const toolResults = await Promise.all(
      response.output
        .filter(item => item.type === 'function_call')
        .map(async item => {
          const result = await scalekit.actions.executeTool({
            toolName: item.name,
            identifier: 'user_123',
            connector: 'gmail',
            toolInput: JSON.parse(item.arguments),
          });
          return {
            type: 'function_call_output' as const,
            call_id: item.call_id,
            output: JSON.stringify(result.data),
          };
        })
    );
    response = await openai.responses.create({
      model: 'gpt-4o',
      previous_response_id: response.id,
      input: toolResults,
      tools: responseTools,
    });
  }

  const message = response.output.find(item => item.type === 'message');
  if (message?.type === 'message') {
    for (const part of message.content) {
      if (part.type === 'output_text') console.log(part.text);
    }
  }
  ```

## Use MCP instead

If you prefer the MCP approach, connect your OpenAI agent via the [Vercel AI SDK + MCP](/agentkit/examples/vercel-ai#use-mcp-instead) or LangChain's MCP client with a Scalekit-generated URL. See [Virtual MCP servers](/agentkit/mcp/overview/) for the URL setup.

## Next

  - [Manage connected accounts](/agentkit/connected-accounts/): Check an account's status and ask users to reconnect.
  - [AgentKit launch checklist](/agentkit/advanced/launch-checklist/): Everything to finish before real users connect.

## API reference

The endpoints this page's code calls, with every field and the SDK method for each:

- `POST` [Execute a tool](https://docs.scalekit.com/agentkit/reference/tools/execute-a-tool.md)
- `GET` [List a user's scoped tools](https://docs.scalekit.com/agentkit/reference/tools/list-scoped-tools.md)


---

## More Scalekit documentation

| Resource | What it contains | When to use it |
|----------|-----------------|----------------|
| [/llms.txt](/llms.txt) | Structured index with routing hints per product area | Start here — find which documentation set covers your topic before loading full content |
| [/llms-full.txt](/llms-full.txt) | Complete documentation for all Scalekit products in one file | Use when you need exhaustive context across multiple products or when the topic spans several areas |
| [sitemap-0.xml](https://docs.scalekit.com/sitemap-0.xml) | Full URL list of every documentation page | Use to discover specific page URLs you can fetch for targeted, page-level answers |
