> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.spyglass.so/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.spyglass.so/_mcp/server.

# Create an agent run

POST https://api.spyglass.so/v2/agent/runs
Content-Type: application/json

Start a Spyglass agent run. The run id is the chat thread id.
Pass `outputSchema` to get that JSON on `structured` when the run completes.
The root `type` must be `"object"`. Each property can be a string, number, integer, boolean, array, or object.
`model` is `default` or `pro`.
Poll GET /agent/runs/\{id} until `status` is `completed` or `failed`.

Limited to 20 requests per minute per user.
The create call is free. The run is billed from model usage when it finishes.

Reference: https://docs.spyglass.so/api-reference/spyglass-api/agent/create-agent-run

## Authentication

- `Authorization` header (bearer token, required) — An API key from Settings → API, prefixed sg_live_.

## Request

### Body (application/json)

This endpoint expects an object.

- `query` (string, required)
- `outputSchema` (AgentRunsPostRequestBodyContentApplicationJsonSchemaOutputSchema, optional) — JSON Schema for `structured`. The root `type` must be `"object"`. Each property can be a string, number, integer, boolean, array, or object.
- `systemPrompt` (string, optional)
- `effort` (enum, optional, default: medium)
  - Allowed values: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`
- `model` (enum, optional, default: default)
  - Allowed values: `default`, `pro`

## Response

### 200

The queued run.

- `id` (string, required)
- `status` (enum, required)
  - Allowed values: `queued`
- `createdAt` (datetime, required)

## Errors

### 400 Bad Request Error

The request body or query string failed validation. `details` lists the offending fields.

- `error` (ErrorError, required)

### 401 Unauthorized Error

The API key is missing, malformed, unknown, or revoked.

- `error` (ErrorError, required)

### 402 Payment Required Error

The team's monthly credits are exhausted.

- `error` (ErrorError, required)

### 403 Forbidden Error

The team's subscription is inactive, or your membership of it has ended.

- `error` (ErrorError, required)

### 405 Method Not Allowed Error

The HTTP method is not supported on this path. The Allow header lists what is. HEAD is refused on metered GET endpoints because it would be billed without returning data.

- `error` (ErrorError, required)

### 429 Too Many Requests Error

Too many requests for this user on this endpoint. Carries a Retry-After header. The per-minute limit is stated on the operation.

- `error` (ErrorError, required)

### 500 Internal Server Error

Something went wrong on our side.

- `error` (ErrorError, required)

## Types

### AgentRunsPostRequestBodyContentApplicationJsonSchemaOutputSchema

JSON Schema for `structured`. The root `type` must be `"object"`. Each property can be a string, number, integer, boolean, array, or object.

- `type` (enum, required)
  - Allowed values: `string`, `number`, `integer`, `boolean`, `array`, `object`
- `properties` (map from string to AgentRunsPostRequestBodyContentApplicationJsonSchemaOutputSchema, optional) — Fields of the structured result.
- `required` (list of string, optional) — Property names the result must include.

### ErrorError

- `code` (enum, required)
  - Allowed values: `invalid_request`, `invalid_api_key`, `payload_too_large`, `out_of_credits`, `membership_ended`, `subscription_inactive`, `brand_not_found`, `not_found`, `method_not_allowed`, `rate_limited`, `not_implemented`, `internal_error`
- `message` (string, required)
- `details` (list of ErrorErrorDetailsItems, optional)

### ErrorErrorDetailsItems

- `path` (string, required)
- `message` (string, required)

## Examples

**Request**

```json
{
  "query": "string"
}
```

**Response**

```json
{
  "id": "string",
  "status": "queued",
  "createdAt": "2024-01-15T09:30:00Z"
}
```

**SDK Code**

```python
import requests

url = "https://api.spyglass.so/v2/agent/runs"

payload = { "query": "string" }
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.spyglass.so/v2/agent/runs';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"query":"string"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.spyglass.so/v2/agent/runs"

	payload := strings.NewReader("{\n  \"query\": \"string\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.spyglass.so/v2/agent/runs")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"query\": \"string\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.spyglass.so/v2/agent/runs")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"query\": \"string\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.spyglass.so/v2/agent/runs', [
  'body' => '{
  "query": "string"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.spyglass.so/v2/agent/runs");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"query\": \"string\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["query": "string"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.spyglass.so/v2/agent/runs")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```