Documentation

Poe Embed Api

The window.Poe object provides methods to interact with the Poe Bot Query API directly from browser JavaScript in Canvas apps. This enables you to build interactive experiences that can call bots programmatically, execute tools automatically, and stream responses in real-time.

Quick Example

// Simple bot query
for await (const chunk of window.Poe.stream({
  bot: "GPT-5.4",
  prompts: "What is 2+2?"
})) {
  console.log(chunk.text);
}

API Methods

window.Poe.sendUserMessage()

Send a message in the chat on behalf of the current user. This is useful when you want the canvas app to trigger bot responses and receive them via a callback handler.

Signature

window.Poe.sendUserMessage<Stream extends boolean>(
  text: string,
  options?: {
    attachments?: File[];
    stream?: Stream;
    openChat?: boolean;
    handler?: string;
    handlerContext?: HandlerContext;
  }
): Promise<{ success: boolean }>

Parameters

  • text (string, required): The text to send. In most cases this should start with @BotName to specify which bot should respond.
  • options.attachments (File[], optional): Files to include in the user message (e.g., from an <input type="file"> element)
  • options.stream (boolean, optional): Whether to invoke the handler with incomplete results as they are available (true) or only with the final complete result (false). Each result contains all tokens received so far.
  • options.openChat (boolean, optional): Whether to open the chat UI when sending the message
  • options.handler (string, optional): The registered name of the handler function to invoke with the results
  • options.handlerContext (HandlerContext, optional): Additional context object to pass to the handler

Returns

Promise resolving to an object with:

  • success (boolean): Whether the message was successfully sent

Errors

May throw a PoeEmbedAPIError with one of these error types:

  • UNKNOWN: Something unexpected happened
  • INVALID_INPUT: The input was invalid (check error.message for details)
  • USER_REJECTED_CONFIRMATION: User rejected the required confirmation
  • ANOTHER_CONFIRMATION_IS_OPEN: Another confirmation is already open

Example

// Register a handler first
window.Poe.registerHandler("myHandler", (result) => {
  const message = result.responses[0];
  console.log("Status:", message.status);
  console.log("Content:", message.content);

  if (message.status === "complete") {
    console.log("Bot response complete!");
  }
});

// Send message and stream results to handler
await window.Poe.sendUserMessage(
  "@GPT-5.4 Tell me a story",
  {
    stream: true,
    handler: "myHandler",
    openChat: false
  }
);

window.Poe.registerHandler()

Register a callback function to receive the results of sendUserMessage() calls. The callback receives results if the handler name matches the handler option passed to sendUserMessage().

Signature

window.Poe.registerHandler(
  name: string,
  func: (result: SendUserMessageResult, context: HandlerContext) => void
): VoidFunction

Parameters

  • name (string, required): String identifier for the handler. Used to associate responses with this callback.
  • func (function, required): Callback function that receives response messages. The function receives:
    • result (SendUserMessageResult): Contains response messages with their content and status
    • context (HandlerContext): The handlerContext object specified in the sendUserMessage() call

Returns

A function that when called, unregisters the handler.

Example

// Register handler that updates UI as content streams in
window.Poe.registerHandler("streamHandler", (result) => {
  const outputDiv = document.getElementById('bot-output');
  const message = result.responses[0];

  // Update UI with streaming content
  outputDiv.textContent = message.content;

  // Show loading indicator while incomplete
  if (message.status === "incomplete") {
    outputDiv.classList.add('streaming');
  } else if (message.status === "complete") {
    outputDiv.classList.remove('streaming');
  } else if (message.status === "error") {
    outputDiv.classList.add('error');
    console.error("Error:", message.statusText);
  }
});

// Trigger the message
await window.Poe.sendUserMessage(
  "@GPT-5.4 Write a poem",
  { stream: true, handler: "streamHandler" }
);

window.Poe.getTriggerMessage()

Returns the message that triggered the canvas tab to open. This is useful when you need to access the original user message or bot response that launched your canvas app.

Signature

window.Poe.getTriggerMessage(): Promise<Message | null>

Parameters

None

Returns

Promise resolving to:

  • Message object if there was a trigger message
  • null if there was no trigger message (e.g., canvas opened manually)

