Integrations

Recovering abandoned carts with a voice AI agent

← All articles

Someone visits your store, fills a cart, clicks “Checkout” and disappears at the payment step. A classic: they got distracted, had second thoughts, the card was declined, they decided to “think about it tonight” and forgot. This is not a cold lead. This is a person who wanted to buy a minute ago and almost did.

The usual response is an email saying “you left something in your cart.” People rarely open it and come back through it even more rarely. Now imagine a call ten minutes after they leave: “Hello! You were filling a cart with us. Is everything OK, did anything stop you from checking out?” People react to that differently.

Let’s build the whole integration. A voice AI agent that pulls the cart contents from your API on its own during the call, talks to the customer and sends the result to managers in Telegram. All the code is below, and you can reproduce it in an evening.

What you’ll get

1
The store detects an abandoned cart and starts a call in AutoCall.kz with one request
↓
2
The AI agent calls the customer and, at the start of the conversation, hits your store’s GET /cart by phone number to find out what is in the cart
↓
3
The conversation: the agent finds out why the order wasn’t placed, helps, and if the customer wants, sends an SMS with a payment link
↓
4
The result arrives at your callback_url, and from there goes to the managers’ Telegram group as a neat card

Note the second step: the agent doesn’t get the cart in advance. It requests it from you itself during the call. That way one agent serves the whole store: it isn’t tied to a specific order and each time looks up the current cart by the customer’s number.

Step 1. Create the agent (once)

The agent is created once and then handles every call. It has three parts: the conversation script (prompt), the fields it must extract (data_schema), and the tools (tools): the cart lookup and sending an SMS.

POST
/api/v1/agents
POST https://autocall.kz/api/v1/agents Authorization: Bearer {your_token} Content-Type: application/json { "name": "Аружан", "voice": "Sulafat", // voices: GET /api/v1/agents/voices "max_seconds": 180, "client_id": "cart-recovery", "prompt": "## Кто ты\nАружан — женский голос интернет-магазина «SHOP». Звонишь клиенту,\nкоторый собрал корзину и начал оформление, но не оплатил. Характер:\nдоброжелательная, лёгкая, без давления. Ты помощник, а не продавец.\n\n## Задача звонка\nПонять, почему заказ не завершён, и помочь довести до конца, если человек\nэтого хочет. Не хочет — вежливо попрощаться и не давить.\n\n## Ход разговора\n1. Первая фраза РОВНО: «Здравствуйте! Это Аружан из магазина SHOP.\n Вы недавно собирали у нас корзину — удобно сейчас говорить?»\n2. Сразу после приветствия узнай состав корзины через инструмент.\n3. Назови, что в корзине, и мягко спроси, всё ли в порядке, не помешало\n ли что-то оформить.\n4. Техническая проблема (не прошла оплата, вопрос по доставке) — предложи\n помощь; если клиент готов вернуться, отправь ссылку на оплату.\n5. Передумал или просто смотрел — спокойно прими, поблагодари, попрощайся.\n\n## Границы\nНе дави и не уговаривай после отказа. Скидок, которых нет, не обещай.\nО товаре и цене говори только то, что вернул инструмент.", "data_schema": [ { "key": "outcome", "label": "Итог" }, // ready to order / changed mind / needs help / call back { "key": "reason", "label": "Причина" }, // why checkout wasn’t completed { "key": "comment", "label": "Комментарий" } ], "tools": [ { "type": "http", "name": "order", // the agent calls this as the call_order function "when": "сразу после приветствия, чтобы узнать состав корзины", "method": "GET", "url": "https://shop.kz/api/cart?phone={{phone}}", "headers": [{ "key": "Authorization", "value": "Bearer SHOP_TOKEN" }], "response_template": "В корзине: {{items}} на сумму {{total}} тенге.", "fallback": "Заказ поднять не удалось, но давайте разберёмся вместе." }, { "type": "sms", "name": "link", // function send_sms_link "when": "если клиент готов вернуться к оформлению", "text": "Ваша корзина ждёт вас: https://shop.kz/cart" } ] }

