> For a complete index of all SignalWire documentation pages, fetch https://signalwire.com/docs/llms.txt

# Send AI chat methods

POST https://%7BYour_Space_Name%7D.signalwire.com/api/ai/chat
Content-Type: application/json

Hold a text conversation with an AI agent. All six methods travel over this endpoint in a
JSON-RPC 2.0 body. Put the method name in `method` and its arguments in `params`.

Your agent is an SWML document you serve, and `config_url` is where you serve it. A
conversation is a series of turns addressed by an `id` you choose. A turn is one user message
and the agent's reply, including any tool calls made along the way. One request runs one turn.

## Methods

| Method | Description |
|---|---|
| `create_conversation` | Create a conversation, or reset an existing one |
| `chat` | Send a message and receive the agent's reply |
| `end_conversation` | End the conversation and trigger post-processing |
| `delete` | Remove the conversation, with no post-processing |
| `chat_log` | Read the conversation back |
| `summarize` | Generate a summary on demand |

#### Permissions

The API token used to authenticate must have the following scope(s) enabled to make a successful request: _Chat_.

[Learn more about API scopes](/docs/platform/your-signalwire-api-space).

Reference: https://signalwire.com/docs/apis/rest/ai-chat/chat-methods

## Authentication

- `Authorization` header (basic auth, required) — SignalWire Basic Authentication using Project ID and API Token. The client sends HTTP requests with the Authorization header containing the word Basic followed by a space and a base64-encoded string of project_id:token. The project ID will be used as the username and the API token as the password. Example: ``` Authorization: Basic base64(project_id:token) ```

## Request

### Body (application/json)

- `object`
  - `method`: `create_conversation` (create_conversation)
    - `id` (string, required) — Your identifier for this request, echoed back on the response so you can match the two.
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `params` (object, required) — The parameters for `create_conversation`.
      - `id` (string, required) — The conversation this method acts on. You choose the value when you create the conversation, and it is scoped to your project.
      - `config_url` (string, required) — The publicly reachable URL serving your agent's SWML. `localhost` and private network addresses cannot be reached by SignalWire.
      - `user_message` (string, optional) — An opening message from the user, sent as part of creating the conversation.
      - `conversation_timeout` (integer, optional, default: 3600) — Seconds a conversation may sit idle before it ends.
      - `user_meta_data` (object, optional) — Arbitrary data about the user, included in webhooks generated for this conversation.
      - `reinit` (boolean, optional, default: false) — Reset an existing conversation instead of returning it as-is. Clears the message history.
  - `method`: `chat` (chat)
    - `id` (string, required) — Your identifier for this request, echoed back on the response so you can match the two.
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `params` (object, required) — The parameters for `chat`.
      - `id` (string, required) — The conversation this method acts on. You choose the value when you create the conversation, and it is scoped to your project.
      - `message` (string, required) — The message to send.
      - `role` (enum, optional, default: user) — Who the message is from. A `system` message steers the agent without appearing as something the user said.
        - Allowed values: `user`, `system`
      - `config_url` (string, optional) — Creates the conversation if it does not exist yet, using this SWML. Sending it here means one call instead of two, at the cost of never receiving `initial_message`, so the agent does not speak first.
      - `conversation_timeout` (integer, optional, default: 3600) — Applies only when this call creates the conversation.
      - `user_meta_data` (object, optional) — Arbitrary data about the user, included in webhooks generated for this conversation.
      - `reinit` (boolean, optional, default: false) — Applies only when this call creates the conversation.
  - `method`: `end_conversation` (end_conversation)
    - `id` (string, required) — Your identifier for this request, echoed back on the response so you can match the two.
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `params` (object, required) — The parameters for `end_conversation`.
      - `id` (string, required) — The conversation this method acts on. You choose the value when you create the conversation, and it is scoped to your project.
  - `method`: `delete` (delete)
    - `id` (string, required) — Your identifier for this request, echoed back on the response so you can match the two.
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `params` (object, required) — The parameters for `delete`.
      - `id` (string, required) — The conversation this method acts on. You choose the value when you create the conversation, and it is scoped to your project.
  - `method`: `chat_log` (chat_log)
    - `id` (string, required) — Your identifier for this request, echoed back on the response so you can match the two.
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `params` (object, required) — The parameters for `chat_log`.
      - `id` (string, required) — The conversation this method acts on. You choose the value when you create the conversation, and it is scoped to your project.
  - `method`: `summarize` (summarize)
    - `id` (string, required) — Your identifier for this request, echoed back on the response so you can match the two.
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `params` (object, required) — The parameters for `summarize`.
      - `id` (string, required) — The conversation this method acts on. You choose the value when you create the conversation, and it is scoped to your project.
      - `summary_prompt` (string, optional) — How to summarize. Overrides the `post_prompt` text in your SWML for this call only.
      - `temperature` (float, optional, default: 0.3) — Sampling temperature for the summary.
      - `top_p` (float, optional, default: 0.3) — Nucleus sampling cutoff for the summary.
      - `frequency_penalty` (float, optional, default: 1) — Penalty applied to tokens by how often they have already appeared.
      - `presence_penalty` (float, optional, default: 1) — Penalty applied to tokens that have appeared at all.
      - `max_tokens` (integer, optional, default: 512) — Longest summary to generate, in tokens.