The Message object contains:

  • text (string): Text content of the message
  • role ("user" | "bot" | "system" | "tool"): Role of the message sender
  • contentType ("text/markdown" | "text/plain", optional): Content format
  • attachments (Attachment[], optional): List of file attachments

Example

// Get the message that opened this canvas
const triggerMessage = await window.Poe.getTriggerMessage();

if (triggerMessage) {
  console.log("Triggered by:", triggerMessage.role);
  console.log("Message:", triggerMessage.text);

  if (triggerMessage.attachments) {
    console.log("Attachments:", triggerMessage.attachments.length);
  }
} else {
  console.log("No trigger message (canvas opened manually)");
}

window.Poe.getDefaultChat()

Get recent messages from the current chat along with the list of participants. This is useful when you need to access the conversation history or understand who is participating in the chat.

Signature

window.Poe.getDefaultChat(limit?: number): Promise<{
  messages: Message[];
  userMembers: Array<UserMember>;
}>

Parameters

  • limit (number, optional): Maximum number of messages to retrieve (default: 50)

Returns

Promise resolving to an object with:

  • messages (Message[]): Array of recent messages from the chat, ordered chronologically
  • userMembers (UserMember[]): Array of participants in the chat

The Message object contains:

  • text (string): Text content of the message
  • role ("user" | "bot" | "system" | "tool"): Role of the message sender
  • contentType ("text/markdown" | "text/plain", optional): Content format
  • attachments (Attachment[], optional): List of file attachments

The UserMember object contains information about chat participants such as user IDs and display names.

Example: Check Participants

// Check who is in the chat
const chat = await window.Poe.getDefaultChat();

console.log("Chat participants:");
chat.userMembers.forEach(member => {
  console.log(`  - ${member.userId}`);
});

Example: Build Context for Bot Query

// Get chat history to provide context to a bot
const chat = await window.Poe.getDefaultChat();

// Convert to conversation history format for stream
const conversationHistory = chat.messages.map(msg => ({
  text: msg.text,
  role: msg.role,
  attachments: msg.attachments
}));

// Add a new user message and query with full context
conversationHistory.push({
  text: "Based on our conversation, what should we do next?",
  role: "user"
});

const response = window.Poe.stream({
  bot: "GPT-5.4",
  prompts: conversationHistory
});

for await (const chunk of response) {
  console.log(chunk.text);
}

window.Poe.addMessage()

Add a message to the chat UI. If sent from a "Canvas App" the message will appear as being from the "Canvas App". If sent from an "Unpublished Canvas App" it will appear as if it was sent by the current user.

Signature

window.Poe.addMessage(message: string | WritableMessage): Promise<{ success: boolean }>

Parameters

  • message (string | WritableMessage, required): The message text or WritableMessage instance to add to the chat. When a WritableMessage is passed, it automatically calls toMarkdown() to format the message with inline refs.

Returns

Promise resolving to an object with:

  • success (boolean): Whether the message was successfully added

Example: String Message

// Add a bot message to the chat
const result = await window.Poe.addMessage("Hello! I've processed your request.");
if (result.success) {
  console.log("Message added successfully");
}

Example: WritableMessage

// Build and add a message
const msg = new WritableMessage();
msg.write("Results:\n");
msg.write("- Item 1\n");
msg.write("- Item 2");

await window.Poe.addMessage(msg);
// Message is automatically formatted as markdown

window.Poe.startMessage()

Build a message using a WritableMessage and automatically add it to the chat when complete. This provides a convenient callback pattern for accumulating streaming responses.

Signature

window.Poe.startMessage(
  callback: (msg: WritableMessage) => Promise<void>
): Promise<{ success: boolean }>

Parameters

  • callback (function, required): Async function that receives a WritableMessage instance

Returns

Promise resolving to an object with:

  • success (boolean): Whether the message was successfully added

Example: Streaming Bot Response

await window.Poe.startMessage(async (msg) => {
  for await (const chunk of window.Poe.stream({
    bot: "GPT-5.4",
    prompts: "Tell me about TypeScript"
  })) {
    msg.write(chunk);
  }
});
// Message is automatically added to chat with proper markdown formatting

Example: Manual Message Building

await window.Poe.startMessage(async (msg) => {
  msg.write("Processing your request...\n\n");

  // Simulate some work
  const result = await processData();

  if (result.success) {
    msg.write("Result: ");
    msg.write(result.data);
  } else {
    msg.overwrite("An error occurred. Please try again.");
  }
});

