Add a resolver route
Copy
// Add this route to your own Express app (npm install express).
// The path is yours to choose; this example uses /api/voice-reply.
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';
const app = express();
app.post('/api/voice-reply', express.text({ type: 'application/json' }), async (req, res) => {
// 1. Make sure the request comes from Borminto.
const expected = 'v1=' + createHmac('sha256', process.env.BORMINTO_RESOLVER_SECRET)
.update(`${req.get('X-Borminto-Timestamp')}.${req.body}`).digest('hex');
const received = req.get('X-Borminto-Signature') ?? '';
if (received.length !== expected.length || !timingSafeEqual(Buffer.from(received), Buffer.from(expected))) {
return res.sendStatus(401);
}
// 2. Read what the caller said.
const { text, history, language } = JSON.parse(req.body);
// 3. Decide the reply with your own AI, RAG, database or tools.
const answer = await myAssistant(text, history, language);
// 4. Tell Borminto what to say.
res.json({ action: 'say', text: answer });
});
app.listen(Number(process.env.PORT ?? 3000));
// Replace with your own logic.
async function myAssistant(text) {
return `You said: ${text}. A consultation costs 300 EGP.`;
}
<?php
// Add this route to routes/api.php in your own Laravel app. The path is yours to choose;
// Laravel adds /api, so this one is https://your-app.com/api/voice-reply.
// Also add this line to config/services.php:
// 'borminto' => ['resolver_secret' => env('BORMINTO_RESOLVER_SECRET')],
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::post('/voice-reply', function (Request $request) {
// 1. Make sure the request comes from Borminto.
$expected = 'v1='.hash_hmac('sha256', $request->header('X-Borminto-Timestamp').'.'.$request->getContent(), config('services.borminto.resolver_secret'));
abort_unless(hash_equals($expected, (string) $request->header('X-Borminto-Signature')), 401);
// 2. Read what the caller said.
$text = $request->input('text');
// 3. Decide the reply with your own AI, RAG, database or tools.
$answer = "You said: {$text}. A consultation costs 300 EGP.";
// 4. Tell Borminto what to say.
return ['action' => 'say', 'text' => $answer];
});
# Add this route to your own FastAPI app (pip install fastapi uvicorn).
# The path is yours to choose; this example uses /api/voice-reply.
import hashlib
import hmac
import os
from fastapi import FastAPI, Request, Response
app = FastAPI()
@app.post("/api/voice-reply")
async def resolve(request: Request):
# 1. Make sure the request comes from Borminto.
body = await request.body()
timestamp = request.headers.get("X-Borminto-Timestamp", "")
expected = "v1=" + hmac.new(os.environ["BORMINTO_RESOLVER_SECRET"].encode(), timestamp.encode() + b"." + body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, request.headers.get("X-Borminto-Signature", "")):
return Response(status_code=401)
# 2. Read what the caller said.
question = await request.json()
# 3. Decide the reply with your own AI, RAG, database or tools.
answer = f"You said: {question['text']}. A consultation costs 300 EGP."
# 4. Tell Borminto what to say.
return {"action": "say", "text": answer}
Complete resolver: model, search and a tool
Copy
// Node.js 18+, no dependencies.
// Env: BORMINTO_RESOLVER_SECRET, AI_BASE_URL (any OpenAI-compatible API, e.g. https://api.openai.com/v1), AI_API_KEY, AI_MODEL
import { createHmac, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
const secret = process.env.BORMINTO_RESOLVER_SECRET;
const done = new Map(); // request_id → reply, so a retry never repeats an action
createServer((request, response) => {
let body = '';
request.on('data', (chunk) => { body += chunk; });
request.on('end', async () => {
// Accept only requests signed by Borminto in the last 5 minutes.
const timestamp = request.headers['x-borminto-timestamp'] ?? '';
const expected = 'v1=' + createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex');
const received = String(request.headers['x-borminto-signature'] ?? '');
const fresh = Math.abs(Date.now() / 1000 - Number(timestamp)) < 300;
if (!fresh || received.length !== expected.length || !timingSafeEqual(Buffer.from(received), Buffer.from(expected))) {
response.writeHead(401).end();
return;
}
const question = JSON.parse(body);
if (!done.has(question.request_id)) done.set(question.request_id, await findAnswer(question));
response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(done.get(question.request_id)));
});
}).listen(Number(process.env.PORT ?? 3000));
// 1. Your RAG: return the passages that answer the question.
async function searchKnowledge(text) {
// Replace with your own search (a vector database, your CMS…). A fixed list keeps the example runnable.
return ['A consultation costs 300 EGP.', 'We are open 4 pm to 9 pm, Saturday to Thursday.', 'The clinic is in Nasr City, Cairo.'];
}
// 2. Your actions: tools the model may call, and the code that runs them.
const tools = [{
type: 'function',
function: {
name: 'book_appointment',
description: 'Book a clinic appointment once the caller gave a day and a time.',
parameters: { type: 'object', properties: { day: { type: 'string' }, time: { type: 'string' } }, required: ['day', 'time'] },
},
}];
async function bookAppointment({ day, time }) {
// Replace with your booking system.
return `Done, you're booked for ${day} at ${time}.`;
}
// 3. The brain: one model call that answers, asks for missing details, or books.
async function findAnswer({ text, history, state, language }) {
const facts = await searchKnowledge(text);
const messages = [
{ role: 'system', content: `You are a clinic receptionist on a phone call. The caller's words come from speech-to-text and may contain sound-alike mistakes. Work out what they meant from the whole sentence and the conversation, and reply to that. Reply in one or two short sentences in the caller's language (${language}), using only these facts:\n${facts.join('\n')}` },
...history.map((message) => ({ role: message.role === 'caller' ? 'user' : 'assistant', content: message.text })),
{ role: 'user', content: text },
];
try {
const response = await fetch(`${process.env.AI_BASE_URL}/chat/completions`, {
method: 'POST',
signal: AbortSignal.timeout(2000), // The caller is waiting on the phone.
headers: { Authorization: `Bearer ${process.env.AI_API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ model: process.env.AI_MODEL, messages, tools }),
});
const message = (await response.json()).choices[0].message;
const call = message.tool_calls?.[0];
if (call?.function.name === 'book_appointment') {
return { action: 'say', text: await bookAppointment(JSON.parse(call.function.arguments)), state: { ...state, booked: true } };
}
if (message.content) return { action: 'say', text: message.content };
} catch {
// Too slow or unavailable: fall through.
}
// Borminto's voice assistant phrases a reply from your facts instead.
return { action: 'facts', facts };
}
<?php
// PHP 8.1+ with curl, no packages. Run: php -S 0.0.0.0:3000 resolver.php
// Env: BORMINTO_RESOLVER_SECRET, AI_BASE_URL (any OpenAI-compatible API, e.g. https://api.openai.com/v1), AI_API_KEY, AI_MODEL
// Accept only requests signed by Borminto in the last 5 minutes.
$body = (string) file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_BORMINTO_TIMESTAMP'] ?? '';
$expected = 'v1='.hash_hmac('sha256', $timestamp.'.'.$body, (string) getenv('BORMINTO_RESOLVER_SECRET'));
if (abs(time() - (int) $timestamp) > 300 || ! hash_equals($expected, $_SERVER['HTTP_X_BORMINTO_SIGNATURE'] ?? '')) {
http_response_code(401);
exit;
}
$question = json_decode($body, true);
// Keep each reply by request_id so a retry never repeats an action.
$saved = sys_get_temp_dir().'/borminto-'.hash('sha256', $question['request_id']).'.json';
$reply = is_file($saved) ? json_decode((string) file_get_contents($saved), true) : findAnswer($question);
file_put_contents($saved, json_encode($reply));
header('Content-Type: application/json');
echo json_encode($reply, JSON_UNESCAPED_UNICODE);
// 1. Your RAG: return the passages that answer the question.
function searchKnowledge(string $text): array
{
// Replace with your own search (a vector database, your CMS…). A fixed list keeps the example runnable.
return ['A consultation costs 300 EGP.', 'We are open 4 pm to 9 pm, Saturday to Thursday.', 'The clinic is in Nasr City, Cairo.'];
}
// 2. Your actions: the code behind each tool the model may call.
function bookAppointment(array $arguments): string
{
// Replace with your booking system.
return "Done, you're booked for {$arguments['day']} at {$arguments['time']}.";
}
// 3. The brain: one model call that answers, asks for missing details, or books.
function findAnswer(array $question): array
{
$facts = searchKnowledge($question['text']);
$messages = [['role' => 'system', 'content' => "You are a clinic receptionist on a phone call. The caller's words come from speech-to-text and may contain sound-alike mistakes. Work out what they meant from the whole sentence and the conversation, and reply to that. Reply in one or two short sentences in the caller's language ({$question['language']}), using only these facts:\n".implode("\n", $facts)]];
foreach ($question['history'] as $message) {
$messages[] = ['role' => $message['role'] === 'caller' ? 'user' : 'assistant', 'content' => $message['text']];
}
$messages[] = ['role' => 'user', 'content' => $question['text']];
$tools = [[
'type' => 'function',
'function' => [
'name' => 'book_appointment',
'description' => 'Book a clinic appointment once the caller gave a day and a time.',
'parameters' => ['type' => 'object', 'properties' => ['day' => ['type' => 'string'], 'time' => ['type' => 'string']], 'required' => ['day', 'time']],
],
]];
$curl = curl_init(rtrim((string) getenv('AI_BASE_URL'), '/').'/chat/completions');
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT_MS => 2000, // The caller is waiting on the phone.
CURLOPT_HTTPHEADER => ['Authorization: Bearer '.getenv('AI_API_KEY'), 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode(['model' => getenv('AI_MODEL'), 'messages' => $messages, 'tools' => $tools]),
]);
$message = json_decode((string) curl_exec($curl), true)['choices'][0]['message'] ?? null;
$call = $message['tool_calls'][0]['function'] ?? null;
if (($call['name'] ?? null) === 'book_appointment') {
return ['action' => 'say', 'text' => bookAppointment(json_decode($call['arguments'], true)), 'state' => ['booked' => true]];
}
if (! empty($message['content'])) {
return ['action' => 'say', 'text' => $message['content']];
}
// Too slow or unavailable: Borminto's voice assistant phrases a reply from your facts instead.
return ['action' => 'facts', 'facts' => $facts];
}
# Python 3.10+, no packages. Run: python3 resolver.py
# Env: BORMINTO_RESOLVER_SECRET, AI_BASE_URL (any OpenAI-compatible API, e.g. https://api.openai.com/v1), AI_API_KEY, AI_MODEL
import hashlib
import hmac
import json
import os
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = os.environ["BORMINTO_RESOLVER_SECRET"].encode()
DONE = {} # request_id -> reply, so a retry never repeats an action
TOOLS = [{
"type": "function",
"function": {
"name": "book_appointment",
"description": "Book a clinic appointment once the caller gave a day and a time.",
"parameters": {"type": "object", "properties": {"day": {"type": "string"}, "time": {"type": "string"}}, "required": ["day", "time"]},
},
}]
def search_knowledge(text):
# 1. Your RAG. Replace with your own search (a vector database, your CMS…). A fixed list keeps the example runnable.
return ["A consultation costs 300 EGP.", "We are open 4 pm to 9 pm, Saturday to Thursday.", "The clinic is in Nasr City, Cairo."]
def book_appointment(day, time):
# 2. Your action. Replace with your booking system.
return f"Done, you're booked for {day} at {time}."
def find_answer(question):
# 3. The brain: one model call that answers, asks for missing details, or books.
facts = search_knowledge(question["text"])
messages = [{"role": "system", "content": f"You are a clinic receptionist on a phone call. The caller's words come from speech-to-text and may contain sound-alike mistakes. Work out what they meant from the whole sentence and the conversation, and reply to that. Reply in one or two short sentences in the caller's language ({question['language']}), using only these facts:\n" + "\n".join(facts)}]
messages += [{"role": "user" if m["role"] == "caller" else "assistant", "content": m["text"]} for m in question["history"]]
messages.append({"role": "user", "content": question["text"]})
request = urllib.request.Request(
os.environ["AI_BASE_URL"].rstrip("/") + "/chat/completions",
data=json.dumps({"model": os.environ["AI_MODEL"], "messages": messages, "tools": TOOLS}).encode(),
headers={"Authorization": "Bearer " + os.environ["AI_API_KEY"], "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=2) as response: # The caller is waiting on the phone.
message = json.load(response)["choices"][0]["message"]
call = (message.get("tool_calls") or [{}])[0].get("function", {})
if call.get("name") == "book_appointment":
return {"action": "say", "text": book_appointment(**json.loads(call["arguments"])), "state": {"booked": True}}
if message.get("content"):
return {"action": "say", "text": message["content"]}
except Exception:
pass # Too slow or unavailable: fall through.
# Borminto's voice assistant phrases a reply from your facts instead.
return {"action": "facts", "facts": facts}
class Resolver(BaseHTTPRequestHandler):
def do_POST(self):
# Accept only requests signed by Borminto in the last 5 minutes.
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
timestamp = self.headers.get("X-Borminto-Timestamp", "")
expected = "v1=" + hmac.new(SECRET, timestamp.encode() + b"." + body, hashlib.sha256).hexdigest()
fresh = timestamp.isdigit() and abs(time.time() - int(timestamp)) < 300
if not fresh or not hmac.compare_digest(expected, self.headers.get("X-Borminto-Signature", "")):
self.send_response(401)
self.end_headers()
return
question = json.loads(body)
reply = DONE.get(question["request_id"])
if reply is None:
reply = DONE[question["request_id"]] = find_answer(question)
payload = json.dumps(reply, ensure_ascii=False).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
HTTPServer(("0.0.0.0", int(os.environ.get("PORT", 3000))), Resolver).serve_forever()