Tool Handler Returns

Learn how tools return data and UI components in the DAIN network

Return Structure

Each tool handler must return a DainResponse object with three properties:

import { DainResponse, CardUIBuilder } from "@dainprotocol/utils";

return new DainResponse({
  text: string,     // Message for the AI agent
  data: object,     // Structured data matching the output schema
  ui: UIComponent  //  UI built with UIBuilders (or set to [] to skip sending UI)
});

Text Response

The text property provides context and guidance for the AI agent and is not shown to users:

return new DainResponse({
  text: "Found 5 relevant results. The first result directly addresses the user's question about machine learning frameworks.",
  data: results,
  ui: cardUI
});

Data Response

The data property must match your tool's defined output schema:

interface SearchResults {
  results: Array<{
    title: string;
    url: string;
    description: string;
  }>;
}

return new DainResponse({
  text: "Found relevant results",
  data: {
    results: [
      {
        title: "Introduction to TensorFlow",
        url: "https://example.com/tensorflow",
        description: "Comprehensive guide to TensorFlow"
      }
    ]
  },
  ui: cardUI
});

UI Response

Create UI components using UIBuilders from @dainprotocol/utils:

Basic Component

const cardUI = new CardUIBuilder()
  .title("Search Results")
  .content("Found 5 matches")
  .build();

return new DainResponse({
  text: "Query complete",
  data: results,
  ui: cardUI
});

Nested Components

const tableUI = new TableUIBuilder()
  .addColumns([
    { key: "title", header: "Title" },
    { key: "description", header: "Description" }
  ])
  .rows(results)
  .build();

const cardUI = new CardUIBuilder()
  .title("Search Results")
  .addChild(tableUI)
  .build();

return new DainResponse({
  text: "Results processed",
  data: results,
  ui: cardUI
});

Complex UI Example

import { 
  DainResponse, 
  CardUIBuilder, 
  AlertUIBuilder,
  TableUIBuilder,
  ChartUIBuilder 
} from "@dainprotocol/utils";

const alertUI = new AlertUIBuilder()
  .variant("info")
  .title("Analysis Complete")
  .message("Found interesting patterns")
  .build();

const chartUI = new ChartUIBuilder()
  .type("line")
  .title("Trends")
  .chartData(data.trends)
  .dataKeys({ x: "date", y: "value" })
  .build();

const tableUI = new TableUIBuilder()
  .addColumns([
    { key: "metric", header: "Metric" },
    { key: "value", header: "Value" }
  ])
  .rows(data.metrics)
  .build();

const cardUI = new CardUIBuilder()
  .title("Analysis Results")
  .addChild(alertUI)
  .addChild(chartUI)
  .addChild(tableUI)
  .build();

return new DainResponse({
  text: "Analysis complete with visualizations",
  data: data,
  ui: cardUI
});