A few things worth spelling out.

The prompt sections are required. ## Кто ты (who you are), ## Задача звонка (call goal) and ## Ход разговора (conversation flow) must be present; without them, creating the agent returns 422. We add the safety rules ourselves, so you don’t need to put them in the prompt.

The order tool is the integration itself. During the call the agent calls it as a function, and we send a GET to your store with {{phone}}, the customer’s number, filled into the URL. Whatever your server returns, the agent says using the response_template. More on substitution a bit further down.

The response comes back with the status generating. The agent isn’t ready right away: we spend a couple of seconds computing its settings. Wait for ready by polling GET /api/v1/agents/{id}, and save the id: you’ll need it to start calls.

Step 2. Your store returns the cart by phone number

This is the only endpoint you need to set up on your side. The agent hits it during the call. You choose the response format; the only requirement is that the field names match the ones in the agent’s response_template ({{items}} and {{total}}).

GET
your store · /api/cart
GET https://shop.kz/api/cart?phone=77010000000 ← 200 OK { "items": "робот-пылесос Samsung и набор насадок", "total": "45 000" }

We take this JSON, put items and total into the template, and the agent says: “Your cart has a Samsung robot vacuum and an attachment set, 45,000 tenge in total.” If your server doesn’t respond or returns something unexpected, the agent says the fallback and carries on; the call doesn’t drop.

The endpoint is exposed to the public internet, so protect it with a token (we send your Authorization from the tool settings) and return only the cart contents by phone number, with no addresses, cards or anything else.

Step 3. Catch the abandoned cart and start the call

Now the store side. Once your system decides a cart is abandoned (say, 10 minutes have passed since the payment step without success), one request starts the call.

Python
shop_backend.py
import requests AUTOCALL_TOKEN = "your_autocall_token" AGENT_ID = 42 # id of the ready agent from step 1 def call_about_cart(phone: str, name: str): requests.post( "https://autocall.kz/api/v1/autocalls", headers={"Authorization": f"Bearer {AUTOCALL_TOKEN}"}, json={ "name": "Возврат корзины", "type": "agent", "agent_id": AGENT_ID, "time_from": "10:00:00", # call only at reasonable hours "time_to": "20:00:00", "max_tries": 1, # one call, no hammering "callback_url": "https://your-service.kz/autocall/callback", "list_id": [ { "number": phone, "variables": {"phone": phone.lstrip("+"), "name": name} } ] } )

The whole trick is in variables. The phone key from there is what gets filled into {{phone}} in the tool URL when the agent goes for the cart. Whatever you put in the variables, the tool can use.

The same request with curl, if your backend isn’t in Python:

cURL
start a call
curl -X POST https://autocall.kz/api/v1/autocalls \ -H "Authorization: Bearer your_token" \ -H "Content-Type: application/json" \ -d '{ "name": "Возврат корзины", "type": "agent", "agent_id": 42, "time_from": "10:00:00", "time_to": "20:00:00", "max_tries": 1, "callback_url": "https://your-service.kz/autocall/callback", "list_id": [{ "number": "+77010000000", "variables": { "phone": "77010000000", "name": "Айгерим" } }] }'

Step 4. Set up a Telegram bot

The bot posts the result to the managers’ group. Three quick steps:

  1. Send @BotFather the /newbot command and set a name. In reply you get a token like 7712345678:AAExxxxxxxxxxxx.
  2. Add the bot to your work group and allow it to post messages.
  3. Find the group’s chat_id: temporarily add @getidsbot to it or open https://api.telegram.org/bot{TOKEN}/getUpdates. The group id is a negative number.

Step 5. Receive the result and post it to Telegram

All that’s left is a small service that receives our callback and turns it into a message. We call callback_url on every change to the call, so the first thing to do is separate the end of the conversation from the intermediate events.

