Write Code From Spec
This example shows how to create a simple LLM function that generates TypeScript code from a plain-text specification. It's ideal when you want a quick implementation based on a natural language prompt.
Step 1 – Prepare the Prompt
We define the LLM instructions using a templated string. The prompt tells the LLM to act as an expert developer and return only TypeScript code, no prose.
const PROMPT = `You are a senior TypeScript developer.
Write a concise implementation for the task: "{{spec}}".
Respond with only the code (no questions or explanation), inside a single ts code block`;Tip: You want to instruct the llm to respond with the markdown code block - this improves the reliability of code extraction with the parser.
Step 2 – Define the Function
This function configures the LLM, applies the prompt, and parses the response using markdownCodeBlock. It wraps everything into a single executor.
export async function writeCodeFromSpec(spec: string) {
// define the LLM
const llm = useLlm("openai.gpt-4o-mini"); // change this if you want
// instantiate the prompt
const prompt = createChatPrompt<{ spec: string }>(PROMPT);
// define the output parser
const parser = createParser("markdownCodeBlock");
// tie everything together in an executor
const executor = createLlmExecutor({ llm, prompt, parser });
return executor.execute({ spec });
}Why this setup? By separating the prompt and parser setup, the function remains readable and testable. It also allows you to swap in new prompts or models easily.
Step 3 – Use it
Here’s how you can call the writeCodeFromSpec function to generate code dynamically:
import { writeCodeFromSpec } from "./your-path";
const code = await writeCodeFromSpec("a function that adds two numbers");
console.log(code);
/**
* ```ts
* { "code": "function add(a: number, b: number): number {\nreturn a + b;\n", "language": "typescript" }
* ```
*/Complete File
import {
createChatPrompt,
createParser,
createLlmExecutor,
useLlm,
} from "llm-exe";
const PROMPT = `You are a senior TypeScript developer.
Write a concise implementation for the task: "{{spec}}".
Respond with only the code (no questions or explanation), inside a single ts code block`;
export async function writeCodeFromSpec(spec: string) {
// define the LLM
const llm = useLlm("openai.gpt-4o-mini"); // change this if you want
// instantiate the prompt
const prompt = createChatPrompt<{ spec: string }>(PROMPT);
// define the output parser
const parser = createParser("markdownCodeBlock");
// tie everything together in an executor
const executor = createLlmExecutor({ llm, prompt, parser });
return executor.execute({ spec });
}