## Response

### 200

The request has succeeded.

- `object or object or object or object or object or object or object`
  - create_conversation result
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `id` (string, required) — The `id` from your request.
    - `result` (object, required) — The conversation that now exists.
      - `status` (enum, required) — What happened. `created` for a new conversation, `reinitialized` when `reinit` reset an existing one, and `exists` when one was already there and was left alone.
        - Allowed values: `created`, `reinitialized`, `exists`
      - `id` (string, required) — The conversation id.
      - `initial_message` (string, optional, nullable) — The agent's opening line, when the agent greets first.
  - chat result
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `id` (string, required) — The `id` from your request.
    - `result` (object, required) — The agent's turn.
      - `response` (string, required) — The agent's reply. When this call created the conversation, this is the agent's opening message.
      - `user_event` (object, optional) — An event one of your tools raised for your application to act on, present only when the turn produced one. The contents under `event` are whatever your tool sent, so the shape is yours; the convention is a `type` key your client can switch on.
  - end_conversation result
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `id` (string, required) — The `id` from your request.
    - `result` (object, required) — The outcome of ending the conversation.
      - `status` (enum, required) — `ended` when the conversation was ended, `not_found` when no conversation had that id.
        - Allowed values: `ended`, `not_found`
      - `id` (string, required) — The conversation id.
  - delete result
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `id` (string, required) — The `id` from your request.
    - `result` (object, required) — The outcome of deleting the conversation.
      - `status` (enum, required) — `deleted` when the conversation was removed, `not_found` when no conversation had that id.
        - Allowed values: `deleted`, `not_found`
      - `id` (string, required) — The conversation id.
  - chat_log result
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `id` (string, required) — The `id` from your request.
    - `result` (object, required) — The entries recorded for the conversation.
      - `chat_log` (list of object, required) — Every entry in the conversation, in order. Alongside the dialogue this can carry your own prompt and other non-dialogue entries, so filter to `user` and `assistant` before displaying a transcript.
        - `role` (string, required) — Who produced the entry. Common roles include `system`, `user`, `assistant`, and `tool`. Other roles may appear, so filter to the roles your application uses rather than assuming a fixed set.
        - `content` (string, required) — The text of the entry.
        - `timestamp` (long, optional) — When the entry was added, as a Unix timestamp in microseconds. Omitted on entries without one.
        - `tool_calls` (list of object, optional) — The tool calls the agent made on this turn. Present only on a turn that made any.
      - `call_timeline` (list of object, optional) — Structured timeline entries returned for the conversation. The entry shape depends on the events recorded for that conversation.
  - summarize result
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `id` (string, required) — The `id` from your request.
    - `result` (object, required) — The outcome of summarizing.
      - `summary` (string, optional) — The generated summary.
      - `error` (string, optional) — Why no summary was produced.
  - Error
    - `jsonrpc` (enum, required) — The JSON-RPC version. Always `2.0`.
      - Allowed values: `2.0`
    - `id` (string, required) — The `id` from your request.
    - `error` (object, required) — The error that ended this call.
      - `code` (enum, required) — Which failure this was. See [API error codes](/docs/apis/error-codes) for descriptions and troubleshooting context.
        - Allowed values: `-32001`, `-32002`, `-32003`, `-32004`, `-32005`, `-32006`, `-32007`, `-32600`, `-32601`, `-32602`, `-32603`
      - `message` (string, required) — A short description of the failure.