WritableMessage

Helper class for building messages from streaming partial responses. Provides methods to accumulate text, handle replace responses, and collect attachments.

Constructor

const msg = new WritableMessage();

Properties

text: string

Get or set the message text directly.

attachments: Attachment[]

Get or set the attachments array directly. Contains Attachment objects (files already uploaded to Poe). Use attachFile() to upload and add files.

Methods

write(input: string | PartialMessage): void

Appends text or processes a PartialMessage from window.Poe.stream(). When passed a PartialMessage, it handles both append and replace operations based on isReplaceResponse, and collects attachments automatically.

overwrite(text: string): void

Replaces the entire message text with new text.

async attachFile(fileOrAttachment: File | Attachment): Promise<Attachment>

Upload a file and add it to the attachments array. If a File object is provided, it will be uploaded using window.Poe.uploadFile() automatically. If an Attachment object is provided, it will be added directly.

Example:

const msg = new WritableMessage("Check out this image:");
const file = document.querySelector('input[type="file"]').files[0];
await msg.attachFile(file);
// File is now uploaded and added to msg.attachments
toMarkdown(): string

Formats the complete message as markdown with inline reference links at the top. Attachments with inlineRef are formatted as [refId]: url.

toMessage(): Message

Converts the WritableMessage to a Message object with text and attachments.

Example: Consuming Streaming Messages

const msg = new WritableMessage();

for await (const chunk of window.Poe.stream({
  bot: "GPT-5.4",
  prompts: "Hello"
})) {
  msg.write(chunk);
}

const text = msg.text;
const markdown = msg.toMarkdown();
await window.Poe.addMessage(markdown);

Example: Manual Construction

const msg = new WritableMessage();
msg.write("Hello ");
msg.write("world");
msg.overwrite("Hi there!"); // Replaces "Hello world"
msg.write(" How are you?");

console.log(msg.text); // "Hi there! How are you?"
await window.Poe.addMessage(msg);

Example: With Attachments

const msg = new WritableMessage();

// Consume bot response with attachments
for await (const chunk of window.Poe.stream({
  bot: "Claude-Sonnet-4.6",
  prompts: "Create a chart"
})) {
  msg.write(chunk);
}

// toMarkdown() automatically formats inline refs
const markdown = msg.toMarkdown();
// Output format:
// [ref1]: https://example.com/chart.png
// [ref2]: https://example.com/data.csv
//
// Here is your chart [ref1] with the data [ref2].

window.Poe.close()

Close the current canvas tab programmatically. This allows canvas apps to close themselves, for example when a user completes a workflow or clicks a "Done" button.

Signature

window.Poe.close(): Promise<{ success: boolean }>

Parameters

None

Returns

Promise resolving to an object with:

  • success (boolean): Whether the tab was successfully closed

Example: Close on Completion

// Close the canvas when user completes a task
async function completeTask() {
  // Perform task logic
  await processUserInput();

  // Close the canvas tab
  const result = await window.Poe.close();
  if (result.success) {
    console.log("Canvas tab closed successfully");
  }
}

document.getElementById('done-btn').addEventListener('click', completeTask);

Notes

  • In multi-user group chats, other users will see the tab close via subscription updates
  • If the closed tab was in the foreground, the next available tab will automatically open
  • If this is the last tab in the chat, the canvas sidebar will be hidden

window.Poe.stream()

High-level API for streaming bot responses with automatic tool execution. When the bot requests tools, they are executed automatically and results are fed back into the conversation loop.

Signature

window.Poe.stream(config: StreamRequest): AsyncGenerator<PartialMessage>

Parameters

  • config.bot (string, required): Bot name to query
    • Examples: "GPT-5.4", "Claude-Sonnet-4.6", "Gemini-3-Flash"
  • config.prompts (string | Message | Array<string | Message>, required): User prompts
    • Simple string for single message: "Hello"
    • Message object with metadata: { text: "Hello", role: "user" }
    • Array of strings or Message objects for conversation history
  • config.tools (ExecutableTool[], optional): Array of executable tools
  • config.maxIterations (number, optional): Maximum tool execution loops (default: 10)

Returns

AsyncGenerator yielding PartialMessage objects:

  • text (string): Text content from the bot
  • isReplaceResponse (boolean): Whether to replace previous text
  • attachment (Attachment | null): File attachment details

