Skip to main content
MigrationVal Town

Migrate Val Town AI

Replace std/openai with your own AI provider key.

std/openai used Val Town's OpenAI account, which doesn't transfer. Call your provider directly with your own key, keeping the API and model your code uses today. Val Town sometimes swapped in a smaller model on the Free plan, so check which model your results came from.

Replace the client

Install openai and add OPENAI_API_KEY and AI_MODEL to the project's environment variables. Use the example that matches the API your code calls.

lib/ai.ts
import OpenAI from "openai";

export async function ask(prompt: string) {
  const model = process.env.AI_MODEL;
  if (!model) throw new Error("AI_MODEL is required");
  const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

  const response = await client.responses.create({ model, input: prompt });
  return response.output_text;
}
lib/ai.ts
import OpenAI from "openai";

export async function ask(prompt: string) {
  const model = process.env.AI_MODEL;
  if (!model) throw new Error("AI_MODEL is required");
  const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

  const completion = await client.chat.completions.create({
    model,
    messages: [{ role: "user", content: prompt }],
  });
  return completion.choices[0]?.message.content ?? "";
}

To reach several providers through one key, set baseURL to an OpenAI-compatible router such as OpenRouter.

Allow for slow responses

Functions run for 30 seconds by default. For a Hono app, raise it with export const config = { maxDuration: 120 }; in src/index.ts, and stream long answers: a response must start within 60 seconds. See Function limits.

Verify

Require sign-in before a route calls the model, set a spending limit with the provider, and check that a few test requests return the same kind of answers as before.

Back to the feature list.