> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ai21.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Create run

## Request body

<ParamField body="input" type="string | object[]" required="false">
  A list of conversational turns, alternating between the user and the assistant, or a single instruction string.

  Please note that there are two different options for the input.

  <Accordion title="show possible types">
    Text input `string`\
    A plain instruction string for AI21 Maestro. Equivalent to a single message with the user role.\
    \
    Input messages `object []`\
    A list of message objects representing a multi-turn conversation alternating between the user and the assistant.

    <Accordion title="show fields">
      <ParamField body="role" type="string" required>
        The role of the entity that is creating the message. Allowed values include:

        `user` : A message is sent by an actual user. It represents the user's intent.

        `assistant` : A message is generated by the assistant.
      </ParamField>

      <ParamField path="content" type="string" required>
        The textual content of the message.
      </ParamField>
    </Accordion>
  </Accordion>
</ParamField>

<ParamField path="system_prompt" type="string" required>
  A high\_level instruction that defines AI21 Maestro's overall behavior, role, opreating systems and response style throughout the run.\
  \
  Common use cases include:\
  **Degining identity**: e.g "You are an expert financial analyst". \
  **Providing context**: e.g "Today's date is November 10, 2025". \
  **Guiding interactions**: e.g "if the user's question is vague, as a clatifying question before answering".

  <Info>
    **Deciding whether to use** `requirements` or  `system_prompt`\
    \
    To avoid conflicts and ensure predictable behavior, always prefer using `requirements` for output conditions, and make sure they don’t contradict the `system_prompt`.

    `system_prompt` defines the agent’s identity, tone, and core reasoning principles. It shapes how Maestro behaves throughout the entire run.

    `requirements`, on the other hand, specify the exact conditions the output must satisfy.
  </Info>
</ParamField>

<ParamField body="requirements" type="object[]">
  Explicit requirements for the output. The requirements can be in terms of content, style, format, genre, point of view, and various guardrails AI21 Maestro will allocate resources to maintain all requirements throughout the run. At the end of the run, the score for each requirement and the overall score will be returned. Users can specify up to 10 requirements.

  <Accordion title="Show properties">
    <ParamField body="name" type="string" required>
      The requirement's name, which allows users to reference it in their applications later.
    </ParamField>

    <ParamField body="description" type="string" required>
      The requirement's description in natural language. This will influence our result scoring and budget allocation. The maximum length for each description is 128 words.
    </ParamField>

    <ParamField path="is_mandatory" body="Default: false If set to true, and the associated requirement is not fully satisfied, the overall requirements_result score will be 0" type="boolean">
      Default: false.\
      If set to `true`, and the associated requirement is not fully satisfied, the overall requirements\_result score will be 0.
    </ParamField>
  </Accordion>

  Examples of requirements:

  * "Write up to 3 paragraphs"
  * "Output only the answer"
  * "Don't mention a word about the company's CEO"
  * "Use a friendly tone"

  <Note>
    **Avoid conflicting requirements**

    Conflicts may reduce run quality or prevent fulfillment.
  </Note>
</ParamField>