Example: Simple Query

const response = window.Poe.stream({
  bot: "GPT-5.4",
  prompts: "Tell me a programming joke"
});

let fullResponse = "";
for await (const chunk of response) {
  fullResponse += chunk.text;
  document.getElementById('output').textContent = fullResponse;
}

Example: With Conversation History

// Maintain conversation context with Message objects
const conversationHistory = [
  { text: "What's 25 * 4?", role: "user" },
  { text: "The result is 100.", role: "bot" },
  { text: "Now multiply that by 3", role: "user" }
];

const response = window.Poe.stream({
  bot: "GPT-5.4",
  prompts: conversationHistory
});

for await (const chunk of response) {
  console.log(chunk.text);
}

Example: With File Attachments

// Get a file from a file input element
const fileInput = document.getElementById('file-input');
const file = fileInput.files[0];

// Send the file to the bot for analysis
// The File object is automatically uploaded before being sent
const response = window.Poe.stream({
  bot: "Claude-Sonnet-4.6",
  prompts: {
    text: "Please analyze this document and summarize the key points.",
    role: "user",
    attachments: [file]  // Browser File object
  }
});

// Display the bot's analysis
for await (const chunk of response) {
  console.log(chunk.text);
}

Example: Multiple Files with Conversation

// Handle file upload in a form
document.getElementById('upload-form').addEventListener('submit', async (e) => {
  e.preventDefault();

  const files = Array.from(e.target.files.files);
  const question = e.target.question.value;

  // Send multiple files with a question
  const response = window.Poe.stream({
    bot: "GPT-5.4",
    prompts: {
      text: question,
      role: "user",
      attachments: files  // Array of File objects
    }
  });

  // Stream the response
  const outputDiv = document.getElementById('output');
  let fullResponse = "";

  for await (const chunk of response) {
    fullResponse += chunk.text;
    outputDiv.textContent = fullResponse;
  }
});

window.Poe.createTool()

Helper function to create executable tool definitions for use with stream(). Tools combine the OpenAI-style tool definition with a runnable implementation function.

Signature

window.Poe.createTool<T, R>(options: CreateToolOptions): ExecutableTool<T, R>

Parameters

  • options.name (string, required): Tool function name
  • options.description (string, required): What the tool does
  • options.parameters (object, optional): JSON Schema defining input structure
  • options.run (function, required): Implementation function (input: T) => R | Promise<R>

Returns

ExecutableTool object with:

  • definition: OpenAI-style tool definition for the API
  • run: The executable function

Example: Calculator Tool

const calculatorTool = window.Poe.createTool({
  name: "calculate",
  description: "Perform a mathematical calculation",
  parameters: {
    type: "object",
    properties: {
      expression: {
        type: "string",
        description: 'Math expression to evaluate, e.g. "2 + 2"'
      }
    },
    required: ["expression"]
  },
  run: async (input) => {
    try {
      // Use a proper math parser in production!
      const result = eval(input.expression);
      return `The result of ${input.expression} is ${result}`;
    } catch (error) {
      return `Error: ${error.message}`;
    }
  }
});

// Use the calculator tool with stream
const response = window.Poe.stream({
  bot: "GPT-5.4",
  prompts: "What is 234 multiplied by 567?",
  tools: [calculatorTool]
});

for await (const chunk of response) {
  console.log(chunk.text);
}

Example: API-Based Tool

const weatherTool = window.Poe.createTool({
  name: "get_weather",
  description: "Get current weather for a location",
  parameters: {
    type: "object",
    properties: {
      location: {
        type: "string",
        description: "City name, e.g. San Francisco"
      },
      unit: {
        type: "string",
        enum: ["celsius", "fahrenheit"],
        description: "Temperature unit"
      }
    },
    required: ["location"]
  },
  run: async (input) => {
    const response = await fetch(
      `/api/weather?location=${encodeURIComponent(input.location)}&unit=${input.unit || 'fahrenheit'}`
    );
    const data = await response.json();
    return `Weather in ${input.location}: ${data.temp}°${input.unit === 'celsius' ? 'C' : 'F'}, ${data.condition}`;
  }
});

// Use the weather tool with stream
const response = window.Poe.stream({
  bot: "Claude-Sonnet-4.6",
  prompts: "What's the weather like in Tokyo?",
  tools: [weatherTool]
});

