- Ask a question and get a response.
- Have a long-running chat with a bot.
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 aquestion and returns a chat completion as a stream:
TypeScript
ChatCompletionStream helper to read the stream and update some React state to display the answer:
TypeScript
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 amessages array and returns a chat completion as a stream:
TypeScript
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
Using Vercel AI SDK
The Vercel AI SDK provides React hooks that simplify streaming and state management. Install it with:streamText instead of the Together SDK directly:
TypeScript
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