Skip to main content
Build two common AI features with Together AI and Next.js:
  • Ask a question and get a response.
  • Have a long-running chat with a bot.
You’ll first build these features using the Together AI SDK directly, then see how to build a chat app using popular frameworks like Vercel AI SDK and Mastra. Live demo and source on GitHub.

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, you’ll need an API route, and a page with a form that lets you submit a 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, you’ll need an API route that accepts an array of messages, and a page with a form that lets you submit new messages. The page also needs to store the entire history of messages between you 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 built a 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 agent framework built on the Vercel AI SDK. Its model router speaks to Together AI directly, so an agent definition is all it takes:
TypeScript
For project setup, agent configuration, and streaming, follow the Mastra quickstart. The Vercel AI SDK quickstart covers the provider layer Mastra builds on, including tool use and structured outputs.