Concept

Which language?

What you can build in TypeScript, in Python and in any other language, including Go with plain HTTP.

VoiceLayer has full SDKs for TypeScript, a client for Python, and a REST API for everything else. There is no Go, Java, Ruby or .NET SDK. Those languages use the REST API directly, and this page shows how, with working Go programs.

What each language can do

You want toTypeScriptPythonGo and any other language
Send and read messages, manage conversations, webhooks and the rest of the API@voicelayer/apivoicelayerREST, with a client generated from the OpenAPI document
Verify a webhookverifyWebhookverify_webhookBy hand: about 30 lines, below
Follow the event streamstreamEventsstream_eventsServer-Sent Events over HTTP
Answer messages from your code (direct mode)@voicelayer/sdk/directvoicelayer-agents (serve_direct)Read the event stream and reply with the REST API
Give an agent framework your channels as tools@voicelayer/agents (Claude Agent SDK, OpenAI Agents, Vercel AI SDK, LangChain)voicelayer-agents (Claude, OpenAI Agents, LangGraph)The MCP server at https://api.vlayers.ai/v1/mcp, with any MCP client
Write a voice agent in code (defineAgent)@voicelayer/sdkNot availableNot available as an SDK. A hosted custom image is the way: see below
Use your own model or framework as the call's brain@voicelayer/sdk and @voicelayer/agentsNot availableNot available as an SDK. A hosted image can serve the brain route
Run your agent on VoiceLayer (hosted)voicelayer deploy --hostedNot availableA prebuilt image, submitted with --image
Build your own channel@voicelayer/sdk/channelNot availableNot available
Test handlers with no network@voicelayer/sdk/testingNot availableNot available

The Python packages are voicelayer (Python 3.9 or later) and voicelayer-agents (Python 3.10 or later). They cover the REST API, webhooks, the event stream and direct mode. They do not author voice agents or run a brain.

The flow builder builds voice agents without code, and the REST API and the MCP server work with every agent no matter how it was built.

TypeScript

Start with the TypeScript API client for the API, Voice agents in code for agents, and Bring your agent for frameworks.

Python

Start with the Python SDK, and Python frameworks for voicelayer-agents.

Go and any other language: use the REST API

The basics

  • Base URL: https://api.vlayers.ai. Every route starts with /v1/.
  • Authentication: Authorization: Bearer <secret API key>. Use a test key (vl_test_…) while you build. See Authentication and API keys.
  • Bodies: JSON, with Content-Type: application/json.
  • Idempotency: send an Idempotency-Key header (1 to 255 characters; a UUID works) with every send. Reuse the same key to retry the same message, and it is never sent twice. See Errors, retries and idempotency.
  • Errors: a refused request has a JSON body with error (a stable code), message, requestId, retryable and docs.
  • The API description: https://docs.vlayers.ai/openapi.json is an OpenAPI 3.1 document. Load it into any code generator. For Go, oapi-codegen reads it. VoiceLayer does not test generated clients in other languages, so check your first call against a test key.

Send a message in Go

This program uses only the standard library. Put it in a module (go mod init example.com/vl-docs) as send/main.go.

// Send a message with the VoiceLayer REST API from Go, using only the standard library.
//
//	export VOICELAYER_API_KEY=vl_test_...
//	go run ./send +15550123 "Your table is booked for 7pm."
//
// With a test key (vl_test_...) nothing reaches a carrier. Use a reserved test number (+15550100 to +15550199).
package main

import (
	"bytes"
	"crypto/rand"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"
)

// apiError is the body of a refused request.
type apiError struct {
	Code      string `json:"error"`
	Message   string `json:"message"`
	RequestID string `json:"requestId"`
	Retryable bool   `json:"retryable"`
}

func (e *apiError) Error() string {
	return fmt.Sprintf("%s: %s (request %s)", e.Code, e.Message, e.RequestID)
}

type sendResponse struct {
	Message struct {
		ID             string `json:"id"`
		ConversationID string `json:"conversationId"`
		Status         string `json:"status"`
	} `json:"message"`
}

// newUUID returns a random version 4 UUID, used as the idempotency key.
func newUUID() (string, error) {
	var b [16]byte
	if _, err := rand.Read(b[:]); err != nil {
		return "", err
	}
	b[6] = (b[6] & 0x0f) | 0x40
	b[8] = (b[8] & 0x3f) | 0x80
	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}