for await (const chunk of response) {
  console.log(chunk.text);
}

Example: Tool with No Parameters

const timeTool = window.Poe.createTool({
  name: "get_current_time",
  description: "Get the current date and time",
  // No parameters needed
  run: async () => {
    return `Current time: ${new Date().toLocaleString()}`;
  }
});

// Use the time tool with stream
const response = window.Poe.stream({
  bot: "GPT-5.4",
  prompts: "What time is it right now?",
  tools: [timeTool]
});

for await (const chunk of response) {
  console.log(chunk.text);
}

window.Poe.uploadFile()

Upload a file to Poe's servers and get an Attachment object that can be used with stream(). This is useful when you want to attach files (images, documents, etc.) to bot messages.

Signature

window.Poe.uploadFile(file: File): Promise<Attachment>

Parameters

  • file (File, required): The File object to upload (e.g., from an <input type="file"> element)

Returns

Promise resolving to an Attachment object with:

  • url (string): The uploaded file's URL
  • contentType (string): The MIME type of the file
  • name (string): The file name
  • inlineRef (string | null): Optional inline reference for markdown rendering

Example: Upload and Send Image to Bot

// Get file from input element
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

// Upload the file
const attachment = await window.Poe.uploadFile(file);

// Send the file to a bot with a question
for await (const chunk of window.Poe.stream({
  bot: "GPT-5.4",
  prompts: {
    text: "What is in this image?",
    role: "user",
    attachments: [attachment]
  }
})) {
  console.log(chunk.text);
}

Example: Using WritableMessage.attachFile()

The WritableMessage class provides a convenient attachFile() method that automatically calls uploadFile() for you:

const message = new WritableMessage("Look at these files:");

// Get files from input
const files = document.querySelector('input[type="file"]').files;

// Upload and attach multiple files
for (const file of files) {
  await message.attachFile(file);
}

// Send message with all attachments
for await (const chunk of window.Poe.stream({
  bot: "GPT-5.4",
  prompts: message.toMessage()
})) {
  console.log(chunk.text);
}

window.Poe.getBotResponse()

Low-level API for streaming Server-Sent Events (SSE) from a bot. Use this when you need fine-grained control over event processing. For automatic tool execution, use stream() instead.

Signature

window.Poe.getBotResponse(config: QueryRequest): AsyncGenerator<BotQueryAppSseEvent>

Parameters

  • config.version (string, required): API version (always "1.0")
  • config.type (string, required): Request type (always "query")
  • config.query (ProtocolMessage[], required): Array of conversation messages
  • config.user_id (string, required): User identifier
  • config.conversation_id (string, required): Conversation identifier
  • config.message_id (string, required): Message identifier
  • config.tools (ToolDefinition[], optional): Tool definitions for manual tool handling

Returns

AsyncGenerator yielding BotQueryAppSseEvent objects. Possible events:

  • text: Text chunk from bot
  • replace_response: Replace previous response
  • file: File attachment
  • suggested_reply: Deprecated — suggested replies are no longer supported by Poe and this event is ignored.
  • meta: Metadata about response format
  • json: Raw JSON data (includes tool calls)
  • error: Error occurred
  • done: Response complete
  • ping: Keep-alive ping

Example

const response = window.Poe.getBotResponse({
  version: "1.0",
  type: "query",
  query: [
    {
      role: "user",
      content: "What is 2+2?"
    }
  ],
  user_id: "user_123",
  conversation_id: "conv_456",
  message_id: "msg_789"
});

for await (const event of response) {
  if (event.event === "text") {
    console.log("Bot says:", event.data.text);
  } else if (event.event === "error") {
    console.error("Error:", event.data.text);
  } else if (event.event === "done") {
    console.log("Response complete");
  }
}

window.Poe.listModels()

Get a list of available OpenAI-compatible models that can be used with stream() and other bot query methods. This is useful for building model selection UIs, validating model names, or listing bots of a particular category.

Signature

window.Poe.listModels(category?: ModelCategory): Promise<Model[]>

Parameters

  • category (ModelCategory, optional): Filter models by category. Available values:
    • ModelCategory.OFFICIAL: Only return official Poe models

Returns