<ParamField path="tools" type="object[]">
  An array of objects. Each object describes a tool that AI21 Maestro may invoke during execution. The behavior and required fields vary depending on the tool’s `type`.

  <Accordion title="Show possible types">
    **MCP Tool** `object`\
    Use this tool type to allow AI21 Maestro to interact with external services through the Model Context Protocol (MCP). MCP enables dynamic discovery of available tools and resources provided by an MCP server, making integration more flexible and extensible.

    <Accordion title="Show fields">
      <ParamField path="type" type="string" required>
        The string has to be `mcp`.
      </ParamField>

      <ParamField path="server_label" type="string" required>
        Unique name for the MCP server within the session.
      </ParamField>

      <ParamField path="server_url" type="string" required>
        Fully qualified URL of the MCP server endpoint.
      </ParamField>

      <ParamField path="headers" type="object">
        Authentication headers (e.g., bearer tokens).
      </ParamField>

      <ParamField path="allowed_tools" type="string[]">
        List of tool names that Maestro can use. Must align with the tools exposed by the MCP server.\
        If not specified, all tools will be loaded.
      </ParamField>
    </Accordion>

    **HTTP Tool** `object`\
    Use this tool type to allow AI21 Maestro to perform HTTP POST requests to an external service.

    <Accordion title="Show fields">
      <ParamField path="type" type="string" required>
        The string has to be `http`.
      </ParamField>

      <ParamField path="function" type="object" required>
        Describes the callable function interface of the tool.

        <Accordion title="Show function fields">
          <ParamField path="name" type="string" required="false">
            A unique identifier for the tool. Should clearly reflect the action it performs.
          </ParamField>

          <ParamField path="description" type="string">
            An explanation of what the tool does and when it should be used.
          </ParamField>

          <ParamField path="parameters" type="object">
            A JSON Schema describing the input parameters this tool accepts.\
            Each parameter should preferably include a description.
          </ParamField>
        </Accordion>
      </ParamField>

      <ParamField path="endpoint" type="object" required>
        Defines how to construct the HTTP request.

        <Accordion title="Show endpoint fields">
          <ParamField path="url" type="string" required="false">
            The endpoint URL the tool should call.
          </ParamField>

          <ParamField path="headers" type="object">
            HTTP headers to include in the request, typically used for authorization or content-type declarations.
          </ParamField>
        </Accordion>
      </ParamField>
    </Accordion>

    <Note>
      Only `POST`requests are currently supported. \
      For more information on how the request is made, see the following example.
    </Note>

    **JSON Example**

    ```json theme={"system"}
    {
      "type": "http",
      "function": {
        "name": "getWeatherForecast",
        "description": "Fetches a 7-day weather forecast for a given location.",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "City or region to fetch weather for"
            }
          },
          "required": ["location"]
        }
      },
      "endpoint": {
        "url": "https://api.weatherapi.com/v1/forecast",
        "headers": {
          "Authorization": "Bearer YOUR_API_KEY"
        }
      }
    }
    ```

    **File Search Tool** `object`\
    When provided, this object defines filters that AI21 Maestro will apply whenever it performs a file search.

    <Accordion title="Show fields">
      <ParamField path="type" type="string" required>
        The string has to be `file_search`.
      </ParamField>

      <ParamField path="labels" type="string[]">
        Restrict file search to files with these labels.\
        If not provided, search is not restricted by label.
      </ParamField>

      <ParamField path="file_ids" type="string[]">
        Restrict file search to these file IDs.\
        If not provided, search is not restricted by file ID.
      </ParamField>
    </Accordion>

    **Web Search Tool** `object`\
    When provided, this object defines filters that AI21 Maestro will apply whenever it performs a web search.

    <Accordion title="Show fields">
      <ParamField path="type" type="string" required>
        The string has to be `web_search`.
      </ParamField>

      <ParamField path="urls" type="string[]">
        Restrict web search to the specified URL prefixes. The following formats are valid:

        1. `https://example.com` – limits to URLs that start with `www.example.com`
        2. `example.com` – limits to URLs that start with `www.example.com`
        3. `example.com/page` – limits to URLs that start with `www.example.com/page`
        4. `sub.example.com` – limits to URLs that start with the specified subdomain (e.g., `docs.example.com`, `blog.example.com`)

        <Note>
          If not provided, search is not restricted to specific domains.
        </Note>
      </ParamField>
    </Accordion>
  </Accordion>
</ParamField>