// send posts one text message on SMS. A retry of the same message must reuse the same key,
// so a request that timed out is never sent twice.
func send(client *http.Client, baseURL, apiKey, idempotencyKey, to, text string) (*sendResponse, error) {
	body, err := json.Marshal(map[string]any{
		"channel": "sms",
		"to":      to,
		"content": map[string]any{"type": "text", "text": text},
	})
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest(http.MethodPost, strings.TrimRight(baseURL, "/")+"/v1/messages", bytes.NewReader(body))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Idempotency-Key", idempotencyKey)

	res, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	raw, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	if res.StatusCode != http.StatusAccepted && res.StatusCode != http.StatusOK {
		var e apiError
		if json.Unmarshal(raw, &e) == nil && e.Code != "" {
			return nil, &e
		}
		return nil, fmt.Errorf("unexpected answer %d: %s", res.StatusCode, raw)
	}
	var out sendResponse
	if err := json.Unmarshal(raw, &out); err != nil {
		return nil, err
	}
	return &out, nil
}

func main() {
	if len(os.Args) != 3 {
		fmt.Fprintln(os.Stderr, "usage: go run ./send <to> <text>")
		os.Exit(2)
	}
	apiKey := os.Getenv("VOICELAYER_API_KEY")
	if apiKey == "" {
		fmt.Fprintln(os.Stderr, "set VOICELAYER_API_KEY")
		os.Exit(2)
	}
	baseURL := os.Getenv("VOICELAYER_API_URL")
	if baseURL == "" {
		baseURL = "https://api.vlayers.ai"
	}
	key, err := newUUID()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	client := &http.Client{Timeout: 30 * time.Second}

	// Retry network errors and retryable refusals, always with the same idempotency key.
	var out *sendResponse
	for attempt := 1; attempt <= 3; attempt++ {
		out, err = send(client, baseURL, apiKey, key, os.Args[1], os.Args[2])
		var refused *apiError
		if err == nil || (errors.As(err, &refused) && !refused.Retryable) {
			break
		}
		time.Sleep(time.Duration(attempt) * time.Second)
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, "send failed:", err)
		os.Exit(1)
	}
	fmt.Printf("message %s is %s (conversation %s)\n", out.Message.ID, out.Message.Status, out.Message.ConversationID)
}
export VOICELAYER_API_KEY=vl_test_...
go run ./send +15550123 "Your table is booked for 7pm."

You see message <id> is sent. With a test key the message never reaches a carrier. The program retries network errors and retryable refusals with the same idempotency key.

Verify a webhook by hand

Every webhook delivery carries this header:

x-voicelayer-signature: t=1792238400,v1=<hex>

To check it:

  1. Read the raw request body. Do not parse and re-encode it first.
  2. Split the header on commas. Take t, and collect every v1 value. Today the header holds one v1=, but accept any number of them and treat one match as enough, so your code keeps working if that changes. To roll a secret, see Roll a signing secret.
  3. Refuse the request if t is more than 300 seconds from now.
  4. Compute HMAC-SHA256 of "<t>.<raw body>" with your subscription's signing secret, used exactly as shown. Hex-encode it.
  5. Compare it to each v1 value in constant time. One match is enough.

Here is a complete handler in Go. Save it as webhook/main.go in the same module.

// Receive VoiceLayer webhooks in Go and verify each one by hand, using only the standard library.
//
//	export VOICELAYER_WEBHOOK_SECRET=...   # shown once when you created the subscription
//	go run ./webhook                       # listens on :3000, or $PORT
//
// VoiceLayer signs "<t>.<raw body>" with HMAC-SHA256 and sends it as
//
//	x-voicelayer-signature: t=<unix seconds>,v1=<hex>
//
// The header holds one v1= today; accept several and treat one match as enough.
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

const (
	signatureHeader = "x-voicelayer-signature"
	tolerance       = 300 * time.Second // refuse a timestamp further than this from now
	maxBody         = 1 << 20           // 1 MiB; most events are far smaller
)

var errBadSignature = errors.New("signature does not match")