A reliable sign that the conversation took place: the last element of the status_tries array equals success. Then data already holds the fields the agent collected.

Python
callback_service.py
from flask import Flask, request import requests app = Flask(__name__) BOT_TOKEN = "7712345678:AAExxxxxxxxxxxx" CHAT_ID = "-1001234567890" # managers’ group id @app.post("/autocall/callback") def callback(): call = request.json.get("call", {}) tries = call.get("status_tries") or [] # call still in progress or not answered: wait for the end, send nothing if not tries or tries[-1] != "success": return "", 204 data = call.get("data") or {} text = ( "🛒 Недобитая корзина — итог звонка\n\n" f"📞 {call.get('number', '—')} · {call.get('duration', 0)} сек\n\n" f"Итог: {data.get('outcome', '—')}\n" f"Причина: {data.get('reason', '—')}\n" f"Комментарий: {data.get('comment', '—')}" ) requests.post( f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage", json={"chat_id": CHAT_ID, "text": text, "parse_mode": "HTML"} ) return "", 204

It runs as a regular Flask app behind any reverse proxy with HTTPS. The /autocall/callback path is exactly the one you set in callback_url when starting the call.

If you also want the result in your CRM, not just in the chat, that is exactly what the callback is for. data holds all fields from data_schema plus data["_transcript"], the full transcript of the conversation, if you need it.

What it sounds like on a call

Live conversation
AruzhanHello! This is Aruzhan from SHOP. You recently filled a cart with us. Is now a good time to talk?
CustomerUh, yes, what is it?
Aruzhan(calls call_order, the store responds) One moment, let me pull up your order… I see a Samsung robot vacuum and an attachment set for 45,000. Is that right? Did anything stop you from checking out?
CustomerWell, I wanted to, but my card got declined for some reason, so I gave up.
AruzhanI see, that happens. I can send you a payment link by SMS, so you can try another card or Kaspi, whichever is easier. Shall I send it?
CustomerYes, please.
Aruzhan(calls send_sms_link) Sent. Your cart is there too, everything is saved. Thank you for your time!

Meanwhile, the managers get this card in their group:

🛒 Unfinished cart: call result
📞 +7 701 000 00 00 · 58 sec
Result: ready to order, link sent
Reason: card payment failed
Comment: will try Kaspi

The manager doesn’t need to listen to the recording and guess: the agent has already broken the conversation down into fields. You can see who really wanted to buy and where they got stuck, and who was just browsing.

Details you shouldn’t skip

Call once and at a reasonable time. The request has max_tries: 1 and a 10:00–20:00 window for a reason. A warm lead turns into an annoyed person the moment you call a second time or at nine in the evening.

Look beyond success. If the last status_tries is no_answer or busy, there was no conversation and data will have no fields. You can simply ignore these events, or use them to send that “you forgot your cart” email, now as a backup channel.

Don’t call people who didn’t knowingly give you their number. Here everything is clean: the customer entered their phone number at checkout and started the purchase themselves. This isn’t a bought database or cold calling, and that is exactly why such a call works and doesn’t feel intrusive. Don’t carry this approach over to an audience that didn’t ask you for it.

Test it on yourself. Before you go live with customers, run a call to your own number with a test cart. Separately, the “Test” button on the agent card calls you in the browser, so you can hear how it talks before the first real call.

What’s next

We built one setup, but the building blocks are reusable. The same callback_url puts data into your CRM, the same HTTP tool lets the agent fetch anything in your system, not just the cart, and the same call launch can be tied to any event: not only an abandoned cart, but also “request unanswered for a day,” “subscription ending,” “delivery arrived.”

The full method specification is in openapi.yaml, and an overview with examples is on the API and integrations page. We wrote a separate article on how the agent itself works and how it differs from a scenario.

Build your own integration

Get an API token and launch your first agent today.

Try it free →