Rewrite Selected Text in Word With Your Own AI Task Pane

Built-in assistants in office suites are convenient, but people often find they cannot make the changes they actually need, such as editing a document in place with a specific house style, or using a model of their choice. A common idea is to skip the bundled assistant and write a small add-in that reads and edits the document directly while calling whatever chat API you like.
This guide walks through a minimal Word add-in with a task pane that takes the selected text, sends it to an OpenAI-compatible chat endpoint, and replaces or inserts the result. It uses the keyless API on this site for the example, because browsers can call it directly thanks to open CORS. You will also learn what to watch for with privacy, rate limits, and the difference between a personal tool and something you deploy to a whole organisation.
Frequently asked questions
What is an Office add-in?
It is a small web app that runs inside Word, Excel, PowerPoint or Outlook, usually in a side panel called a task pane. It uses the Office JavaScript API to read and change the open document.
Can an add-in call any API on the internet?
It can call APIs that allow cross-origin requests from the add-in's origin, over HTTPS. If an API does not send the right CORS headers, you need your own small backend to forward requests.
How does a custom add-in differ from a built-in assistant?
A built-in assistant is configured by the vendor and its capabilities are fixed. Your own add-in does exactly what you code, with the model you choose, but you are responsible for security, privacy and maintenance.
Is it safe to put a paid API key in an add-in?
Not in the front-end code. Anyone who opens the add-in can read it. For paid providers, route requests through a small backend that holds the key and enforces limits per user.
Which is better for editing documents: replacing the selection or inserting after it?
Inserting after the selection, or into a comment, is safer while you are testing, because the original stays visible. Replacing is convenient once you trust the prompt.
Does the keyless API keep my document text?
The service is stateless and does not keep conversation history, but each request leaves a technical log with time, IP, user agent, country, endpoint, status, latency, sizes and token counts. Do not send confidential documents to any free public service.
Does this work in Excel too?
The same task pane approach works in Excel with the Excel API: read a range, call the model, write values back. Spreadsheet-specific concerns like recalculation and batching need extra care.
Step by step
- Scaffold a Word task pane project — Use the Office add-in generator to create a JavaScript task pane project for Word and start the dev server.
- Add the API call — Write an askModel function that posts the instruction and selected text to the chat completions endpoint and handles 429 and 503.
- Read and write the document — Use Word.run to load the selection's text, call the model, then insert the result as a paragraph after the selection.
- Wire the task pane — Attach the handler in Office.onReady, disable the button during requests and show plain status messages.
- Decide on a backend — Keep direct calls for a personal keyless setup; add a server that holds keys for any paid provider or team deployment.
What you will build
The add-in has one task pane with a text box for an instruction, such as "make this paragraph more concise" or "translate into plain English", and a button. When you click it, the add-in reads the current selection in Word, sends instruction and text to the chat API, and inserts the result below the selection. That is enough to cover rewriting, summarising, translating and tone changes on any part of a document.
Everything runs in the browser engine Office provides. There is no server of your own in this minimal version, which works only because the keyless API allows cross-origin requests. For a paid provider you would add a backend, covered later in this guide.
The moving parts
A manifest file that tells Office where the add-in lives, an HTML page for the task pane, and a JavaScript file that talks to Word and to the API.
Hosting
The task pane page must be served over HTTPS. For development, the official Yeoman generator sets up a local HTTPS server; for sharing, any static host with HTTPS works.
Scaffold the add-in project
The quickest route is Microsoft's Yeoman generator for Office add-ins, which creates a project with a manifest, a task pane and a development server. Choose a task pane project for Word with JavaScript. The generated project includes scripts that sideload the add-in into Word for testing.
Check Microsoft's current documentation for the exact commands and supported platforms, since tooling evolves. The concepts below stay the same regardless of how the project was created.
Keep the generated project under version control from the first commit. Manifests and Office API versions change over time, and being able to compare a working state with a broken one saves hours when an Office update changes behaviour.
Sideloading
Sideloading installs the add-in only for you, for testing. Organisation-wide deployment goes through the admin centre and needs a reviewed manifest.
npm install -g yo generator-office
yo office # choose: Office Add-in Task Pane project, JavaScript, Word
cd my-office-add-in
npm start # starts the dev server and sideloads into Word
Read the selection and call the API
Word's JavaScript API works in batches: you queue operations on proxy objects, then call context.sync() to execute them. To read the selection, get it, load its text property, and sync. Then call the chat API with fetch, and finally insert the result after the selection in another batch.
Keep the API call outside the Word batch. Network requests can take seconds, and mixing them with document operations makes errors harder to handle.
Insert, do not replace, at first
Inserting the result as a new paragraph after the selection keeps the original for comparison. Switch to insertText(result, "Replace") once the prompt is reliable.
Long selections
The model has a 32,000-token context. For very long selections, split by paragraph and process them one at a time.
const API = "https://api.apifreekeyanthropic.com/v1/chat/completions";
async function askModel(instruction, text) {
const res = await fetch(API, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "free-ai",
max_tokens: 1200,
messages: [
{ role: "system", content: "You edit documents. Return only the edited text, no comments." },
{ role: "user", content: instruction + "\n\n---\n" + text }
]
})
});
if (res.status === 429) throw new Error("Rate limited, wait " + (res.headers.get("Retry-After") || "a few") + " s");
if (res.status === 503) throw new Error("Service busy, retry in a few seconds");
if (!res.ok) throw new Error("API error " + res.status);
const data = await res.json();
return data.choices[0].message.content;
}
async function rewriteSelection() {
const instruction = document.getElementById("instruction").value;
let selected = "";
await Word.run(async (context) => {
const range = context.document.getSelection();
range.load("text");
await context.sync();
selected = range.text;
});
if (!selected.trim()) return;
const result = await askModel(instruction, selected);
await Word.run(async (context) => {
const range = context.document.getSelection();
range.insertParagraph(result, "After");
await context.sync();
});
}Wire up the task pane
The task pane is ordinary HTML. Add a text area for the instruction, a button, and a status line. Wait for Office.onReady before attaching handlers, and disable the button while a request is running so repeated clicks do not hit the parallel request limit.
Offer a few preset instructions as buttons, for example "shorter", "more formal" and "plain English". Presets make the tool faster to use and help keep prompts consistent across a team.
Clear error messages
Show whether the problem was an empty selection, a rate limit or a network error. Users of document tools are often not developers and need plain wording.
Office.onReady((info) => {
if (info.host !== Office.HostType.Word) return;
const button = document.getElementById("run");
const status = document.getElementById("status");
button.onclick = async () => {
button.disabled = true;
status.textContent = "Working...";
try {
await rewriteSelection();
status.textContent = "Done";
} catch (e) {
status.textContent = e.message;
} finally {
button.disabled = false;
}
};
});
CORS, backends and API keys
Browsers block cross-origin requests unless the API explicitly allows them. The keyless endpoint here has CORS open, so the task pane can call it directly. Many commercial APIs either do not allow browser calls or allow them only with special headers, and even where possible, putting a paid key in browser code exposes it to every user.
For a paid provider, add a small backend: the task pane calls your server, which authenticates the user, applies limits and forwards the request with a key it keeps secret. This is also where you can log usage per user and block requests that exceed a budget.
Rate limits per office
Limits on the keyless API apply per IP address. In an office where everyone shares one public IP, colleagues share the same one request per second and daily cap, so a popular tool can hit 429 responses quickly. That is another reason to move team tools behind a backend with a paid provider.
Budgets per user
A backend can count tokens per signed-in user and stop requests past a daily budget, which keeps a single heavy user from consuming the team's whole allowance or running up a bill. Show users their remaining budget in the task pane so the limit never comes as a surprise.
- Personal tool with a keyless API: direct browser call is fine.
- Team tool with a paid API: backend required, key stored on the server.
- Organisation-wide deployment: backend plus sign-in, so you know who made each request.
- Never ship a paid key in the manifest, the HTML or the JavaScript bundle.
Privacy and document content
Documents often contain personal data, contracts or internal plans. Before sending any of that to an external API, check your organisation's rules and the provider's data policy. For free public services, assume no confidentiality guarantees beyond what is written.
The service on this site is stateless and keeps no conversation history, but it records technical logs for every request, including IP and token counts. It has no SLA and no accounts. That makes it suitable for drafts, public text and personal writing, not for confidential business documents. For those, use a provider with contractual data terms or a model you host yourself.
Send only what is needed
Process the selection, not the whole document. Less data sent means less exposure and fewer tokens.