// verify checks header against the raw body. It returns an error when the header is missing or
// malformed, the timestamp is outside the tolerance, or no v1 value matches.
func verify(secret string, header string, body []byte, now time.Time) error {
	if header == "" {
		return errors.New("missing " + signatureHeader + " header")
	}
	var timestamp string
	var candidates []string
	for _, part := range strings.Split(header, ",") {
		key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
		if !ok {
			continue
		}
		switch key {
		case "t":
			timestamp = value
		case "v1":
			candidates = append(candidates, value) // keep every one, not only the last
		}
	}
	seconds, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil || len(candidates) == 0 {
		return errors.New("malformed " + signatureHeader + " header")
	}
	age := now.Sub(time.Unix(seconds, 0))
	if age < -tolerance || age > tolerance {
		return errors.New("timestamp outside the tolerance (a replay, or a skewed clock)")
	}

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(timestamp + "."))
	mac.Write(body)
	expected := mac.Sum(nil)

	matched := false
	for _, c := range candidates {
		got, err := hex.DecodeString(c)
		if err != nil {
			continue
		}
		if hmac.Equal(got, expected) { // constant time; do not stop at the first, so timing reveals nothing
			matched = true
		}
	}
	if !matched {
		return errBadSignature
	}
	return nil
}

type event struct {
	ID        string          `json:"id"`
	Type      string          `json:"type"`
	CreatedAt string          `json:"createdAt"`
	Livemode  bool            `json:"livemode"`
	Data      json.RawMessage `json:"data"`
}

func handler(secret string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "POST only", http.StatusMethodNotAllowed)
			return
		}
		// Read the raw body first. Verify before you parse: re-encoding JSON changes the bytes that were signed.
		body, err := io.ReadAll(io.LimitReader(r.Body, maxBody))
		if err != nil {
			http.Error(w, "unreadable body", http.StatusBadRequest)
			return
		}
		if err := verify(secret, r.Header.Get(signatureHeader), body, time.Now()); err != nil {
			log.Printf("rejected delivery: %v", err)
			http.Error(w, "invalid signature", http.StatusBadRequest)
			return
		}
		var ev event
		if err := json.Unmarshal(body, &ev); err != nil || ev.Type == "" {
			http.Error(w, "not a VoiceLayer event", http.StatusBadRequest)
			return
		}
		// Answer fast with a 2xx and do slow work afterwards. A delivery can arrive more than once:
		// process each ev.ID once.
		log.Printf("event %s %s livemode=%t", ev.ID, ev.Type, ev.Livemode)
		w.WriteHeader(http.StatusOK)
	}
}

func main() {
	secret := os.Getenv("VOICELAYER_WEBHOOK_SECRET")
	if secret == "" {
		log.Fatal("set VOICELAYER_WEBHOOK_SECRET")
	}
	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	mux := http.NewServeMux()
	mux.Handle("/", handler(secret))
	log.Printf("listening on :%s", port)
	srv := &http.Server{Addr: ":" + port, Handler: mux, ReadHeaderTimeout: 10 * time.Second}
	log.Fatal(fmt.Errorf("server stopped: %w", srv.ListenAndServe()))
}
export VOICELAYER_WEBHOOK_SECRET=...   # shown once when you created the subscription
go run ./webhook

The program answers 200 for a good delivery and 400 for a bad signature. Create the subscription with POST /v1/webhooks/subscriptions: see Receive with webhooks. Process each event id once, because a delivery can arrive more than once.

A test for the verifier, which checks a header with one v1, several v1 values in either order, a wrong secret, a missing header, a malformed header and a replay, is in the repository at examples/docs/go/webhook/main_test.go. Run it with go test ./....

Follow the event stream

GET /v1/events/stream is a Server-Sent Events stream. Any HTTP client that can read a response as it arrives can use it:

curl -N https://api.vlayers.ai/v1/events/stream \
  -H "Authorization: Bearer $VOICELAYER_API_KEY"

Each frame has an id: (its cursor), an event: and a data: line holding the event JSON. After a dropped connection, send the last cursor you handled as Last-Event-ID. A heartbeat arrives every 15 seconds; a connection silent for longer is dead. See Stream events.

Host a custom image

If you want your own code to run on VoiceLayer, you can ship an image in any language. It must answer a small HTTP contract. See Bring an image in any language for the contract, the push and the --image command. The voicelayer command line, which does the upload, is a Node program.

Next steps

On this page