Prerequisites

  • Bun installed
  • OpenRouter API key
  • Next.js project with the Builder Box

Environment Setup

  1. Create a .env.local file in your apps/server folder:
# OpenRouter API Key
OPENROUTER_API_KEY=your_api_key_here
  1. Install required dependencies:
bun add ai openai @ai-sdk/openrouter

Configuration

1. OpenRouter Setup

Create a new file at lib/openrouter.ts:
import { OpenRouter } from '@ai-sdk/openrouter';

export const openrouter = new OpenRouter({
  apiKey: process.env.OPENROUTER_API_KEY!,
  defaultModel: 'gpt-4o-mini',  // or any other model you want to use
});

Usage Example

Here’s a simple example of using the AI SDK in a server action:
// app/actions/ai.ts
'use server';

import { streamText } from 'ai';
import { openrouter } from '@/lib/openrouter';

export async function TextStream(prompt: string) {

 const result = streamText({
		model: openrouter("gemini-1.5-flash"),
		messages: [
      {
        role: "user",
        content: prompt,
      },
    ],
	}); // streamText is a function from the ai package

  return result;
}

Next Steps

Troubleshooting

Common Issues

  1. API Key Not Found
    • Ensure your .env.local file is in the correct location
    • Verify the API key is correctly set
  2. Model Not Available
    • Check if the model is supported by OpenRouter
    • Verify your API key has access to the model
  3. Rate Limiting
    • Monitor your API usage
    • Implement rate limiting in your application

Support

If you encounter any issues, please:
  1. Check the OpenRouter Documentation
  2. Review the Vercel AI SDK Documentation
  3. Open an issue in our GitHub repository