Promise resolving to an array of Model objects with:

  • id (string): The identifier to use in bot API calls (e.g., "GPT-5.4", "Claude-Sonnet-4.6")
  • object (string): Always "model"
  • created (number): Unix timestamp when the model was created
  • description (string): Brief description of the model's capabilities
  • owned_by (string): The organization that owns the model
  • root (string): The root model identifier
  • architecture (object): Model architecture details
    • input_modalities (string[]): Supported input types (e.g., ["text", "image"])
    • output_modalities (string[]): Supported output types (e.g., ["text"])
    • modality (string): Primary modality
  • pricing (object | null): Pricing information per token
    • prompt (string): Cost per prompt token
    • completion (string): Cost per completion token
    • image (string | null): Cost per image
    • request (string | null): Cost per request
    • input_cache_read (string | null): Cost for cached input reads
    • input_cache_write (string | null): Cost for cached input writes
  • context_window (object | null): Context window limits
    • context_length (number): Maximum context length in tokens
    • max_output_tokens (number): Maximum output tokens
  • context_length (number | null): Context length (deprecated, use context_window)
  • metadata (object): Display metadata
    • display_name (string): Human-readable display name
    • image (object): Model avatar image
      • url (string): Image URL
      • alt (string): Alt text
      • width (number): Image width
      • height (number): Image height
    • url (string): URL to the model's page
  • reasoning (object | null): Reasoning/thinking capabilities
    • budget (object): Token budget for reasoning
      • max_tokens (number): Maximum reasoning tokens
      • min_tokens (number): Minimum reasoning tokens
    • required (boolean): Whether reasoning is required
    • supports_reasoning_effort (boolean): Whether reasoning effort parameter is supported
  • parameters (array): Configurable model parameters
    • name (string): Parameter name
    • schema (object): JSON Schema for the parameter
    • default_value (any): Default value
    • description (string, optional): Parameter description

Example: Build a Model Selector

// Fetch available models and populate a dropdown
const models = await window.Poe.listModels();

const select = document.getElementById('model-select');
models.forEach(model => {
  const option = document.createElement('option');
  option.value = model.id;
  option.textContent = model.metadata.display_name;
  select.appendChild(option);
});

Example: Filter by Category

// Get only official Poe models
const officialModels = await window.Poe.listModels(ModelCategory.OFFICIAL);

console.log("Official models:");
officialModels.forEach(model => {
  console.log(`- ${model.metadata.display_name}: ${model.description}`);
});

Example: Check Model Capabilities

// Find models that support image input
const models = await window.Poe.listModels();

const visionModels = models.filter(model =>
  model.architecture.input_modalities.includes("image")
);

console.log("Vision-capable models:");
visionModels.forEach(model => {
  console.log(`- ${model.metadata.display_name}`);
});

Complete Examples

Multi-Tool Chat Application

// Define multiple tools
const tools = [
  window.Poe.createTool({
    name: "get_weather",
    description: "Get weather for a location",
    parameters: {
      type: "object",
      properties: {
        location: { type: "string" }
      },
      required: ["location"]
    },
    run: async ({ location }) => {
      const response = await fetch(`/api/weather?location=${location}`);
      const data = await response.json();
      return `Weather in ${location}: ${data.condition}, ${data.temp}°F`;
    }
  }),

  window.Poe.createTool({
    name: "search_web",
    description: "Search the web for information",
    parameters: {
      type: "object",
      properties: {
        query: { type: "string" }
      },
      required: ["query"]
    },
    run: async ({ query }) => {
      const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
      const results = await response.json();
      return `Search results: ${results.items.map(r => r.title).join(', ')}`;
    }
  }),

  window.Poe.createTool({
    name: "get_time",
    description: "Get the current time",
    run: async () => new Date().toLocaleTimeString()
  })
];

// Use in a chat application
async function sendMessage(userMessage) {
  const response = window.Poe.stream({
    bot: "GPT-5.4",
    prompts: userMessage,
    tools: tools,
    maxIterations: 10
  });

  // Display streamed response in UI
  const messageEl = document.getElementById('bot-message');
  let fullResponse = "";

  for await (const chunk of response) {
    if (chunk.text) {
      fullResponse += chunk.text;
      messageEl.textContent = fullResponse;
    }
    if (chunk.attachment) {
      displayAttachment(chunk.attachment);
    }
  }
}

