Basic completion
Type: Recipe
Outcome
Build a small command-line program that sends one prompt to OpenAI through Anvia and prints the model's text response.
- Difficulty: Beginner
- Estimated time: 10 minutes
Prerequisites
- Node.js 22 or newer
- pnpm 11 or newer
- An OpenAI API key with access to
gpt-5
Packages used
@anvia/coreforcreateCompletion(...)@anvia/openaifor the OpenAI completion modeltsx, TypeScript, and Node.js types for running the TypeScript file
Installation and environment setup
From an empty project directory, install the runtime and development packages:
pnpm init
pnpm pkg set type=module
pnpm add @anvia/core @anvia/openai
pnpm add --save-dev tsx typescript @types/nodeSet the API key in the shell that will run the example. Do not put a real key in the source file.
export OPENAI_API_KEY=your_api_keyComplete example
Save this as basic-completion.ts:
import { createCompletion } from '@anvia/core'
import { OpenAIClient } from '@anvia/openai'
const apiKey = process.env.OPENAI_API_KEY
if (!apiKey) {
throw new Error('Set OPENAI_API_KEY before running this example.')
}
const openai = new OpenAIClient({ apiKey })
const model = openai.completionModel('gpt-5')
const result = await createCompletion(model, {
instructions: 'Answer clearly and in no more than two sentences.',
input: 'What is the difference between a library and a framework?',
})
console.log(result.text)Run it
pnpm tsx basic-completion.tsExpected behavior
The program prints a short answer. The wording can vary because it is generated by the selected model. A missing key, unavailable model, rejected request, or provider error causes the promise to reject and the process to exit with an error.
How it works
OpenAIClient creates a provider-backed model that implements Anvia's completion-model contract. createCompletion(...) makes exactly one model request; it does not start an agent loop, execute tools, or persist conversation history. result.text is the visible text normalized from the provider response. The result also contains normalized content, usage, and the full response when the application needs them.
Production notes
- Construct provider clients in server-side code and load keys from a secret manager or protected environment, never browser code or source control.
- Treat generated text as untrusted input before rendering it as HTML or using it in another system.
- Map authentication, rate-limit, transport, and provider-validation errors at the application boundary. Retry only failures known to be transient.
- Record normalized usage for cost monitoring. Avoid logging prompts, raw responses, or credentials unless your data policy explicitly permits it.
Next steps
Source and extensions
This recipe is adapted from the runnable text call cookbook. Next, add explicit timeout handling, record result.usage, or expose the call behind an authenticated server endpoint.