Choosing the model behind the add-in
For rewriting, shortening and simple translation, a mid-size open model is often enough. free-ai is an independent open-weight model of about 35B parameters, tuned to refuse less, and handles these jobs well. This site is not affiliated with Anthropic and does not offer Claude; if you want a Claude model in your add-in, use Anthropic's official API through your own backend and check their current documentation and pricing.
Commercial flagship models clearly win on nuanced editing of long, complex documents, on keeping a consistent voice across many pages, and on working with images or tables embedded in documents. If those matter to your users, the extra cost is likely justified.
Make the model configurable
Store base URL and model name in the add-in's settings so you can switch providers without redeploying the manifest.
Going further
Once the basic loop works, useful extensions include streaming the result into the task pane so users see progress, adding a preview step before inserting, writing results as comments instead of body text, and supporting Excel ranges with the same pattern. If you render rich previews inside the pane, follow the practices in rendering model-generated HTML safely.
If your add-in grows into a tool many colleagues use, consider how identities and permissions flow through it; on-behalf-of auth for remote tools explains delegated identity, which applies equally when your backend calls other services for the signed-in user.
Streaming in the pane
Set "stream": true and read the server-sent events with a stream reader, appending each chunk to the status area until data: [DONE] arrives.

Send a first prompt from the chat box on the home page: no key, no account and no card, just your browser.
Read also
- How to Render Model-Generated HTML Safely in Your Own Web App
- Rolling Usage Window vs Fixed Daily Reset: Which Is Easier to Plan?
- Is It Okay to Build on an AI Service's Undocumented Endpoints?
- Why Do Agent Benchmarks Contradict the Usual Model Rankings?
- Why Does an AI Agent Keep Asking Permission Instead of Working?