thirdwebPlayground
AI

AI SDK Integration

Use the thirdweb blockchain models with the Vercel AI SDK to build AI agents and UIs that can interact with your contracts and wallets.

Documentation

Client Code Example

Use the Vercel AI React SDK to build a chat UI that can interact with the server code.

Code
"use client";

import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";
import { useState } from "react";
import { ThirdwebAiMessage } from "@thirdweb-dev/ai-sdk-provider";

export default function Page() {
  const [sessionId, setSessionId] = useState("");
  const { messages, sendMessage, status } =
    useChat<ThirdwebAiMessage>({
      transport: new DefaultChatTransport({
        // see server implementation below
        api: "/api/chat",
      }),
      onFinish: ({ message }) => {
        // record session id for continuity
        setSessionId(message.metadata?.session_id ?? "");
      },
    });

  const send = (message: string) => {
    sendMessage(
      { text: message },
      {
        body: {
          // send session id for continuity
          sessionId,
        },
      },
    );
  };

  return (
    <>
      {messages.map((message) => (
        <RenderMessage message={message} />
      ))}
      <ChatInputBox send={send} />
    </>
  );
}
Preview

Next.js Server Code Example

The server code is responsible for handling the chat requests and streaming the responses to the client.

Server Code
// src/app/api/chat/route.ts

import { convertToModelMessages, streamText } from "ai";
import { createThirdwebAI } from "@thirdweb-dev/ai-sdk-provider";

// Allow streaming responses up to 5 minutes
export const maxDuration = 300;

const thirdwebAI = createThirdwebAI({
  secretKey: process.env.THIRDWEB_SECRET_KEY,
});

export async function POST(req: Request) {
  const { messages, sessionId } = await req.json();

  const result = streamText({
    model: thirdwebAI.chat({
      context: {
        session_id: sessionId, // session id for continuity
        chain_ids: [8453], // optional chain ids
        from: "0x...", // optional from address
        auto_execute_transactions: true, // optional, defaults to false
      },
    }),
    messages: convertToModelMessages(messages),
    tools: thirdwebAI.tools(), // optional, to use handle transactions and swaps
  });

  return result.toUIMessageStreamResponse({
    sendReasoning: true, // optional, to send reasoning steps to the client
    messageMetadata({ part }) {
      // record session id for continuity
      if (part.type === "finish-step") {
        return {
          session_id: part.response.id,
        };
      }
    },
  });
}