// Call it when user sends a message
document.getElementById('send-btn').addEventListener('click', () => {
  const input = document.getElementById('user-input');
  sendMessage(input.value);
  input.value = '';
});

Error Handling

async function queryBot(userMessage) {
  try {
    const response = window.Poe.stream({
      bot: "GPT-5.4",
      prompts: userMessage
    });

    for await (const chunk of response) {
      if (chunk.text) {
        console.log(chunk.text);
      }
    }
  } catch (error) {
    console.error("Bot query failed:", error.message);
    // Show user-friendly error message
    document.getElementById('error').textContent = "Failed to get response. Please try again.";
  }
}

Interactive Canvas App

// Initialize canvas app with bot capabilities
class BotCanvas {
  constructor() {
    this.conversationHistory = [];
    this.tools = this.initializeTools();
  }

  initializeTools() {
    return [
      window.Poe.createTool({
        name: "draw_shape",
        description: "Draw a shape on the canvas",
        parameters: {
          type: "object",
          properties: {
            shape: {
              type: "string",
              enum: ["circle", "square", "triangle"]
            },
            x: { type: "number" },
            y: { type: "number" },
            size: { type: "number" }
          },
          required: ["shape", "x", "y"]
        },
        run: async (input) => {
          this.drawShape(input);
          return `Drew ${input.shape} at (${input.x}, ${input.y})`;
        }
      })
    ];
  }

  async sendMessage(text) {
    // Add to history
    this.conversationHistory.push({
      text: text,
      role: "user"
    });

    // Query bot with full history
    const response = window.Poe.stream({
      bot: "GPT-5.4",
      prompts: this.conversationHistory,
      tools: this.tools
    });

    let botResponse = "";
    for await (const chunk of response) {
      botResponse += chunk.text;
      this.updateUI(botResponse);
    }

    // Add bot response to history
    this.conversationHistory.push({
      text: botResponse,
      role: "bot"
    });
  }

  drawShape(params) {
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    // Drawing implementation...
  }

  updateUI(text) {
    document.getElementById('output').textContent = text;
  }
}

// Initialize
const app = new BotCanvas();

Type Definitions

StreamRequest

interface StreamRequest {
  bot: string;                                          // Bot name (e.g., "GPT-5.4")
  prompts: string | Message | Array<string | Message>;  // Prompts or conversation history
  tools?: ExecutableTool[];                             // Optional tools
  maxIterations?: number;                               // Max tool execution loops (default: 10)
}

Sender

interface Sender {
  role: "user" | "bot" | "system" | "tool";  // Sender role
  id?: string | null;                         // Unique identifier of bot or user
  name?: string | null;                       // Display name
}

Attachment

interface Attachment {
  name: string;                // Name of the attachment file
  url: string;                 // URL to the attachment (points to Poe's storage)
  contentType: string;         // MIME type (e.g. "image/jpeg", "text/csv")
  inlineRef: string | null;    // Markdown reference for inline rendering
}

Message

interface Message {
  text: string;                                    // Message content
  role?: "user" | "bot" | "system" | "tool";      // Sender role (defaults to "user")
  contentType?: "text/markdown" | "text/plain";   // Content format (defaults to "text/markdown")
  attachments?: (Attachment | File)[];             // File attachments (File objects are automatically uploaded)
}

Note on File Attachments: When you include browser File objects in the attachments array, they are automatically uploaded to Poe's storage before being sent to the bot. The bot will receive Attachment objects with the uploaded URLs. This makes it easy to send user-selected files directly to bots.

StreamingMessage

Note: Most fields are deprecated. Use Message type for new code.

interface StreamingMessage {
  messageId: string;        // @deprecated Unique identifier for the message
  senderId: string;         // @deprecated The senderId (bot name or user ID)
  content: string;          // @deprecated The entire content received so far
  contentType: string;      // @deprecated Content type: "text/plain" or "text/markdown"
  status: "incomplete" | "complete" | "error";  // Current status of streaming
  statusText?: string;      // @deprecated User-friendly status explanation
  attachments?: {           // @deprecated List of attachments
    attachmentId: string;
    mimeType: string;
    url: string;
    isInline: boolean;
    name: string;
  }[];
}

ProtocolMessage

interface ProtocolMessage {
  role: "user" | "bot" | "system" | "tool";
  content: string;
}

ExecutableTool

