JD | 🇳🇱J
Convex Community4mo ago
3 replies
JD | 🇳🇱

Convex agents, convex/chat.ts: process.env.OPENROUTER_API_KEY is undefined

I have this code in chat.ts, following a Convex Agents tutorial:

import { Agent } from "@convex-dev/agent";
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
import { components } from "./_generated/api";
import { action, mutation } from "./_generated/server";
import { v } from "convex/values";

const openrouter = createOpenRouter({
    apiKey: process.env.OPENROUTER_API_KEY,
});

const DEMO_USER_ID = "demo-user";
        
const chatAgent = new Agent(components.agent, {
    name: "chat-agent",
    languageModel: openrouter.languageModel("gemini-2.5-flash"),
    chat: openrouter.chat("gemini-2.5-flash"),
    instructions: "You are a helpful assistant. Be concise and friendly in your responses.",
    maxSteps: 10,
})

export const createThread = mutation({
    args: {},
    handler: async (ctx) => {
        const { threadId } = await chatAgent.createThread(ctx, {
            userId: DEMO_USER_ID,
        });
        return threadId;
    }
});

export const sendMessageToAgent = action({
    args: {
        threadId: v.string(),
        prompt: v.string(),
    },
    handler: async (ctx, args) => {
        const { thread } = await chatAgent.continueThread(ctx, {
            threadId: args.threadId,
        });

        const result = await thread.generateText({ prompt: args.prompt });
        
        return result;
    }
});


I have this in .env.local:

# Deployment used by `npx convex dev`
CONVEX_DEPLOYMENT=anonymous:anonymous-japp

CONVEX_URL=http://127.0.0.1:3210
SITE_URL=http://localhost:8081

OPENROUTER_API_KEY=<secret>

JWT_PRIVATE_KEY=<secret>
JWKS='<secret>'


Despite that, I keep getting

CONVEX A(chat:sendMessageToAgent)] [Request ID: 7abed25820c29ad1] Server Error
Uncaught AI_LoadAPIKeyError: OpenRouter API key is missing. Pass it using the 'apiKey' parameter or the OPENROUTER_API_KEY environment variable.
Was this page helpful?