## Examples

### delete

**Request**

```json
{
  "method": "delete",
  "id": "req-4",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123"
  }
}
```

**Response**

```json
{
  "id": "req-1",
  "jsonrpc": "2.0",
  "result": {
    "id": "conv-123",
    "initial_message": "Hi! How can I help?",
    "status": "created"
  }
}
```

**SDK Code**

```python delete
import requests

url = "https://{your_space_name}.signalwire.com/api/ai/chat"

payload = {
    "method": "delete",
    "id": "req-4",
    "jsonrpc": "2.0",
    "params": { "id": "conv-123" }
}
headers = {
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers, auth=("<project_id>", "<api_token>"))

print(response.json())
```

```javascript delete
const url = 'https://{your_space_name}.signalwire.com/api/ai/chat';
const credentials = btoa("<project_id>:<api_token>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: '{"method":"delete","id":"req-4","jsonrpc":"2.0","params":{"id":"conv-123"}}'
};

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

```go delete
package main

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

func main() {

	url := "https://{your_space_name}.signalwire.com/api/ai/chat"

	payload := strings.NewReader("{\n  \"method\": \"delete\",\n  \"id\": \"req-4\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}")

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

	req.SetBasicAuth("<project_id>", "<api_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 delete
require 'uri'
require 'net/http'

url = URI("https://{your_space_name}.signalwire.com/api/ai/chat")

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

request = Net::HTTP::Post.new(url)
request.basic_auth("<project_id>", "<api_token>")
request["Content-Type"] = 'application/json'
request.body = "{\n  \"method\": \"delete\",\n  \"id\": \"req-4\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}"

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

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

HttpResponse<String> response = Unirest.post("https://{your_space_name}.signalwire.com/api/ai/chat")
  .basicAuth("<project_id>", "<api_token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"method\": \"delete\",\n  \"id\": \"req-4\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://{your_space_name}.signalwire.com/api/ai/chat', [
  'body' => '{
  "method": "delete",
  "id": "req-4",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123"
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
    'auth' => ['<project_id>', '<api_token>'],
]);

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

```csharp delete
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://{your_space_name}.signalwire.com/api/ai/chat");
client.Authenticator = new HttpBasicAuthenticator("<project_id>", "<api_token>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"method\": \"delete\",\n  \"id\": \"req-4\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift delete
import Foundation

let credentials = Data("<project_id>:<api_token>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/json"
]
let parameters = [
  "method": "delete",
  "id": "req-4",
  "jsonrpc": "2.0",
  "params": ["id": "conv-123"]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://{your_space_name}.signalwire.com/api/ai/chat")! 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()
```

### end_conversation

**Request**

```json
{
  "method": "end_conversation",
  "id": "req-3",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123"
  }
}
```

**Response**

```json
{
  "id": "req-1",
  "jsonrpc": "2.0",
  "result": {
    "id": "conv-123",
    "initial_message": "Hi! How can I help?",
    "status": "created"
  }
}
```

**SDK Code**

```python end_conversation
import requests

url = "https://{your_space_name}.signalwire.com/api/ai/chat"

payload = {
    "method": "end_conversation",
    "id": "req-3",
    "jsonrpc": "2.0",
    "params": { "id": "conv-123" }
}
headers = {
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers, auth=("<project_id>", "<api_token>"))

print(response.json())
```

```javascript end_conversation
const url = 'https://{your_space_name}.signalwire.com/api/ai/chat';
const credentials = btoa("<project_id>:<api_token>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: '{"method":"end_conversation","id":"req-3","jsonrpc":"2.0","params":{"id":"conv-123"}}'
};

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

```go end_conversation
package main

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

func main() {

	url := "https://{your_space_name}.signalwire.com/api/ai/chat"

	payload := strings.NewReader("{\n  \"method\": \"end_conversation\",\n  \"id\": \"req-3\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}")

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

	req.SetBasicAuth("<project_id>", "<api_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 end_conversation
require 'uri'
require 'net/http'

url = URI("https://{your_space_name}.signalwire.com/api/ai/chat")

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

request = Net::HTTP::Post.new(url)
request.basic_auth("<project_id>", "<api_token>")
request["Content-Type"] = 'application/json'
request.body = "{\n  \"method\": \"end_conversation\",\n  \"id\": \"req-3\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}"

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

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

HttpResponse<String> response = Unirest.post("https://{your_space_name}.signalwire.com/api/ai/chat")
  .basicAuth("<project_id>", "<api_token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"method\": \"end_conversation\",\n  \"id\": \"req-3\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://{your_space_name}.signalwire.com/api/ai/chat', [
  'body' => '{
  "method": "end_conversation",
  "id": "req-3",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123"
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
    'auth' => ['<project_id>', '<api_token>'],
]);

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

```csharp end_conversation
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://{your_space_name}.signalwire.com/api/ai/chat");
client.Authenticator = new HttpBasicAuthenticator("<project_id>", "<api_token>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"method\": \"end_conversation\",\n  \"id\": \"req-3\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift end_conversation
import Foundation

let credentials = Data("<project_id>:<api_token>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/json"
]
let parameters = [
  "method": "end_conversation",
  "id": "req-3",
  "jsonrpc": "2.0",
  "params": ["id": "conv-123"]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://{your_space_name}.signalwire.com/api/ai/chat")! 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()
```

### summarize

**Request**

```json
{
  "method": "summarize",
  "id": "req-6",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123",
    "summary_prompt": "List the order numbers discussed and whether each was resolved."
  }
}
```

**Response**

```json
{
  "id": "req-1",
  "jsonrpc": "2.0",
  "result": {
    "id": "conv-123",
    "initial_message": "Hi! How can I help?",
    "status": "created"
  }
}
```

**SDK Code**

```python summarize
import requests

url = "https://{your_space_name}.signalwire.com/api/ai/chat"

payload = {
    "method": "summarize",
    "id": "req-6",
    "jsonrpc": "2.0",
    "params": {
        "id": "conv-123",
        "summary_prompt": "List the order numbers discussed and whether each was resolved."
    }
}
headers = {
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers, auth=("<project_id>", "<api_token>"))

print(response.json())
```

```javascript summarize
const url = 'https://{your_space_name}.signalwire.com/api/ai/chat';
const credentials = btoa("<project_id>:<api_token>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: '{"method":"summarize","id":"req-6","jsonrpc":"2.0","params":{"id":"conv-123","summary_prompt":"List the order numbers discussed and whether each was resolved."}}'
};

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

```go summarize
package main

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

func main() {

	url := "https://{your_space_name}.signalwire.com/api/ai/chat"

	payload := strings.NewReader("{\n  \"method\": \"summarize\",\n  \"id\": \"req-6\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"summary_prompt\": \"List the order numbers discussed and whether each was resolved.\"\n  }\n}")

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

	req.SetBasicAuth("<project_id>", "<api_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 summarize
require 'uri'
require 'net/http'

url = URI("https://{your_space_name}.signalwire.com/api/ai/chat")

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

request = Net::HTTP::Post.new(url)
request.basic_auth("<project_id>", "<api_token>")
request["Content-Type"] = 'application/json'
request.body = "{\n  \"method\": \"summarize\",\n  \"id\": \"req-6\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"summary_prompt\": \"List the order numbers discussed and whether each was resolved.\"\n  }\n}"

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

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

HttpResponse<String> response = Unirest.post("https://{your_space_name}.signalwire.com/api/ai/chat")
  .basicAuth("<project_id>", "<api_token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"method\": \"summarize\",\n  \"id\": \"req-6\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"summary_prompt\": \"List the order numbers discussed and whether each was resolved.\"\n  }\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://{your_space_name}.signalwire.com/api/ai/chat', [
  'body' => '{
  "method": "summarize",
  "id": "req-6",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123",
    "summary_prompt": "List the order numbers discussed and whether each was resolved."
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
    'auth' => ['<project_id>', '<api_token>'],
]);

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

```csharp summarize
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://{your_space_name}.signalwire.com/api/ai/chat");
client.Authenticator = new HttpBasicAuthenticator("<project_id>", "<api_token>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"method\": \"summarize\",\n  \"id\": \"req-6\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"summary_prompt\": \"List the order numbers discussed and whether each was resolved.\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift summarize
import Foundation

let credentials = Data("<project_id>:<api_token>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/json"
]
let parameters = [
  "method": "summarize",
  "id": "req-6",
  "jsonrpc": "2.0",
  "params": [
    "id": "conv-123",
    "summary_prompt": "List the order numbers discussed and whether each was resolved."
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://{your_space_name}.signalwire.com/api/ai/chat")! 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()
```

### chat_log

**Request**

```json
{
  "method": "chat_log",
  "id": "req-5",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123"
  }
}
```

**Response**

```json
{
  "id": "req-1",
  "jsonrpc": "2.0",
  "result": {
    "id": "conv-123",
    "initial_message": "Hi! How can I help?",
    "status": "created"
  }
}
```

**SDK Code**

```python chat_log
import requests

url = "https://{your_space_name}.signalwire.com/api/ai/chat"

payload = {
    "method": "chat_log",
    "id": "req-5",
    "jsonrpc": "2.0",
    "params": { "id": "conv-123" }
}
headers = {
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers, auth=("<project_id>", "<api_token>"))

print(response.json())
```

```javascript chat_log
const url = 'https://{your_space_name}.signalwire.com/api/ai/chat';
const credentials = btoa("<project_id>:<api_token>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: '{"method":"chat_log","id":"req-5","jsonrpc":"2.0","params":{"id":"conv-123"}}'
};

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

```go chat_log
package main

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

func main() {

	url := "https://{your_space_name}.signalwire.com/api/ai/chat"

	payload := strings.NewReader("{\n  \"method\": \"chat_log\",\n  \"id\": \"req-5\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}")

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

	req.SetBasicAuth("<project_id>", "<api_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 chat_log
require 'uri'
require 'net/http'

url = URI("https://{your_space_name}.signalwire.com/api/ai/chat")

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

request = Net::HTTP::Post.new(url)
request.basic_auth("<project_id>", "<api_token>")
request["Content-Type"] = 'application/json'
request.body = "{\n  \"method\": \"chat_log\",\n  \"id\": \"req-5\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}"

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

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

HttpResponse<String> response = Unirest.post("https://{your_space_name}.signalwire.com/api/ai/chat")
  .basicAuth("<project_id>", "<api_token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"method\": \"chat_log\",\n  \"id\": \"req-5\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://{your_space_name}.signalwire.com/api/ai/chat', [
  'body' => '{
  "method": "chat_log",
  "id": "req-5",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123"
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
    'auth' => ['<project_id>', '<api_token>'],
]);

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

```csharp chat_log
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://{your_space_name}.signalwire.com/api/ai/chat");
client.Authenticator = new HttpBasicAuthenticator("<project_id>", "<api_token>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"method\": \"chat_log\",\n  \"id\": \"req-5\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift chat_log
import Foundation

let credentials = Data("<project_id>:<api_token>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/json"
]
let parameters = [
  "method": "chat_log",
  "id": "req-5",
  "jsonrpc": "2.0",
  "params": ["id": "conv-123"]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://{your_space_name}.signalwire.com/api/ai/chat")! 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()
```

### chat

**Request**

```json
{
  "method": "chat",
  "id": "req-2",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123",
    "message": "Where is order A-771?"
  }
}
```

**Response**

```json
{
  "id": "req-1",
  "jsonrpc": "2.0",
  "result": {
    "id": "conv-123",
    "initial_message": "Hi! How can I help?",
    "status": "created"
  }
}
```

**SDK Code**

```python chat
import requests

url = "https://{your_space_name}.signalwire.com/api/ai/chat"

payload = {
    "method": "chat",
    "id": "req-2",
    "jsonrpc": "2.0",
    "params": {
        "id": "conv-123",
        "message": "Where is order A-771?"
    }
}
headers = {
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers, auth=("<project_id>", "<api_token>"))

print(response.json())
```

```javascript chat
const url = 'https://{your_space_name}.signalwire.com/api/ai/chat';
const credentials = btoa("<project_id>:<api_token>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: '{"method":"chat","id":"req-2","jsonrpc":"2.0","params":{"id":"conv-123","message":"Where is order A-771?"}}'
};

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

```go chat
package main

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

func main() {

	url := "https://{your_space_name}.signalwire.com/api/ai/chat"

	payload := strings.NewReader("{\n  \"method\": \"chat\",\n  \"id\": \"req-2\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"message\": \"Where is order A-771?\"\n  }\n}")

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

	req.SetBasicAuth("<project_id>", "<api_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 chat
require 'uri'
require 'net/http'

url = URI("https://{your_space_name}.signalwire.com/api/ai/chat")

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

request = Net::HTTP::Post.new(url)
request.basic_auth("<project_id>", "<api_token>")
request["Content-Type"] = 'application/json'
request.body = "{\n  \"method\": \"chat\",\n  \"id\": \"req-2\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"message\": \"Where is order A-771?\"\n  }\n}"

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

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

HttpResponse<String> response = Unirest.post("https://{your_space_name}.signalwire.com/api/ai/chat")
  .basicAuth("<project_id>", "<api_token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"method\": \"chat\",\n  \"id\": \"req-2\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"message\": \"Where is order A-771?\"\n  }\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://{your_space_name}.signalwire.com/api/ai/chat', [
  'body' => '{
  "method": "chat",
  "id": "req-2",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123",
    "message": "Where is order A-771?"
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
    'auth' => ['<project_id>', '<api_token>'],
]);

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

```csharp chat
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://{your_space_name}.signalwire.com/api/ai/chat");
client.Authenticator = new HttpBasicAuthenticator("<project_id>", "<api_token>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"method\": \"chat\",\n  \"id\": \"req-2\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"message\": \"Where is order A-771?\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift chat
import Foundation

let credentials = Data("<project_id>:<api_token>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/json"
]
let parameters = [
  "method": "chat",
  "id": "req-2",
  "jsonrpc": "2.0",
  "params": [
    "id": "conv-123",
    "message": "Where is order A-771?"
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://{your_space_name}.signalwire.com/api/ai/chat")! 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()
```

### create_conversation

**Request**

```json
{
  "method": "create_conversation",
  "id": "req-1",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123",
    "config_url": "https://your-agent.example.com/swml",
    "conversation_timeout": 1800,
    "user_meta_data": {
      "customer_tier": "premium"
    }
  }
}
```

**Response**

```json
{
  "id": "req-1",
  "jsonrpc": "2.0",
  "result": {
    "id": "conv-123",
    "initial_message": "Hi! How can I help?",
    "status": "created"
  }
}
```

**SDK Code**

```python create_conversation
import requests

url = "https://{your_space_name}.signalwire.com/api/ai/chat"

payload = {
    "method": "create_conversation",
    "id": "req-1",
    "jsonrpc": "2.0",
    "params": {
        "id": "conv-123",
        "config_url": "https://your-agent.example.com/swml",
        "conversation_timeout": 1800,
        "user_meta_data": { "customer_tier": "premium" }
    }
}
headers = {
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers, auth=("<project_id>", "<api_token>"))

print(response.json())
```

```javascript create_conversation
const url = 'https://{your_space_name}.signalwire.com/api/ai/chat';
const credentials = btoa("<project_id>:<api_token>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: '{"method":"create_conversation","id":"req-1","jsonrpc":"2.0","params":{"id":"conv-123","config_url":"https://your-agent.example.com/swml","conversation_timeout":1800,"user_meta_data":{"customer_tier":"premium"}}}'
};

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

```go create_conversation
package main

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

func main() {

	url := "https://{your_space_name}.signalwire.com/api/ai/chat"

	payload := strings.NewReader("{\n  \"method\": \"create_conversation\",\n  \"id\": \"req-1\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"config_url\": \"https://your-agent.example.com/swml\",\n    \"conversation_timeout\": 1800,\n    \"user_meta_data\": {\n      \"customer_tier\": \"premium\"\n    }\n  }\n}")

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

	req.SetBasicAuth("<project_id>", "<api_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 create_conversation
require 'uri'
require 'net/http'

url = URI("https://{your_space_name}.signalwire.com/api/ai/chat")

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

request = Net::HTTP::Post.new(url)
request.basic_auth("<project_id>", "<api_token>")
request["Content-Type"] = 'application/json'
request.body = "{\n  \"method\": \"create_conversation\",\n  \"id\": \"req-1\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"config_url\": \"https://your-agent.example.com/swml\",\n    \"conversation_timeout\": 1800,\n    \"user_meta_data\": {\n      \"customer_tier\": \"premium\"\n    }\n  }\n}"

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

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

HttpResponse<String> response = Unirest.post("https://{your_space_name}.signalwire.com/api/ai/chat")
  .basicAuth("<project_id>", "<api_token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"method\": \"create_conversation\",\n  \"id\": \"req-1\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"config_url\": \"https://your-agent.example.com/swml\",\n    \"conversation_timeout\": 1800,\n    \"user_meta_data\": {\n      \"customer_tier\": \"premium\"\n    }\n  }\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://{your_space_name}.signalwire.com/api/ai/chat', [
  'body' => '{
  "method": "create_conversation",
  "id": "req-1",
  "jsonrpc": "2.0",
  "params": {
    "id": "conv-123",
    "config_url": "https://your-agent.example.com/swml",
    "conversation_timeout": 1800,
    "user_meta_data": {
      "customer_tier": "premium"
    }
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
    'auth' => ['<project_id>', '<api_token>'],
]);

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

```csharp create_conversation
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://{your_space_name}.signalwire.com/api/ai/chat");
client.Authenticator = new HttpBasicAuthenticator("<project_id>", "<api_token>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"method\": \"create_conversation\",\n  \"id\": \"req-1\",\n  \"jsonrpc\": \"2.0\",\n  \"params\": {\n    \"id\": \"conv-123\",\n    \"config_url\": \"https://your-agent.example.com/swml\",\n    \"conversation_timeout\": 1800,\n    \"user_meta_data\": {\n      \"customer_tier\": \"premium\"\n    }\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift create_conversation
import Foundation

let credentials = Data("<project_id>:<api_token>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/json"
]
let parameters = [
  "method": "create_conversation",
  "id": "req-1",
  "jsonrpc": "2.0",
  "params": [
    "id": "conv-123",
    "config_url": "https://your-agent.example.com/swml",
    "conversation_timeout": 1800,
    "user_meta_data": ["customer_tier": "premium"]
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://{your_space_name}.signalwire.com/api/ai/chat")! 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()
```