Skip to main content
In this guide you’ll learn how to use Together AI and Next.js to build two common AI features:
  • Ask a question and get a response
  • Have a long-running chat with a bot
We’ll first build these features using the Together AI SDK directly, then show how to build a chat app using popular frameworks like Vercel AI SDK and Mastra. Here’s the live demo, and here’s the source on GitHub. Let’s get started!

Installation

After creating a new Next.js app, install the Together AI TypeScript SDK:

Ask a single question

To ask a question with Together AI, we’ll need an API route, and a page with a form that lets the user submit their question. 1. Create the API route Make a new POST route that takes in a question and returns a chat completion as a stream:
TypeScript
2. Create the page Add a form that sends a POST request to your new API route, and use the ChatCompletionStream helper to read the stream and update some React state to display the answer:
TypeScript
That’s it! Submitting the form will update the page with the LLM’s response. You can now use the isLoading state to add additional styling, or a Reset button if you want to reset the page.

Have a long-running chat

To build a chatbot with Together AI, we’ll need an API route that accepts an array of messages, and a page with a form that lets the user submit new messages. The page will also need to store the entire history of messages between the user and the AI assistant. 1. Create an API route Make a new POST route that takes in a messages array and returns a chat completion as a stream:
TypeScript
2. Create a page Create a form to submit a new message, and some React state to store the messages for the session. In the form’s submit handler, send over the new array of messages, and use the ChatCompletionStream helper to read the stream and update the last message with the LLM’s response.
TypeScript
You’ve just built a simple chatbot with Together AI!

Using Vercel AI SDK

The Vercel AI SDK provides React hooks that simplify streaming and state management. Install it with:
The API route uses streamText instead of the Together SDK directly:
TypeScript
The page uses the useChat hook which handles all message state and streaming automatically:
TypeScript

Using Mastra

Mastra is an AI framework that provides built-in integrations and abstractions for building AI applications. Install it with:
The API route uses Mastra’s Together AI integration:
TypeScript
The page uses Mastra’s chat hooks to manage conversation state:
TypeScript