Work a conversation

Take over a conversation from the agent and hand it back, the way your team does in the inbox, with platic.conversations. The script uses a chat it creates, so it does not touch your real conversations.

Before you start

  • A Platica API key in PLATIC_API_KEY, with write access to conversations.
  • Chat turns use your workspace's credits.
  • Node.js 20.3 or newer and npm install platic-sdk.

Pause, wait, resume and archive

  • Creates an agent and starts a chat as a contact. The turn's id is the conversation's id.
  • Pauses the agent: the conversation becomes supervised and a reply in progress stops. Pausing again answers changed: false and does nothing.
  • Changes the topic with expectedVersion, so a change made since the read is not overwritten.
  • Waits: hands the conversation back to the agent (automatic) without replying now. The agent reads the instruction when the contact writes next.
  • Pauses again and resumes: the agent replies to the contact now, following the instruction. The script reads the history until the reply shows up.
  • Archives the conversation and deletes the agent and the contact.

The code

import { ConflictError, Platic, PreconditionFailedError } from "platic-sdk";

const apiKey = process.env.PLATIC_API_KEY;
if (!apiKey) {
  console.error("Set PLATIC_API_KEY to a Platica API key (pl_key_…).");
  process.exit(1);
}

const platic = new Platic({ apiKey });

const agent = await platic.agents.create({
  name: "Bookings",
  instructions: "You book appointments for Acme's salon. Be brief.",
});
let contactId: string | undefined;

try {
  // A chat turn creates the conversation: its `id` is the conversation's ID.
  const turn = await platic.chat.send({
    agentId: agent.id,
    client: { id: `example-${Date.now()}`, name: "Ana López" },
    message: "Hi! Can I book a haircut for Monday?",
  });
  contactId = turn.clientId;
  const conversationId = turn.id;

  // 1. Your team takes over: the agent stops, including a reply it is writing.
  const paused = await platic.conversations.pause(conversationId);
  console.log(`pause: ${paused.data.operation}, changed: ${paused.meta.changed}`);
  const again = await platic.conversations.pause(conversationId);
  console.log(`pause again: changed: ${again.meta.changed}`);

  // 2. Change the topic only if nobody changed the conversation since you read it.
  const { meta } = await platic.conversations.get(conversationId, { fields: ["topic"] });
  try {
    const updated = await platic.conversations.update(conversationId, { topic: "Monday booking" }, { expectedVersion: meta.resourceVersion });
    console.log(`topic: ${updated.data.topic}`);
  } catch (error) {
    if (!(error instanceof PreconditionFailedError)) throw error;
    console.log("it changed since it was read; read it again and decide again");
  }

  // 3. Hand it back without replying now: the agent reads the note when Ana writes next.
  const waiting = await platic.conversations.wait(conversationId, {
    instruction: "Monday is full. If they ask again, offer Tuesday at 10:00.",
  });
  console.log(`wait: ${waiting.data.operation}, changed: ${waiting.meta.changed}`);

  // 4. Take it again, then hand it back so the agent replies now.
  await platic.conversations.pause(conversationId);
  const before = await platic.conversations.messages.list(conversationId, { limit: 1 });
  const resumed = await platic.conversations.resume(conversationId, {
    instruction: "Tell Ana that Monday is full and offer Tuesday at 10:00.",
  });
  console.log(`resume: ${resumed.data.operation}, changed: ${resumed.meta.changed}`);
  console.log(`agent: ${await nextReply(conversationId, before.data[0]?.id)}`);

  // 5. Close it. An open case would stop the archive.
  try {
    const archived = await platic.conversations.archive(conversationId);
    console.log(`archive: ${archived.data.status}, changed: ${archived.meta.changed}`);
  } catch (error) {
    if (!(error instanceof ConflictError && error.code === "CASE_OPEN")) throw error;
    console.log("close these cases first:", error.caseIds);
  }
} finally {
  if (contactId) await platic.clients.delete(contactId);
  await platic.agents.delete(agent.id);
  console.log("removed the example's agent and contact");
}

// The reply starts after `resume` answers: read the newest messages until the agent's shows up.
async function nextReply(conversationId: string, lastSeenId: string | undefined): Promise<string> {
  for (let attempt = 0; attempt < 30; attempt += 1) {
    const page = await platic.conversations.messages.list(conversationId, { limit: 5 });
    const reply = page.data.find((message) => message.role === "assistant");
    if (reply && reply.id !== lastSeenId) return reply.content ?? "";
    await new Promise((resolve) => setTimeout(resolve, 2_000));
  }
  return "(no reply yet)";
}

Run it

Save the code in conversations.ts and run it with tsx.

export PLATIC_API_KEY=pl_key_...
npx tsx conversations.ts

What to expect

pause: supervised, changed: true
pause again: changed: false
topic: Monday booking
wait: automatic, changed: true
resume: automatic, changed: true
agent: Hi Ana, Monday is fully booked. Would Tuesday at 10:00 work for you?
archive: archived, changed: true
removed the example's agent and contact

resume answers as soon as the agent starts its reply; the reply itself arrives a moment later. Any action whose result already holds answers changed: false and does nothing, as the second pause shows.

API reference used

Next steps