<ParamField body="models" type="string[]">
  defaults to null.

  Specify a single model to be used for the run. Choose from the following:

  **First-Party Models** Models hosted and managed by AI21:

  * `jamba-large`
  * `jamba-mini`

  **Third‑Party Models (Managed by AI21)** Models hosted by third-party providers but accessed through AI21’s API (no user API key required):

  * `claude-3-5-haiku`
  * `claude-4-sonnet`
  * `gemini-2.5-flash`
  * `gemini-2.5-flash-lite`
  * `gpt-4.1`
  * `gpt-4.1-mini`
  * `llama-33-70b-instruct`
  * `mistral-7b`
  * `mistral-8x7b`
  * `mistral-small`
  * `mistral-small-24B`
  * `qwen-qwq-32b`
  * `qwen3-235b-a22b-instruct-2507`

  **Third-Party Models (BYOK)**\
  Bring‑Your‑Own‑Key (BYOK) third‑party models: \
  Specify the ID of a third-party model configured on the [**3rd-Party Models page**](https://studio.ai21.com/v2?tab=third_party_models).

  These models require your own API key. AI21 uses your key to authenticate and access the model on your behalf. Supported providers include OpenAI, Anthropic, and Google.
</ParamField>

<ParamField body="budget" type="string">
  Controls how many resources AI21 Maestro allocates to fulfill a task, including the number of execution steps and the level of effort applied.

  The higher the budget, the more likely latency and execution costs will increase.\
  \
  **Accepted values**:

  * `low` -  One execution step is taken with minimal effort to fulfill the requirements.
  * `medium` - Multiple execution steps are taken with moderate effort to fulfill the requirements.
  * `high`  - Multiple execution strategies, each containing multiple execution steps, are used with maximum effort to fulfill the requirements.

  Defaults to `low` if not provided.
</ParamField>

<ParamField body="include" type="string[]">
  Specify which extra fields should be included in the output. If not provided, none of these fields will be included. Supported values:

  * `data_sources` — Includes the `data_sources` field in the output.
  * `requirements_result` — Includes detailed results for each requirement in the `requirements_result` field.
</ParamField>

<ParamField body="response_language" type="string | null">
  Controls the output language of AI21 Maestro responses.\
  Response language can be only one of the following: "arabic", "dutch", "english", "french", "german", "hebrew", "italian", "portuguese", "spanish".\
  \
  If not provided, the language is detected automatically, AI21 Maestro will respond in the same language as the input prompt unless a specific language is set.
</ParamField>

## Returns

[Run object](/reference/run-object)

<RequestExample>
  ```python Python theme={"system"}
  from ai21 import AI21Client
  from ai21.models.chat import ChatMessage

  client = AI21Client(api_key="YOUR_API_KEY")

  # Create and poll a Maestro run
  run = client.beta.maestro.runs.create_and_poll(
      input="Summarize today's major movements in global financial markets and explain possible reasons for these changes.",
      requirements=[
          {"name": "factual_accuracy",
              "description": "Base insights on verifiable data from reliable financial sources."},
          {"name": "clarity", "description": "Keep explanations concise and free of jargon."},
          {"name": "tone", "description": "Maintain a neutral, professional tone suitable for enterprise reporting."}
      ],
      tools=[
          {
              "type": "web_search",
              "urls": ["https://www.reuters.com/markets/", "https://finance.yahoo.com/"]
          }
      ],
      include=["requirements_result", "data_sources"],
      budget="medium"
  )

  # Print the generated analysis
  print("=== Financial Market Summary ===")
  print(run.result)
  print()

  # Print requirement evaluation
  print("=== Requirements Results ===")
  for req in run.requirements_result["requirements"]:
      print(f"- {req['name']}: {req['score']} ({req['reason']})")
  print()

  # Print data sources
  print("=== Data Sources ===")
  if hasattr(run, 'data_sources') and run.data_sources:
      if run.data_sources.get('web_search'):
          print("Web Search Results:")
          for result in run.data_sources['web_search']:
              print(f"  - {result.get('url')}")
  else:
      print("No data sources available")
  ```

  ```javascript Javascript theme={"system"}
  // TypeScript example using AI21 Labs TypeScript SDK
  // Install deps first: npm i ai21 ts-node typescript
  // If the import path differs in your SDK version, adjust it per the SDK docs.
  import { AI21} from "ai21";

  const apiKey = process.env.AI21_API_KEY;
  if (!apiKey) {
    throw new Error("AI21_API_KEY is not set. Please export it as an environment variable.");
  }

  const client = new AI21({
    apiKey,
  });

  const body = {
    input: [
      {
        role: "user",
        content:
          "Summarize today's major movements in global financial markets and explain possible reasons for these changes.",
      },
    ],
    requirements: [
      {
        name: "factual_accuracy",
        description:
          "Base insights on verifiable data from reliable financial sources.",
      },
      {
        name: "clarity",
        description: "Keep explanations concise and free of jargon.",
      },
      {
        name: "tone",
        description:
          "Maintain a neutral, professional tone suitable for enterprise reporting.",
      },
    ],
    tools: [
      {
        type: "web_search",
        urls: [
          "https://www.reuters.com/markets/",
          "https://finance.yahoo.com/",
        ],
      },
    ],
    budget: "low",
    include: ["requirements_result", "data_sources"],
  };

  async function main() {
    const result = await client.beta.maestro.runs.createAndPoll(body, {
      interval: 1000,
      timeout: 100000
    });
    console.log(JSON.stringify(result, null, 2));
  }

  main().catch((err) => {
    console.error(err);
    process.exit(1);
  });
  ```

  ```php PHP theme={"system"}
  <?php

  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api.ai21.com/studio/v1/maestro/runs',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_HTTPHEADER => array(
      'Authorization: Bearer YOUR_API_KEY_HERE',
      'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => '{
      "input": [
        {
          "role": "user",
          "content": "Summarize today\'s major movements in global financial markets and explain possible reasons for these changes."
        }
      ],
      "requirements": [
        {
          "name": "factual_accuracy",
          "description": "Base insights on verifiable data from reliable financial sources."
        },
        {
          "name": "clarity",
          "description": "Keep explanations concise and free of jargon."
        },
        {
          "name": "tone",
          "description": "Maintain a neutral, professional tone suitable for enterprise reporting."
        }
      ],
      "tools": [
        {
          "type": "web_search",
          "urls": [
            "https://www.reuters.com/markets/",
            "https://finance.yahoo.com/"
          ]
        }
      ]
    }'
  ));

  $response = curl_exec($curl);
  curl_close($curl);

  echo $response;
  ```

  ```bash cURL theme={"system"}
  curl --location --request POST 'https://api.ai21.com/studio/v1/maestro/runs' \
    --header 'Authorization: Bearer <YOUR_API_KEY>' \
    --header 'Content-Type: application/json' \
    --data '{
      "input": [
        {
          "role": "user",
          "content": "Summarize today'\''s major movements in global financial markets and explain possible reasons for these changes."
        }
      ],
      "requirements": [
        {
          "name": "factual_accuracy",
          "description": "Base insights on verifiable data from reliable financial sources."
        },
        {
          "name": "clarity",
          "description": "Keep explanations concise and free of jargon."
        },
        {
          "name": "tone",
          "description": "Maintain a neutral, professional tone suitable for enterprise reporting."
        }
      ],
      "tools": [
        {
          "type": "web_search",
          "urls": [
            "https://www.reuters.com/markets/",
            "https://finance.yahoo.com/"
          ]
        }
      ],
      "budget": "medium",
      "include": ["requirements_result", "data_sources"]
    }'
  ```

  ```java Java theme={"system"}
  HttpResponse<String> response = Unirest.post("https://api.ai21.com/studio/v1/maestro/runs")
    .header("Content-Type", "application/json")
    .body("{\n  \"input\": [\n    {\n      \"role\": \"<string>\",\n      \"content\": \"<string>\"\n    }\n  ],\n  \"requirements\": [\n    {\n      \"name\": \"<string>\",\n      \"description\": \"<string>\"\n    }\n  ],\n  \"tool_resources\": {\n    \"file_search\": {\n      \"labels\": [\n        \"<string>\"\n      ],\n      \"file_ids\": [\n        \"<string>\"\n      ]\n    },\n    \"web_search\": {\n      \"urls\": [\n        \"<string>\"\n      ]\n    }\n  },\n  \"models\": [\n    \"<string>\"\n  ],\n  \"budget\": \"<string>\",\n  \"include\": [\n    \"<string>\"\n  ],\n  \"response_language\": {}\n}")
    .asString();
  ```

  ```json JSON theme={"system"}
  {
    "input": [
      {
        "role": "user",
        "content": "Summarize today's major movements in global financial markets and explain possible reasons for these changes."
      }
    ],
    "requirements": [
      {
        "name": "factual_accuracy",
        "description": "Base insights on verifiable data from reliable financial sources."
      },
      {
        "name": "clarity",
        "description": "Keep explanations concise and free of jargon."
      },
      {
        "name": "tone",
        "description": "Maintain a neutral, professional tone suitable for enterprise reporting."
      }
    ],
    "tools": [
      {
        "type": "web_search",
        "urls": [
          "https://www.reuters.com/markets/",
          "https://finance.yahoo.com/"
        ]
      }
    ],
    "budget": "medium",
    "include": ["requirements_result", "data_sources"]
  }
  ```
</RequestExample>
