ai-messages-to-prompt Edge Function — Ai
AISerialises a structured message array into a formatted prompt string for open-source LLMs, supporting ChatML, Llama 2, Alpaca, and plain text formats.
Edge function ai-messages-to-prompt Serialises a structured message array into a formatted prompt string for open-source LLMs, supporting ChatML, Llama 2, Alpaca, and plain text formats.. Deployed on Cloudflare Workers — zero cold starts, globally distributed. Mount it via your Aerostack workspace to call it from any AI agent.
npx aerostack add navin/ai-messages-to-prompt Use with AI Assistants
MCPConnect Claude, Cursor, or any MCP-compatible client — then call this function by slug
① Add MCP Server
Add this once — access all Aerostack functions from your AI tool.
{
"mcpServers": {
"aerostack": {
"url": "https://mcp.aerostack.dev",
"type": "http"
}
}
} ② Call this function
Ask your AI to use the call_function tool with this slug:
call_function({
slug: "ai-messages-to-prompt",
args: {
"messages": null,
"format": "chatml",
"addGenerationPrompt": true
}
}) ai-messages-to-prompt — Convert messages to a formatted LLM prompt string
Serialises a structured
{role, content}message array into a raw prompt string for open-source LLMs (ChatML, Llama 2, Alpaca, or plain text formats).
API
POST /api/ai-messages-to-prompt
Request body
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
messages |
{role: "system"│"user"│"assistant", content: string}[] |
✅ | — | Conversation messages |
format |
"chatml" | "llama2" | "alpaca" | "plain" |
❌ | "chatml" |
Prompt template format |
addGenerationPrompt |
boolean | ❌ | true |
Append the model's generation prefix |
Success response (200)
{
"success": true,
"data": {
"prompt": "<|im_start|>system\nYou are helpful.<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n",
"format": "chatml",
"messageCount": 2
}
}
Error responses
| Code | HTTP | When |
|---|---|---|
INVALID_INPUT |
400 | Invalid role or missing messages |
INTERNAL_ERROR |
500 | Unknown format |
Usage
cURL
curl -X POST "$FUNCTION_URL" \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "What is 2+2?"}
],
"format": "llama2"
}'
TypeScript / JavaScript (HTTP)
const response = await fetch(FUNCTION_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages, format: 'chatml' }),
});
const { data } = await response.json();
const rawPrompt = data.prompt;
// Send rawPrompt to your local LLM inference engine
Direct import (Node / Bun / Deno)
import { aiMessagesToPrompt } from '@aerostack/functions/ai-messages-to-prompt';
const { prompt } = aiMessagesToPrompt({ messages, format: 'alpaca' });
Format Examples
ChatML
<|im_start|>system
You are helpful.<|im_end|>
<|im_start|>user
Hello<|im_end|>
<|im_start|>assistant
Llama 2
[INST] <<SYS>>
You are helpful.
<</SYS>>
Hello [/INST]
Alpaca
### Instruction:
You are helpful.
### Input:
Hello
### Response:
Plain
System: You are helpful.
User: Hello
Assistant:
Use Cases
- Formatting a conversation history for a local Llama/Mistral/Phi model that requires a specific prompt template.
- Building a prompt serialisation layer in an agent framework that supports multiple open-source LLMs.
- Generating training data in the correct format for fine-tuning open-source models.
Notes
- Only
system,user, andassistantroles are accepted — other role values throw an error. addGenerationPrompt: falseomits the trailing generation prefix (useful for training data generation).- For Llama 2 multi-turn: system is injected into the first
[INST]block only.
Metadata
Tags
Publisher
@navin verified
Build and publish your own functions
Write a TypeScript function, deploy it to the edge, and share it with thousands of developers — in minutes.
More AI Functions
Browse AI Functions →ai-chunk-overlap
by @navin
Splits text into overlapping chunks with configurable size, overlap, and boundary snapping (char, word, sentence) for RAG and embedding pipelines.
ai-context-window-fit
by @navin
Trims a conversation message array to fit within a model's context window using configurable strategies, without making any API calls.
ai-cost-estimate
by @navin
Calculates the API cost for an LLM request given a model name, prompt token count, and completion token count, supporting multiple currencies.
ai-extract-keywords
by @navin
Extracts the top N keywords from text using TF-IDF inspired scoring with built-in English stopword filtering, no external API calls required.
ai-guardrail-injection-detect
by @navin
Scores text for common prompt injection attack patterns including role overrides, instruction leaking, and jailbreak attempts.
ai-language-detect
by @navin
Detects the natural language of a text string using character trigram frequency analysis, supporting 13 languages with no external API calls.
Frequently asked questions
What does the ai-messages-to-prompt function do? +
ai-messages-to-prompt is a serverless edge function for ai automation written in aerostack. Deploy it to Cloudflare Workers via your Aerostack workspace.
How do I deploy the ai-messages-to-prompt function? +
Install the Aerostack CLI and run: ```bash aerostack deploy function @navin/ai-messages-to-prompt ``` It will be live on Cloudflare Workers in seconds.
What runtime does ai-messages-to-prompt use? +
ai-messages-to-prompt runs on aerostack on the Cloudflare Workers edge runtime — zero cold starts, globally distributed.
Can I customise the ai-messages-to-prompt function? +
Yes. Fork the function from your Aerostack dashboard, modify the source, and redeploy. All changes are version-controlled.