interface ExecutableTool<T = any, R = any> {
  definition: ToolDefinition;
  run: (input: T) => R | Promise<R>;
}

ToolDefinition

interface ToolDefinition {
  type: "function";
  function: {
    name: string;
    description: string;
    parameters: {
      type: "object";
      properties: Record<string, any>;
      required?: string[];
    };
  };
}

PartialMessage

interface PartialMessage {
  text: string;
  isReplaceResponse: boolean;
  attachment: Attachment | null;
}

BotQueryAppSseEvent

type BotQueryAppSseEvent =
  | { event: "text"; data: { text: string } }
  | { event: "replace_response"; data: { text: string } }
  | { event: "file"; data: { url: string; name: string; content_type: string; inline_ref?: string } }
  // Deprecated: suggested replies are no longer supported by Poe and this event is ignored.
  | { event: "suggested_reply"; data: { text: string } }
  | { event: "meta"; data: { content_type?: "text/markdown" | "text/plain"; linkify?: boolean } }
  | { event: "json"; data: object }
  | { event: "error"; data: { allow_retry?: boolean; text?: string; error_type?: string } }
  | { event: "done"; data: {} }
  | { event: "ping"; data: {} };

Best Practices

Security Considerations

  • Validate tool inputs: Always validate and sanitize inputs in tool run functions
  • Limit API access: Be cautious about what operations tools can perform
  • Rate limiting: Consider implementing rate limits for expensive operations
  • Error handling: Always wrap tool execution in try-catch blocks
const safeTool = window.Poe.createTool({
  name: "process_data",
  description: "Process user data",
  run: async (input) => {
    // Validate input
    if (!input.data || typeof input.data !== 'string') {
      throw new Error("Invalid input");
    }

    // Sanitize
    const sanitized = input.data.replace(/<script>/gi, '');

    // Process safely
    try {
      return await processData(sanitized);
    } catch (error) {
      console.error('Processing failed:', error);
      return "Processing failed. Please try again.";
    }
  }
});

Performance Tips

  • Cache tool results: Cache expensive computations or API calls
  • Debounce user input: Avoid excessive bot queries
  • Stream responses: Always stream to provide immediate feedback
  • Limit iterations: Set appropriate maxIterations to prevent infinite loops
// Debounce user input
let timeout;
input.addEventListener('input', (e) => {
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    queryBot(e.target.value);
  }, 500); // Wait 500ms after user stops typing
});

Debugging

  • Console logging: Log tool executions and responses
  • Error messages: Provide clear error messages to users
  • Test tools independently: Test tool functions separately before integrating
const debugTool = window.Poe.createTool({
  name: "debug_tool",
  description: "Tool for debugging",
  run: async (input) => {
    console.log('[Tool] Input:', input);

    try {
      const result = await performOperation(input);
      console.log('[Tool] Output:', result);
      return result;
    } catch (error) {
      console.error('[Tool] Error:', error);
      throw error;
    }
  }
});

Common Patterns

Conversation Manager

class ConversationManager {
  constructor(botName) {
    this.botName = botName;
    this.history = [];
  }

  async send(userMessage, tools = []) {
    // Add user message to history
    this.history.push({
      text: userMessage,
      role: "user"
    });

    // Query bot with full context
    const response = window.Poe.stream({
      bot: this.botName,
      prompts: this.history,
      tools: tools
    });

    let botReply = "";
    for await (const chunk of response) {
      botReply += chunk.text;
    }

    // Add bot reply to history
    this.history.push({
      text: botReply,
      role: "bot"
    });

    return botReply;
  }

  clear() {
    this.history = [];
  }
}

// Usage
const conversation = new ConversationManager("GPT-5.4");
await conversation.send("Hello!");
await conversation.send("What did I just say?"); // Bot has context

Notes

  • Tool Execution Loop: stream() automatically handles the loop of calling the bot, executing tools, and feeding results back until completion or maxIterations is reached.

  • Streaming: Both getBotResponse() and stream() stream results as they arrive, allowing real-time UI updates.

  • Error Handling: If a tool execution fails, the error is passed back to the bot as context, allowing it to handle the error gracefully and potentially retry.

  • Multiple Tools: The bot can call multiple tools in sequence or in parallel within a single response.

  • Type Safety: Use TypeScript generics with createTool<InputType, ReturnType>() for type-safe tool definitions.

See Also