Getting Started
This is the one quickstart. It takes you from nothing to a visible reply from an AI employee that you built: sign in, create an agent, give it a small workflow, make an API key, then start a conversation and read the answer. Plan on about fifteen minutes, plus the wait for a test login if you do not have one yet.
Everything, building an agent and running a session with one, goes through a single GraphQL API.
| Step | What you do | Credential it uses | Time |
|---|---|---|---|
| 1 | Get a test login | none | up to 1 day |
| 2 | Sign in | email and password | 1 minute |
| 3 | Create the agent | dashboard token | 2 minutes |
| 4 | Build, publish and attach a workflow | dashboard token | 4 minutes |
| 5 | Make an API key | dashboard token | 1 minute |
| 6 | Start a session, send a message, read the reply | API key, session token | 5 minutes |
Before you start: three rules every request follows
Section titled “Before you start: three rules every request follows”- One URL,
POSTonly. Every call is an HTTPPOSTto the GraphQL URL with a JSON body{ "query": "...", "variables": { ... } }. Send inputs asvariables, as the samples below do. - The platform header. Every request carries
x-huat-platform: customer. Without it even a valid credential answersPlatform is not specified!. See the header every request needs. - Check
errorsbeforedata. Errors come back in a JSONerrorsarray with a machine-readableextensions.code, usually with HTTP status 200. See Errors.
Request bodies must not be compressed: a Content-Encoding other than identity is refused with HTTP 415. Most clients never send one. Details: Compressed request bodies: HTTP 415.
Step 1: Get a test login
Section titled “Step 1: Get a test login”There is no self-serve sign-up. A new developer gets a test workspace by asking for one:
- Open the contact page and fill in the form: your name and work email.
- In the message, write “developer test workspace” and say what you want to build in a sentence or two.
- You receive a login for the test environment within one working day.
The login belongs to the workspace owner, which is what you need: building agents and connecting channels are owner operations. If you already have a login, skip to step 2.
Step 2: Sign in
Section titled “Step 2: Sign in”mutation Login($input: SignInInput!) { login(input: $input) { accessToken refreshToken }}{ "input": { "email": "you@example.com", "password": "<YOUR_PASSWORD>" }}Headers: x-huat-platform: customer.
Expected response (the token is shortened here):
{ "data": { "login": { "accessToken": "eyJhbGciOi...", "refreshToken": "eyJhbGciOi..." } }}The accessToken is your dashboard token. Send it as Authorization: Bearer <accessToken> on steps 3 to 5, together with x-huat-platform: customer. Treat it like a password.
The three credentials (dashboard token, API key, session token) and when each applies are explained once, on Authentication.
Step 3: Create the agent
Section titled “Step 3: Create the agent”An agent is the persona a session talks to. It has no workflow yet, which step 4 adds.
mutation CreateAgent($input: CreateAgentInput!) { createAgent(input: $input) { id name status workflowId }}{ "input": { "name": "Helpdesk triage", "position": "IT helpdesk assistant", "personaPrompt": "You are a calm, precise IT helpdesk assistant. Ask one question at a time and never promise a fix you cannot make.", "openingGreeting": "Hi, I can log an IT ticket for you. What is the problem?", "useCase": "SUPPORT", "voiceTier": "STANDARD", "avatarBackend": "CLIENT_3D" }}Expected response: status is ACTIVE and workflowId is null. Write down the agent id; the rest of this page calls it <AGENT_ID>.
Step 4: Give it a workflow
Section titled “Step 4: Give it a workflow”A workflow is the graph of steps the agent runs on every turn. This one has three: it starts, asks the model to pick a queue, and replies. An agent with no published workflow cannot answer, so this step matters.
4a. Create the empty workflow.
mutation CreateWorkflow($input: CreateWorkflowInput!) { createWorkflow(input: $input) { id name isPublished }}{ "input": { "name": "Ticket routing", "description": "Classifies a ticket as L1, L2 or L3 and tells the user where it goes." }}Write down the workflow id (<WORKFLOW_ID>).
4b. Save the graph. nodes and edges are JSON, so they must travel as variables, never inline in the query.
mutation SaveGraph($input: UpdateWorkflowInput!) { updateWorkflow(input: $input) { id version isPublished }}{ "input": { "id": 12, "nodes": [ { "id": "start", "type": "start", "label": "Start", "config": {}, "position": { "x": 0, "y": 0 } }, { "id": "classify", "type": "llm", "label": "Classify level", "config": { "promptTemplate": "You route IT support tickets. Read the ticket and answer with one word: L1 for password resets, account unlocks and how-to questions; L2 for a broken device, application or connection that needs a technician; L3 for an outage, a security incident or anything affecting many people.\n\nTicket: \"{{userMessage}}\"", "outputVar": "level", "matchAnyOf": ["L1", "L2", "L3"], "streamOutput": false }, "position": { "x": 0, "y": 100 } }, { "id": "reply", "type": "response", "label": "Tell the user", "config": { "messageTemplate": "Thanks. Your ticket goes to the {{level}} queue; we will reply here." }, "position": { "x": 0, "y": 200 } } ], "edges": [ { "id": "e1", "source": "start", "target": "classify" }, { "id": "e2", "source": "classify", "target": "reply" } ] }}Replace 12 with your <WORKFLOW_ID>. Node type values are lowercase. Expected response: isPublished is false; this saved a draft.
4c. Publish it.
mutation Publish($id: Int!) { publishWorkflow(id: $id) { id version isPublished }}{ "id": 12 }Expected response: isPublished is true. If the graph is not runnable (no start node, an unreachable node) the call refuses with a message naming the problem.
4d. Attach it to the agent. id is a separate argument here, not a field of input.
mutation Attach($id: ID!, $input: UpdateAgentInput!) { updateAgent(id: $id, input: $input) { id workflowId status }}{ "id": "7", "input": { "workflowId": 12 } }Use your <AGENT_ID> and <WORKFLOW_ID>. Expected response: workflowId now holds your workflow’s id. The agent is ready.
Step 5: Make an API key
Section titled “Step 5: Make an API key”Your server talks to Wetel with an API key, not with the dashboard token. Create one named key per consumer so you can revoke one without breaking the others.
mutation CreateKey($name: String!) { createNamedApiKey(name: $name) { id name key warning }}{ "name": "quickstart-test" }Expected response: key is a string starting sk_. It is shown once. Copy it into your server’s secret store now; Wetel keeps only a hash and cannot show it again. Keep the id in case you need to revoke it with revokeNamedApiKey.
Step 6: Get a reply
Section titled “Step 6: Get a reply”Now act as your application. These three calls use the API key and a session token, never the dashboard token.
6a. Start a session. Header: X-Api-Key: <YOUR_API_KEY> and x-huat-platform: customer.
mutation StartSession($input: SdkStartInput!) { sdkStart(input: $input) { sessionId avatarToken agentId graphqlEndpoint }}{ "input": { "agentId": 7, "clientId": "quickstart-001" } }Expected response: a sessionId, an avatarToken (the short-lived session token, about an hour) and the graphqlEndpoint. clientId is your own id for this conversation; step 6c uses it to find the session again.
6b. Send a message. Header: Authorization: Bearer <avatarToken> and x-huat-platform: customer.
mutation SendMessage($input: SdkSendMessageInput!) { sdkSendMessage(input: $input)}{ "input": { "sessionId": 42, "text": "My laptop cannot connect to the office VPN since this morning." }}Expected response: { "data": { "sdkSendMessage": true } }. That true only acknowledges the message. The reply is produced asynchronously, a few seconds later.
6c. Read the reply. Wait about three seconds, then ask for the session’s messages. Header: X-Api-Key: <YOUR_API_KEY>.
query ReadReply($externalCustomerId: String!, $first: Int) { sessionsByExternalCustomerId( externalCustomerId: $externalCustomerId first: $first ) { edges { node { id status messages { role text } } } }}{ "externalCustomerId": "quickstart-001", "first": 1 }Expected response: the messages in order. Your message has role USER; the agent’s answer is the MODEL message after it:
{ "data": { "sessionsByExternalCustomerId": { "edges": [ { "node": { "id": 42, "status": "ACTIVE", "messages": [ { "role": "USER", "text": "My laptop cannot connect to the office VPN since this morning." }, { "role": "MODEL", "text": "Thanks. Your ticket goes to the L2 queue; we will reply here." } ] } } ] } }}If the MODEL message is not there yet, wait two seconds and repeat 6c. That reply is your agent answering. The queue (L2) is chosen by the model, so yours may say L1 or L2.
The same thing as one program
Section titled “The same thing as one program”Steps 6a to 6c, plus ending the session, are also a complete program that starts a session, sends the message, polls for the reply every two seconds for up to sixty, prints it and ends the session. Pick your language. Set WETEL_API_KEY and WETEL_AGENT_ID and run it; the comment at the top of each file has the exact command. The same files are on Downloads.
#!/usr/bin/env bash# Hello ticket: start a session, send one message, poll for the reply, end the session.# Needs curl and jq. Run: WETEL_API_KEY=sk_... WETEL_AGENT_ID=7 bash hello-ticket.shset -euo pipefailAPI_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"AGENT_ID="${WETEL_AGENT_ID:-1}"CLIENT_ID="ticket-$(date +%s)" # one clientId per conversationTEXT="My laptop cannot connect to the office VPN since this morning."
read -r -d '' START <<'GRAPHQL' || truemutation StartSession($input: SdkStartInput!) { sdkStart(input: $input) { sessionId avatarToken agentId graphqlEndpoint }}GRAPHQLread -r -d '' SEND <<'GRAPHQL' || truemutation SendMessage($input: SdkSendMessageInput!) { sdkSendMessage(input: $input)}GRAPHQLread -r -d '' POLL <<'GRAPHQL' || truequery PollSession($externalCustomerId: String!, $first: Int) { sessionsByExternalCustomerId(externalCustomerId: $externalCustomerId, first: $first) { totalCount edges { node { id status messages { id role text turnIndex createdAt } } } }}GRAPHQLread -r -d '' END <<'GRAPHQL' || truemutation EndSession($input: SdkEndSessionInput!) { sdkEndSession(input: $input) { sessionId durationSeconds evaluation { score summary } }}GRAPHQL
# gql QUERY VARIABLES_JSON AUTH_HEADER: prints .data, or the first error and exits.gql() { local response response=$(jq -n --arg query "$1" --argjson variables "$2" '{query: $query, variables: $variables}' | curl -sS "$API_URL" -H "Content-Type: application/json" -H "x-huat-platform: customer" -H "$3" --data-binary @-) if [ "$(jq '.errors | length' <<<"$response")" != "0" ]; then jq -r '.errors[0] | "\(.extensions.code): \(.message)"' <<<"$response" >&2 exit 1 fi jq '.data' <<<"$response"}
# 1. Start a session with the API key.STARTED=$(gql "$START" "$(jq -n --argjson agentId "$AGENT_ID" --arg clientId "$CLIENT_ID" '{input: {agentId: $agentId, clientId: $clientId}}')" "X-Api-Key: $WETEL_API_KEY")SESSION_ID=$(jq '.sdkStart.sessionId' <<<"$STARTED")AVATAR_TOKEN=$(jq -r '.sdkStart.avatarToken' <<<"$STARTED")
# 2. Send the message with the session token. It returns true at once.gql "$SEND" "$(jq -n --argjson sessionId "$SESSION_ID" --arg text "$TEXT" '{input: {sessionId: $sessionId, text: $text}}')" "Authorization: Bearer $AVATAR_TOKEN" >/dev/null
# 3. Poll the session's messages until the reply arrives# (the reply is every MODEL message after the last USER message).REPLY=""DEADLINE=$(($(date +%s) + 60))while [ -z "$REPLY" ] && [ "$(date +%s)" -lt "$DEADLINE" ]; do sleep 2 POLLED=$(gql "$POLL" "$(jq -n --arg clientId "$CLIENT_ID" '{externalCustomerId: $clientId, first: 1}')" "X-Api-Key: $WETEL_API_KEY") REPLY=$(jq -r --argjson id "$SESSION_ID" ' .sessionsByExternalCustomerId.edges[].node | select(.id == $id) | .messages | ((map(.role) | rindex("USER")) // -1) as $u | .[($u + 1):] | map(select(.role == "MODEL") | .text) | join("\n")' <<<"$POLLED")doneecho "${REPLY:-No reply within the timeout.}"
# 4. End the session with the session token.gql "$END" "$(jq -n --argjson sessionId "$SESSION_ID" '{input: {sessionId: $sessionId}}')" "Authorization: Bearer $AVATAR_TOKEN" >/dev/null// Hello ticket: start a session, send one message, poll for the reply, end the session.// Node 18+. Run: WETEL_API_KEY=sk_... WETEL_AGENT_ID=7 npx tsx hello-ticket.tsconst API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";const API_KEY = process.env.WETEL_API_KEY ?? "";const AGENT_ID = Number(process.env.WETEL_AGENT_ID ?? "1");const POLL_INTERVAL_MS = 2000;const TIMEOUT_MS = 60000;
const START = `mutation StartSession($input: SdkStartInput!) { sdkStart(input: $input) { sessionId avatarToken agentId graphqlEndpoint }}`;const SEND = `mutation SendMessage($input: SdkSendMessageInput!) { sdkSendMessage(input: $input)}`;const POLL = `query PollSession($externalCustomerId: String!, $first: Int) { sessionsByExternalCustomerId(externalCustomerId: $externalCustomerId, first: $first) { totalCount edges { node { id status messages { id role text turnIndex createdAt } } } }}`;const END = `mutation EndSession($input: SdkEndSessionInput!) { sdkEndSession(input: $input) { sessionId durationSeconds evaluation { score summary } }}`;
type Message = { role: string; text: string };type GraphQLResponse = { data?: any; errors?: { message: string; extensions?: { code?: string } }[];};type Session = { id: number; messages: Message[] };
async function gql( query: string, variables: Record<string, unknown>, auth: Record<string, string>): Promise<any> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", ...auth, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } return body.data;}
// The reply is every MODEL message after the last USER message.function replyAfterLastUserMessage(messages: Message[]): string | undefined { const lastUser = messages.map(m => m.role).lastIndexOf("USER"); const replies = messages.slice(lastUser + 1).filter(m => m.role === "MODEL"); return replies.length ? replies.map(m => m.text).join("\n") : undefined;}
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
async function main(): Promise<void> { const agentId = AGENT_ID; const clientId = `ticket-${Date.now()}`; // one clientId per conversation const text = "My laptop cannot connect to the office VPN since this morning."; const withKey = { "X-Api-Key": API_KEY };
// 1. Start a session with the API key. const started = await gql( START, { input: { agentId: agentId, clientId: clientId, }, }, withKey ); const { sessionId, avatarToken } = started.sdkStart; const withToken = { Authorization: `Bearer ${avatarToken}` };
// 2. Send the message with the session token. It returns true at once. await gql( SEND, { input: { sessionId: sessionId, text: text, }, }, withToken );
// 3. Poll the session's messages until the reply arrives. let reply: string | undefined; const deadline = Date.now() + TIMEOUT_MS; while (!reply && Date.now() < deadline) { await sleep(POLL_INTERVAL_MS); const polled = await gql( POLL, { externalCustomerId: clientId, first: 1, }, withKey ); const session = polled.sessionsByExternalCustomerId.edges .map((edge: { node: Session }) => edge.node) .find((node: Session) => node.id === sessionId); reply = replyAfterLastUserMessage(session?.messages ?? []); } console.log(reply ?? "No reply within the timeout.");
// 4. End the session with the session token. await gql( END, { input: { sessionId: sessionId, }, }, withToken );}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// Hello ticket: start a session, send one message, poll for the reply, end the session.// PHP 7.3+ with curl. Run: WETEL_API_KEY=sk_... WETEL_AGENT_ID=7 php hello-ticket.php$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';$apiKey = getenv('WETEL_API_KEY');$pollIntervalSeconds = 2;$timeoutSeconds = 60;
$START = <<<'GRAPHQL'mutation StartSession($input: SdkStartInput!) { sdkStart(input: $input) { sessionId avatarToken agentId graphqlEndpoint }}GRAPHQL;$SEND = <<<'GRAPHQL'mutation SendMessage($input: SdkSendMessageInput!) { sdkSendMessage(input: $input)}GRAPHQL;$POLL = <<<'GRAPHQL'query PollSession($externalCustomerId: String!, $first: Int) { sessionsByExternalCustomerId(externalCustomerId: $externalCustomerId, first: $first) { totalCount edges { node { id status messages { id role text turnIndex createdAt } } } }}GRAPHQL;$END = <<<'GRAPHQL'mutation EndSession($input: SdkEndSessionInput!) { sdkEndSession(input: $input) { sessionId durationSeconds evaluation { score summary } }}GRAPHQL;
function gql(string $apiUrl, string $query, array $variables, array $auth): array{ $ch = curl_init($apiUrl); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array_merge(['Content-Type: application/json', 'x-huat-platform: customer'], $auth), CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]), ]); $body = json_decode(curl_exec($ch), true); curl_close($ch); if (!empty($body['errors'])) { $error = $body['errors'][0]; throw new RuntimeException(($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message']); } return $body['data'];}
// The reply is every MODEL message after the last USER message.function replyAfterLastUserMessage(array $messages): ?string{ $lastUser = -1; foreach ($messages as $i => $message) { if ($message['role'] === 'USER') { $lastUser = $i; } } $replies = []; foreach (array_slice($messages, $lastUser + 1) as $message) { if ($message['role'] === 'MODEL') { $replies[] = $message['text']; } } return $replies ? implode("\n", $replies) : null;}
$agentId = (int) (getenv('WETEL_AGENT_ID') ?: 1);$clientId = 'ticket-' . round(microtime(true) * 1000); // one clientId per conversation$text = 'My laptop cannot connect to the office VPN since this morning.';$withKey = ['X-Api-Key: ' . $apiKey];
// 1. Start a session with the API key.$started = gql($apiUrl, $START, [ 'input' => [ 'agentId' => $agentId, 'clientId' => $clientId, ],], $withKey)['sdkStart'];$sessionId = $started['sessionId'];$withToken = ['Authorization: Bearer ' . $started['avatarToken']];
// 2. Send the message with the session token. It returns true at once.gql($apiUrl, $SEND, [ 'input' => [ 'sessionId' => $sessionId, 'text' => $text, ],], $withToken);
// 3. Poll the session's messages until the reply arrives.$reply = null;$deadline = time() + $timeoutSeconds;while ($reply === null && time() < $deadline) { sleep($pollIntervalSeconds); $polled = gql($apiUrl, $POLL, [ 'externalCustomerId' => $clientId, 'first' => 1,], $withKey); foreach ($polled['sessionsByExternalCustomerId']['edges'] as $edge) { if ($edge['node']['id'] === $sessionId) { $reply = replyAfterLastUserMessage($edge['node']['messages']); } }}echo ($reply ?? 'No reply within the timeout.'), PHP_EOL;
// 4. End the session with the session token.gql($apiUrl, $END, [ 'input' => [ 'sessionId' => $sessionId, ],], $withToken);// Hello ticket: start a session, send one message, poll for the reply, end the session.// .NET 8: put this in Program.cs of a console app. Run: WETEL_API_KEY=sk_... WETEL_AGENT_ID=7 dotnet runusing System.Net.Http.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";var apiKey = Environment.GetEnvironmentVariable("WETEL_API_KEY") ?? "";var agentId = int.Parse(Environment.GetEnvironmentVariable("WETEL_AGENT_ID") ?? "1");var pollInterval = TimeSpan.FromSeconds(2);var timeout = TimeSpan.FromSeconds(60);
const string Start = """ mutation StartSession($input: SdkStartInput!) { sdkStart(input: $input) { sessionId avatarToken agentId graphqlEndpoint } } """;const string Send = """ mutation SendMessage($input: SdkSendMessageInput!) { sdkSendMessage(input: $input) } """;const string Poll = """ query PollSession($externalCustomerId: String!, $first: Int) { sessionsByExternalCustomerId(externalCustomerId: $externalCustomerId, first: $first) { totalCount edges { node { id status messages { id role text turnIndex createdAt } } } } } """;const string End = """ mutation EndSession($input: SdkEndSessionInput!) { sdkEndSession(input: $input) { sessionId durationSeconds evaluation { score summary } } } """;
using var http = new HttpClient();
async Task<JsonNode> Gql(string query, object variables, string authHeader, string authValue){ using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl) { Content = JsonContent.Create(new { query, variables }), }; request.Headers.Add("x-huat-platform", "customer"); request.Headers.TryAddWithoutValidation(authHeader, authValue); using var response = await http.SendAsync(request); var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!; if (body["errors"] is JsonArray errors && errors.Count > 0) { throw new Exception($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); } return body["data"]!;}
// The reply is every MODEL message after the last USER message.static string? ReplyAfterLastUserMessage(JsonArray messages){ var list = messages.Select(m => m!).ToList(); var lastUser = list.FindLastIndex(m => (string?)m["role"] == "USER"); var replies = list.Skip(lastUser + 1) .Where(m => (string?)m["role"] == "MODEL") .Select(m => (string?)m["text"]) .ToList(); return replies.Count > 0 ? string.Join("\n", replies) : null;}
var clientId = $"ticket-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}"; // one clientId per conversationvar text = "My laptop cannot connect to the office VPN since this morning.";
// 1. Start a session with the API key.var started = (await Gql(Start, new { input = new { agentId = agentId, clientId = clientId } }, "X-Api-Key", apiKey))["sdkStart"]!;var sessionId = (int)started["sessionId"]!;var avatarToken = (string)started["avatarToken"]!;
// 2. Send the message with the session token. It returns true at once.await Gql(Send, new { input = new { sessionId = sessionId, text = text } }, "Authorization", $"Bearer {avatarToken}");
// 3. Poll the session's messages until the reply arrives.string? reply = null;var deadline = DateTime.UtcNow + timeout;while (reply is null && DateTime.UtcNow < deadline){ await Task.Delay(pollInterval); var polled = await Gql(Poll, new { externalCustomerId = clientId, first = 1 }, "X-Api-Key", apiKey); foreach (var edge in polled["sessionsByExternalCustomerId"]!["edges"]!.AsArray()) { if ((int)edge!["node"]!["id"]! == sessionId) { reply = ReplyAfterLastUserMessage(edge["node"]!["messages"]!.AsArray()); } }}Console.WriteLine(reply ?? "No reply within the timeout.");
// 4. End the session with the session token.await Gql(End, new { input = new { sessionId = sessionId } }, "Authorization", $"Bearer {avatarToken}");# Hello ticket: start a session, send one message, poll for the reply, end the session.# Python 3.8+ with "requests". Run: WETEL_API_KEY=sk_... WETEL_AGENT_ID=7 python hello_ticket.pyimport osimport time
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")API_KEY = os.environ["WETEL_API_KEY"]AGENT_ID = int(os.environ.get("WETEL_AGENT_ID", "1"))POLL_INTERVAL_SECONDS = 2TIMEOUT_SECONDS = 60
START = """mutation StartSession($input: SdkStartInput!) { sdkStart(input: $input) { sessionId avatarToken agentId graphqlEndpoint }}"""SEND = """mutation SendMessage($input: SdkSendMessageInput!) { sdkSendMessage(input: $input)}"""POLL = """query PollSession($externalCustomerId: String!, $first: Int) { sessionsByExternalCustomerId(externalCustomerId: $externalCustomerId, first: $first) { totalCount edges { node { id status messages { id role text turnIndex createdAt } } } }}"""END = """mutation EndSession($input: SdkEndSessionInput!) { sdkEndSession(input: $input) { sessionId durationSeconds evaluation { score summary } }}"""
def gql(query, variables, auth): response = requests.post( API_URL, json={"query": query, "variables": variables}, headers={"x-huat-platform": "customer", **auth}, timeout=30, ) body = response.json() if body.get("errors"): error = body["errors"][0] raise RuntimeError(f"{error.get('extensions', {}).get('code')}: {error['message']}") return body["data"]
def reply_after_last_user_message(messages): """The reply is every MODEL message after the last USER message.""" roles = [m["role"] for m in messages] last_user = len(roles) - 1 - roles[::-1].index("USER") if "USER" in roles else -1 replies = [m["text"] for m in messages[last_user + 1 :] if m["role"] == "MODEL"] return "\n".join(replies) if replies else None
def main(): agent_id = AGENT_ID client_id = f"ticket-{int(time.time() * 1000)}" # one clientId per conversation text = "My laptop cannot connect to the office VPN since this morning." with_key = {"X-Api-Key": API_KEY}
# 1. Start a session with the API key. started = gql(START, { "input": { "agentId": agent_id, "clientId": client_id, }, }, with_key)["sdkStart"] session_id, avatar_token = started["sessionId"], started["avatarToken"] with_token = {"Authorization": f"Bearer {avatar_token}"}
# 2. Send the message with the session token. It returns true at once. gql(SEND, { "input": { "sessionId": session_id, "text": text, }, }, with_token)
# 3. Poll the session's messages until the reply arrives. reply = None deadline = time.time() + TIMEOUT_SECONDS while reply is None and time.time() < deadline: time.sleep(POLL_INTERVAL_SECONDS) polled = gql(POLL, { "externalCustomerId": client_id, "first": 1, }, with_key) nodes = [edge["node"] for edge in polled["sessionsByExternalCustomerId"]["edges"]] session = next((n for n in nodes if n["id"] == session_id), None) reply = reply_after_last_user_message(session["messages"] if session else []) print(reply or "No reply within the timeout.")
# 4. End the session with the session token. gql(END, { "input": { "sessionId": session_id, }, }, with_token)
if __name__ == "__main__": main()What you just did
Section titled “What you just did”In short: your app logs in and builds the agent and workflow, starts a session with the API key, sends a message with the session token, and later reads the agent’s reply from the session’s messages.
sequenceDiagram participant You as Your app participant API as Wetel API participant Agent as Agent and workflow You->>API: login, createAgent, workflow calls, createNamedApiKey (dashboard token) You->>API: sdkStart (API key) API-->>You: sessionId and session token You->>API: sdkSendMessage (session token) API->>Agent: run the published workflow Agent-->>API: the reply, a few seconds later You->>API: read the session's messages (API key) API-->>You: your message and the agent's replyYou built an agent once (steps 2 to 5) and then ran it the way a product would (step 6): a long-lived key on your server starts sessions, a short-lived token is the only thing a browser needs, and the reply arrives separately from the message that caused it.
If something goes wrong
Section titled “If something goes wrong”| What you see | Cause | Fix |
|---|---|---|
Platform is not specified! with a valid credential | The x-huat-platform: customer header is missing | Add the header to every request |
Invalid username / password! | Wrong email or password; every sign-in failure reads the same | Check both; after repeated failures the account locks for a while |
TWO_FACTOR_REQUIRED after a correct password | The account has two-factor sign-in on | Use signIn and completeSignInWithTwoFactor instead of login; see Authentication |
UNAUTHENTICATED / Unauthorized | The wrong credential for the call (API key on a dashboard call, or the reverse), or an expired token | Steps 3 to 5 take the dashboard token; step 6a and 6c the API key; step 6b the session token |
| An API key is rejected | The key is from another environment, or was revoked | Mint the key on the same environment you call |
Cannot query field ... or BAD_USER_INPUT on a node | A typo, a capitalised node type, or nodes sent inline instead of as variables | Copy the variables exactly; type values are lowercase |
publishWorkflow refuses the graph | No start node, or a node nothing connects to | Fix what the message names; workflow diagnostics lists findings before you publish |
sdkStart returns NOT_FOUND for the agent | The agent id is not in the workspace of the API key | Use the id from step 3, and a key from the same workspace |
The message was accepted but no MODEL message ever shows | The agent has no published workflow attached, or the run failed | Confirm step 4d (workflowId is set); open the run in Observability |
| The reply is a generic apology | The workflow failed on that turn | Read the run’s node trace in Observability |
HTTP 415 | Your HTTP client compresses request bodies | Turn request compression off for calls to Wetel |
| Too many requests | A per-address limit on sign-in or on session starts | Wait a minute and retry; see Rate limiting |
More symptoms and their causes: Troubleshooting.
Next steps
Section titled “Next steps”- Connect a Telegram bot: put this agent in a chat people already use.
- Channels overview: every way to reach an agent, and what is live.
- Core API Flow: the full session lifecycle, including streaming replies to a browser.
- Agents and the workflow overview: shape the persona and the graph.
- Authentication: the credential model and revocation.
- Operation reference: every operation with samples in five languages.
- Recipe: Route a ticket: the same ticket agent with a fuller graph.