@writerai/writer-sdk v3.6.0
SDK Installation
NPM
npm add @writerai/writer-sdk
Yarn
yarn add @writerai/writer-sdk
Authentication
Writer authenticates your API requests using your account’s API keys. If you do not include your key when making an API request, or use one that is incorrect or outdated, Writer returns an error.
Your API keys are available in the account dashboard. We include randomly generated API keys in our code examples if you are not logged in. Replace these with your own or log in to see code examples populated with your own API keys.
If you cannot see your secret API keys in the Dashboard, this means you do not have access to them. Contact your Writer account owner and ask to be added to their team as a developer.
SDK Example Usage
Example
import { Writer } from "@writerai/writer-sdk";
const writer = new Writer({
apiKey: "<YOUR_API_KEY_HERE>",
organizationId: 850421,
});
async function run() {
const result = await writer.billing.getSubscriptionDetails();
// Handle the result
console.log(result);
}
run();
Available Resources and Operations
billing
- getSubscriptionDetails - Get your organization subscription details
aiContentDetector
- detect - Content detector api
content
- check - Check your content against your preset styleguide.
- correct - Apply the style guide suggestions directly to your content.
coWrite
- generateContent - Generate content using predefined templates
- listTemplates - Get a list of your existing CoWrite templates
files
models
- list - List available LLM models
completions
- create - Create completion for LLM model
- createModelCustomizationCompletion - Create completion for LLM customization model
- stream - Create streaming completion for LLM model
modelCustomization
- create - Create model customization
- delete - Delete Model customization
- get - Get model customization
- list - List model customizations
downloadTheCustomizedModel
- fetchFile - Download your fine-tuned model (available only for Palmyra Base and Palmyra Large)
document
snippet
styleguide
terminology
user
- list - List users
Global Parameters
A parameter is configured globally. This parameter must be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, This global value will be used as the default on the operations that use it. When such operations are called, there is a place in each to override the global value, if needed.
For example, you can set organizationId
to 99895
at SDK initialization and then you do not have to pass the same value on calls to operations like detect
. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.
Available Globals
The following global parameter is available. The required parameter must be set when you initialize the SDK client.
Name | Type | Required | Description |
---|---|---|---|
organizationId | number | ✔️ | The organizationId parameter. |
Example
import { Writer } from "@writerai/writer-sdk";
const writer = new Writer({
apiKey: "<YOUR_API_KEY_HERE>",
organizationId: 496531,
});
async function run() {
const contentDetectorRequest = {
input: "<value>",
};
const organizationId = 592237;
const result = await writer.aiContentDetector.detect(contentDetectorRequest, organizationId);
// Handle the result
console.log(result);
}
run();
Error Handling
All SDK methods return a response object or throw an error. If Error objects are specified in your OpenAPI Spec, the SDK will throw the appropriate Error type.
Error Object | Status Code | Content Type |
---|---|---|
errors.FailResponse | 400,401,403,404,500 | application/json |
errors.SDKError | 4xx-5xx | / |
Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The SDKValidationError
that is thrown as a result will capture the raw value that failed validation in an attribute called rawValue
. Additionally, a pretty()
method is available on this error that can be used to log a nicely formatted string since validation errors can list many issues and the plain error string may be difficult read when debugging.
import { Writer } from "@writerai/writer-sdk";
import * as errors from "@writerai/writer-sdk/sdk/models/errors";
const writer = new Writer({
apiKey: "<YOUR_API_KEY_HERE>",
organizationId: 850421,
});
async function run() {
let result;
try {
result = await writer.billing.getSubscriptionDetails();
} catch (err) {
switch (true) {
case err instanceof errors.SDKValidationError: {
// Validation errors can be pretty-printed
console.error(err.pretty());
// Raw value may also be inspected
console.error(err.rawValue);
return;
}
case err instanceof errors.FailResponse: {
console.error(err); // handle exception
return;
}
default: {
throw err;
}
}
}
// Handle the result
console.log(result);
}
run();
Server Selection
Select Server by Index
You can override the default server globally by passing a server index to the serverIdx
optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:
# | Server | Variables |
---|---|---|
0 | https://enterprise-api.writer.com | None |
import { Writer } from "@writerai/writer-sdk";
const writer = new Writer({
serverIdx: 0,
apiKey: "<YOUR_API_KEY_HERE>",
organizationId: 850421,
});
async function run() {
const result = await writer.billing.getSubscriptionDetails();
// Handle the result
console.log(result);
}
run();
Override Server URL Per-Client
The default server can also be overridden globally by passing a URL to the serverURL
optional parameter when initializing the SDK client instance. For example:
import { Writer } from "@writerai/writer-sdk";
const writer = new Writer({
serverURL: "https://enterprise-api.writer.com",
apiKey: "<YOUR_API_KEY_HERE>",
organizationId: 850421,
});
async function run() {
const result = await writer.billing.getSubscriptionDetails();
// Handle the result
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient
that wraps the native
Fetch API. This
client is a thin wrapper around fetch
and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient
constructor takes an optional fetcher
argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest"
hook to to add a
custom header and a timeout to requests and how to use the "requestError"
hook
to log errors:
import { Writer } from "@writerai/writer-sdk";
import { HTTPClient } from "@writerai/writer-sdk/lib/http";
const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native `fetch`.
fetcher: (request) => {
return fetch(request);
}
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000);
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new Writer({ httpClient });
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
Name | Type | Scheme |
---|---|---|
apiKey | apiKey | API key |
To authenticate with the API the apiKey
parameter must be set when initializing the SDK client instance. For example:
import { Writer } from "@writerai/writer-sdk";
const writer = new Writer({
apiKey: "<YOUR_API_KEY_HERE>",
organizationId: 850421,
});
async function run() {
const result = await writer.billing.getSubscriptionDetails();
// Handle the result
console.log(result);
}
run();
File uploads
Certain SDK methods accept files as part of a multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
Depending on your JavaScript runtime, there are convenient utilities that return a handle to a file without reading the entire contents into memory:
- Node.js v20+: Since v20, Node.js comes with a native
openAsBlob
function innode:fs
.- Bun: The native
Bun.file
function produces a file handle that can be used for streaming file uploads.- Browsers: All supported browsers return an instance to a
File
when reading the value from an<input type="file">
element.- Node.js v18: A file stream can be created using the
fileFrom
helper fromfetch-blob/from.js
.
import { Writer } from "@writerai/writer-sdk";
import { openAsBlob } from "node:fs";
const writer = new Writer({
apiKey: "<YOUR_API_KEY_HERE>",
organizationId: 403654,
});
async function run() {
const uploadModelFileRequest = {
file: await openAsBlob("./sample-file"),
};
const organizationId = 330343;
const result = await writer.files.upload(uploadModelFileRequest, organizationId);
// Handle the result
console.log(result);
}
run();
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
Server-sent event streaming
Server-sent events are used to stream content from certain
operations. These operations will expose the stream as an async iterable that
can be consumed using a for await...of
loop. The loop will
terminate when the server no longer has any events to send and closes the
underlying connection.
import { Writer } from "@writerai/writer-sdk";
const writer = new Writer({
apiKey: "<YOUR_API_KEY_HERE>",
organizationId: 824292,
});
async function run() {
const completionRequest = {
bestOf: 1,
maxTokens: 1024,
minTokens: 1,
prompt: "<value>",
stop: ["the", "is", "and"],
temperature: 0.7,
topP: 1,
};
const modelId = "<value>";
const organizationId = 806561;
const result = await writer.completions.stream(completionRequest, modelId, organizationId);
if (res.completionEvent == null) {
throw new Error("failed to create stream: received null value");
}
for await (const event of res.completionEvent) {
// Handle the event
}
}
run();