# Writer AI Studio > This file is very large and may be truncated. For an index of this content, please refer to https://dev.writer.com/llms.txt instead. # AGENTS Source: https://dev.writer.com/AGENTS # Developer documentation style guide This guide covers writing and organizing the public developer docs at dev.writer.com, which Mintlify builds from `docs-official/`. How to edit, add pages to `docs.json`, and preview locally is in `docs/development/developer-docs.md`. Marketing and product writing follow WRITER's [general style guide](https://writer.styleguide.com/) instead. [Google's developer documentation style guide](https://developers.google.com/style) is the base reference. Where this guide is silent, follow Google; where they differ, this guide wins. ## Write for a developer solving one problem Developers come to the docs to implement a feature or fix an error. They search, scan for the relevant part, and jump between sections; few read a page top to bottom. So every page either helps the reader finish a task or explains why that task matters, and its structure gets them to the answer fast. Organize around what developers do, not around product features, with one problem per heading. Put the most common answer or code example at the top of its section and background theory after it. Start with the smallest working example, then add complexity in steps (configuration, options, advanced features), each building on the last. Document the common, successful path first, with verification steps ("You should see...") so readers know they're on track; edge cases and troubleshooting come after it, not instead of it. Keep sections short, and use code blocks, lists, bold text, and quick-reference tables for parameters and error codes to break up walls of text. Keep what a task needs on one page, with parameter descriptions next to the code that uses them, so readers don't bounce between concept pages and the API reference. Cross-link related pages for readers who land on the wrong one. Content that appears on several pages belongs in a snippet under `snippets/`, so a change lands everywhere at once. Write as if every feature has always existed. "New", "recently", "as of \[date]", and "latest version" date the page the moment it ships, so keep time references to changelog entries and deprecation notices: "This feature provides...", not "As of November 2025, this feature is available..."; "The API endpoint...", not "The new API endpoint...". ## Page pattern Every page opens by saying what the reader will accomplish and why it matters: ```markdown theme={null} # Set up webhook notifications This guide shows you how to configure webhooks to receive real-time updates when users complete actions in your application. After setting up webhooks, your application can respond to events without polling the WRITER API. ``` Every heading is followed by one or two sentences of prose before any list, code block, or table, because a reader arriving from search needs to know what the section holds before the structure starts: ```markdown theme={null} ## Follow best practices Handle errors, authenticate securely, and respect rate limits to keep your integration reliable. - Do this - Do that ``` Every page ends with a `## Next steps` section linking follow-up tutorials, related features, and advanced configuration where it applies. It is the one heading that stays a noun phrase, so readers find it in the same place on every page: ```markdown theme={null} ## Next steps Now that you have webhooks configured, you can: - [Handle webhook failures](link) to ensure reliable event processing - [Secure your webhook endpoints](link) with signature verification - [Set up webhook monitoring](link) to track delivery success ``` API reference pages start with what the endpoint does, list required parameters before optional ones, and show realistic requests, responses, and error conditions. Tutorials use numbered steps, include verification steps and troubleshooting for common issues, and end with next steps. ## Voice Address the reader as "you", in active voice and present tense, with direct imperatives: "Install the SDK", not "You need to install the SDK" or "You will install the SDK". | Avoid | Why | | - | - | | "we", "us", "our" | Readers can't tell whether "we" means WRITER or the author and the reader | | "please" | Too polite for technical instructions | | "will" for current features | Present tense reads as something the reader can do now | | "simple", "basic", "easy", "trivial", "straightforward", "just", "simply", "obviously" | Readers who struggle with the task feel inadequate | | "powerful", "amazing", "revolutionary", "cutting-edge", "industry-leading", "seamlessly", "effortlessly", "instantly", and other hyperbole | Sounds promotional rather than helpful | | "leverage", "utilize", "optimize", "robust", "streamline", "synergy", "paradigm", "game-changer", "low-hanging fruit" | Vague and overused | | Instead of | Write | | - | - | | This simple API | This API | | You need to install X / You need to configure Y | Install X / Configure Y | | Our powerful system | The system | | Just add the code | Add the code | | We recommend | Use, or Consider using | | This tutorial will show you | This tutorial demonstrates | | You will be able to | You can | | Please install / Please configure | Install / Configure | | Utilize / Leverage the API | Use / Use the API | | Click the button | Select the button | | Since you need to... | Because you need to... | For example, not "Our powerful API makes it easy to integrate authentication. We've designed a simple system that will help you get started quickly." but "The authentication API handles user login and token management. Follow these steps to integrate authentication into your application." Not "You need to install the WRITER SDK before you can start building." but "Install the WRITER SDK before building your application." ## Mechanics * Use the Oxford comma in lists. * Spell out zero through nine and use numerals for 10 and up, except where that would mix the two in one phrase: "there are 2 people and 15 dogs". Spell out a number that starts a sentence. * No periods in acronyms: UK, not U.K. * Write "generative AI", not "GenAI" or "gen AI". ## Headings Headings use sentence case (capitalize the first word and proper nouns) and start with an imperative verb that says what the reader does, because that matches how people search and tells them what the section gets them. Avoid gerunds ("Configuring"), noun phrases ("Configuration", "Overview"), questions ("How do I configure X?"), and passive constructions ("Getting started"). `Next steps` is the one exception, above. | Instead of | Write | | - | - | | Key differences | Compare the APIs | | Parameter mapping | Map your parameters | | Accessing data | Access your data | | Migration steps | Migrate your code | | Prerequisites | Prepare your environment | | Configuration | Configure the settings | | Installation | Install the SDK | | Overview | Understand the basics, or Learn about \[feature] | | Authentication | Authenticate your requests | | Error handling | Handle errors | | Best practices | Follow best practices | | Chat completions | Chat with an LLM | | Set Up Your Development Environment | Set up your development environment | ## Links Link text says where the link goes ("Learn more about authentication methods"), never "click here", "read more", or "this link", and external links get a sentence of context. Run `npx mint broken-links` from `docs-official/` before publishing; `.github/workflows/docs-official-checks.yml` runs it and `mint validate` on every PR that touches the folder. ## Code examples Readers paste examples straight into their own code, so every example runs as-is: all imports, dependencies, and setup, the complete request and response, error handling where a real integration needs it, and realistic names, values, and scenarios instead of foo/bar placeholders. Comment only the non-obvious lines. When common variations exist, show more than one example. Test each example as written, in every language it's shown in, before publishing. API and SDK examples include the full client initialization: ```python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() ``` ```javascript theme={null} import { Writer } from "writer-sdk"; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); ``` Wrap code shown in more than one language in ``: API endpoint examples in cURL, Python, and JavaScript, and SDK examples in Python and JavaScript where both exist. A standalone JSON example needs no ``. Writer Framework pages (`framework/`) and Agent Builder pages are the exception to both rules: their code runs on the Framework or on the reader's own deployed app, not on the SDK, and Framework code is Python-only. ````mdx theme={null} ```bash cURL curl -X POST https://api.writer.com/v1/chat \ -H "Authorization: Bearer $WRITER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "palmyra-x6", "messages": [{"role": "user", "content": "Write a one-sentence description of a wool sweater."}] }' ``` ```python Python from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.chat.chat( model="palmyra-x6", messages=[{"role": "user", "content": "Write a one-sentence description of a wool sweater."}], ) print(response.choices[0].message.content) ``` ```javascript JavaScript import { Writer } from "writer-sdk"; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.chat.chat({ model: "palmyra-x6", messages: [{ role: "user", content: "Write a one-sentence description of a wool sweater." }], }); console.log(response.choices[0].message.content); ``` ```` Mintlify's built-in components (``, ``, ``, ``, ``, `` and the rest) are available in every MDX file without an import. Only snippets are imported, then used as components: ```mdx theme={null} import apiKey from '/snippets/apiKey.mdx'; ``` ## Images and alt text Alt text replaces the image when it isn't visible, so swapping every image for its alt text should leave the page's meaning unchanged. Describe what the image does on the page, not only what it shows. Informative images (information the text doesn't carry), functional images (buttons, links), and complex images (charts, diagrams, screenshots that need describing) get alt text. Leave it empty, `![](/images/image.png)`, so screen readers skip the image, when the image is decorative, repeats what the surrounding text already says, or is a UI screenshot, icon, or visual aid for content already in the text. Good alt text: * stays under 155 characters, as a full sentence or noun phrase with punctuation for natural pauses; * leaves out "Image of" and "Photo of"; * avoids all caps, which screen readers may read letter by letter; * stays the same for an image that repeats (controls, status indicators, icons). For example: `![Architecture of an app that's built with Apps Script](/images/architecture.png)`, `![User interface showing the login form with username and password fields](/images/login-form.png)`, `![Flowchart showing the authentication process from login to dashboard](/images/flowchart.png)`. ## Before you submit Check that the page: * [ ] opens with what the reader will accomplish and why; * [ ] has prose under every heading, sentence-case imperative headings, and ends with `## Next steps`; * [ ] uses active voice, present tense, "you", and direct imperatives, with no qualifiers, marketing language, or "we"; * [ ] has complete, tested examples; * [ ] passes `npx mint broken-links`. # Get your organization subscription details Source: https://dev.writer.com/api-reference-legacy/billing/get-your-organization-subscription-details get /billing/subscription > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Detect If the content is AI generated Source: https://dev.writer.com/api-reference-legacy/content/detect-if-the-content-is-ai-generated post /content/organization/{organizationId}/detect > [!WARNING] > > This endpoint is deprecated. Use the [AI detection](/api-reference/tool-api/ai-detect) endpoint instead. # Post contentorganization team check Source: https://dev.writer.com/api-reference-legacy/content/post-contentorganization-team-check post /content/organization/{organizationId}/team/{teamId}/check > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Post contentorganization team correct Source: https://dev.writer.com/api-reference-legacy/content/post-contentorganization-team-correct post /content/organization/{organizationId}/team/{teamId}/correct > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Get cowriteorganization team template Source: https://dev.writer.com/api-reference-legacy/cowrite/get-cowriteorganization-team-template get /cowrite/organization/{organizationId}/team/{teamId}/template/{templateId} > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Post cowriteorganization team generate Source: https://dev.writer.com/api-reference-legacy/cowrite/post-cowriteorganization-team-generate post /cowrite/organization/{organizationId}/team/{teamId}/generate > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Delete snippets Source: https://dev.writer.com/api-reference-legacy/snippet/delete-snippets delete /snippet/organization/{organizationId}/team/{teamId} > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Find snippets Source: https://dev.writer.com/api-reference-legacy/snippet/find-snippets get /snippet/organization/{organizationId}/team/{teamId} > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Update snippets Source: https://dev.writer.com/api-reference-legacy/snippet/update-snippets put /snippet/organization/{organizationId}/team/{teamId} > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # List your styleguide pages Source: https://dev.writer.com/api-reference-legacy/styleguide/list-your-styleguide-pages get /styleguide/page > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Page details Source: https://dev.writer.com/api-reference-legacy/styleguide/page-details get /styleguide/page/{pageId} > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Add terms Source: https://dev.writer.com/api-reference-legacy/terminology/add-terms post /terminology/organization/{organizationId}/team/{teamId} > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Delete terms Source: https://dev.writer.com/api-reference-legacy/terminology/delete-terms delete /terminology/organization/{organizationId}/team/{teamId} > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Find terms Source: https://dev.writer.com/api-reference-legacy/terminology/find-terms get /terminology/organization/{organizationId}/team/{teamId} > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Update terms Source: https://dev.writer.com/api-reference-legacy/terminology/update-terms put /terminology/organization/{organizationId}/team/{teamId} > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # List users Source: https://dev.writer.com/api-reference-legacy/user/list-users get /user > [!WARNING] > > We're deprecating these API endpoints, so the Control Center API key setup won't work. \[Contact support] ([https://support.writer.com/](https://support.writer.com/)) if you need them. # Manage API keys Source: https://dev.writer.com/api-reference/api-keys Learn how to create, manage, and delete API keys. This guide shows you how to create and manage API keys for the Writer API. After you create a key in [Control Center](https://app.writer.com/controlcenter), you can authenticate requests to Writer API endpoints. > [!WARNING] > > **Deprecation notice**: Legacy API keys (keys created under the previous API agent model) will stop working on **January 1, 2027**. > > **Migration path**: Create a new API key, update your applications to use the new key, then revoke the legacy key. ## About API keys The Writer API uses token authentication for API requests. Pass your API key in the `Authorization` header: ``` Authorization: Bearer ``` Each key is a standalone credential with its own name, owner or organization access, expiration, and permissions. Permissions control which API capabilities the key can call. Expiration defines how long the key remains valid. ## Create an API key Create a key from the API keys page in Control Center. Use an account with admin access to create and manage organization API keys. 1. From the [Control Center home page](https://app.writer.com/controlcenter), open **Security & compliance** in the navigation menu, then select **API Keys**. 2. Select **New** to open the **Generate an API Key** page. 3. Under **About**, configure the key: * **Key name**: a descriptive name that helps you identify the key. * **Short description** (optional): notes about how you plan to use the key. * Under **Who can use this key?**, choose **All teams** or **Specific user**: * For **All teams**, the key is an organization key. The creator is the key owner. * For **Specific user**, choose the user who owns the key. That user must be an active member of your organization. 4. Under **Limits**, set **Expiration**: * Choose **No expiration**, a preset duration (30, 60, or 90 days, or 1 year), or a custom date. 5. Under **Permissions**, turn on the capabilities this key needs. Each category is either all access or no access: * **Playbooks**: run and read playbook content (available when your organization has access to the Playbooks API). * **Knowledge graphs and files**: view and create knowledge graphs and files. * **Models**: send requests to models enabled for your organization. 6. Select **Generate**. 7. When the key appears, copy it and store it securely. Acknowledge that you have copied the key before you leave the page. You can't view the full key again after that. > [!NOTE] > > Store the API key in a secure location, such as a `.env` file (for example, `WRITER_API_KEY=`). If you lose a key, delete it and generate a new one—you can't recover the original secret. ## View and manage API keys The API keys page lists every key as its own row. Use this list to find keys, open details, and edit or delete keys you created on this page. 1. From the [Control Center home page](https://app.writer.com/controlcenter), open **Security & compliance** → **API Keys**. 2. Search or filter the list by access, permissions, owner, or expiration as needed. 3. Select a key name to open its detail page. The detail page shows the masked key ID, access summary, expiration, and history. 4. To change a key, open the row **Actions** menu and select **Edit**, or open the key and edit from there. Save your changes when you finish. > [!NOTE] > > You can't view or reveal the full API key after it's created. Copy it the first time it's shown and store it securely. To replace a lost key, generate a new key. ## Configure key permissions Permissions are set per key and determine which API endpoints that key can call. Turn each category on for all access or leave it off for no access. 1. From the [Control Center home page](https://app.writer.com/controlcenter), open **Security & compliance** → **API Keys**. 2. Create a new key or open an existing key and select **Edit**. 3. Under **Permissions**, toggle **Playbooks**, **Knowledge graphs and files**, and **Models** as needed. 4. Save your changes (or select **Generate** for a new key). > [!NOTE] > > Capabilities map to Writer API endpoints. Turn on only the permissions your integration needs. ## Understand legacy API keys Keys created under the previous API agent model appear in the new API keys list as legacy keys. You can view them, but you can't edit, delete, or rotate them on the new page. Manage those keys on the legacy API keys page until they stop working on **January 1, 2027**. Before that date, create a replacement key on the new page, update your applications, then revoke the legacy key. ## Delete an API key Delete a key when you no longer need it or when you need to replace a compromised credential. Deletion is permanent. 1. From the [Control Center home page](https://app.writer.com/controlcenter), open **Security & compliance** → **API Keys**. 2. On the row for the key you want to remove, open the **Actions** menu, then select **Delete**. 3. Confirm by selecting **Yes, delete key**. Legacy keys can't be deleted from the new API keys page. Open the legacy API keys page from the key's detail menu to manage them there until retirement. ## Next steps * [Make your first API call](/home/quickstart) using your API key * Read the [chat completion endpoint reference](/api-reference/completion-api/chat-completion) * Review [API error codes](/api-reference/error-codes) if requests fail authentication # Application details Source: https://dev.writer.com/api-reference/application-api/application-details get /v1/applications/{application_id} Retrieves detailed information for a specific no-code agent (formerly called no-code applications), including its configuration and current status. > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. # Retrieve all jobs Source: https://dev.writer.com/api-reference/application-api/application-jobs get /v1/applications/{application_id}/jobs Retrieve all jobs created via the async API, linked to the provided application ID (or alias). > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. # Generate from application Source: https://dev.writer.com/api-reference/application-api/applications post /v1/applications/{application_id} Generate content from an existing no-code agent (formerly called no-code applications) with inputs. > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. # Generate from application (async) Source: https://dev.writer.com/api-reference/application-api/generate-application-job post /v1/applications/{application_id}/jobs Generate content asynchronously from an existing no-code agent (formerly called no-code applications) with inputs. > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. # Retrieve graphs Source: https://dev.writer.com/api-reference/application-api/get-application-graphs get /v1/applications/{application_id}/graphs Retrieve Knowledge Graphs associated with a no-code agent that has chat capabilities. > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. # Retrieve a single job Source: https://dev.writer.com/api-reference/application-api/get-single-async-job get /v1/applications/jobs/{job_id} Retrieves a single job created via the Async API. > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. # List applications Source: https://dev.writer.com/api-reference/application-api/list-applications get /v1/applications Retrieves a paginated list of no-code agents (formerly called no-code applications) with optional filtering and sorting capabilities. > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. # Retry job execution Source: https://dev.writer.com/api-reference/application-api/post-retry-async-job post /v1/applications/jobs/{job_id}/retry Re-triggers the async execution of a single job previously created via the Async api and terminated in error. > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. # Associate graphs Source: https://dev.writer.com/api-reference/application-api/put-application-graphs put /v1/applications/{application_id}/graphs Updates the list of Knowledge Graphs associated with a no-code chat agent. > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. # Chat completion Source: https://dev.writer.com/api-reference/completion-api/chat-completion post /v1/chat Generate a chat completion based on the provided messages. The response shown below is for non-streaming. To learn about streaming responses, see the [chat completion guide](https://dev.writer.com/home/chat-completion). > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. # List models Source: https://dev.writer.com/api-reference/completion-api/list-models get /v1/models Retrieve a list of available models that can be used for text generation, chat completions, and other AI tasks. > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. # Text generation Source: https://dev.writer.com/api-reference/completion-api/text-generation post /v1/completions Generate text completions using the specified model and prompt. This endpoint is useful for text generation tasks that don't require conversational context. > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. # Understand error codes Source: https://dev.writer.com/api-reference/error-codes This page provides a comprehensive reference for all error codes, HTTP status codes, and error handling patterns used across Writer APIs. ## Error code reference > [!TIP] > > **Quickstart**: Most issues fall into these categories. Check here first! > [card] Authentication Issues > > **401 Unauthorized**: check your API key format and permissions > [card] Bad Request Data > > **400 + validation_error**: verify required fields and data types > [card] Rate Limiting > > **429 Too Many Requests**: implement exponential backoff > [card] Server Problems > > **5xx Errors**: check our status page or retry your request ## Error types Jump to specific error types to find the cause and suggested action: * [Authentication and authorization errors](#authentication-and-authorization-errors) * [Request validation errors](#request-validation-errors) * [Rate limiting and quota errors](#rate-limiting-and-quota-errors) * [Server and processing errors](#server-and-processing-errors) * [Error codes by service](#error-codes-by-service) ## Error response format All API endpoints return errors in a consistent JSON format: ```json theme={null} { "tpe": "error_type", "errors": [ { "description": "Human-readable error description", "key": "error.message.key", "extras": {} } ], "extras": {} } ``` ### Response structure > [accordion] 🔧 Core fields (always present) > > | Field | Type | Description | > | - | - | - | > | `tpe` | string | Error type identifier (for example, "BadRequest", "Unauthorized") | > | `errors` | array | Array of error messages with details | > | `extras` | object | Additional error context and metadata | > [accordion] 📋 Error message details > > | Field | Type | Description | > | - | - | - | > | `description` | string | Human-readable error description for developers | > | `key` | string | Message key for internationalization | > | `extras` | object | Additional context specific to the error | ## HTTP status codes Writer APIs use standard HTTP status codes to indicate the nature of errors: | Status | Error code | Type | Description | Common causes | | - | - | - | - | - | | 400 | `BadRequest` | Validation | Invalid request parameters or malformed request body | Missing required fields, invalid format | | 401 | `Unauthorized` | Authentication | Missing or invalid authentication credentials | Missing API key, invalid format | | 403 | `Forbidden` | Authorization | Valid credentials but insufficient permissions | Insufficient access rights | | 404 | `NotFound` | Validation | Requested resource does not exist | Invalid resource ID, deleted resource | | 409 | `Conflict` | Validation | Request conflicts with current state | Duplicate resource, version conflict | | 410 | `Gone` | Validation | Resource was permanently removed | Deleted/expired resource | | 413 | `PayloadTooLarge` | Validation | Request body too large | Exceeds configured size limits | | 422 | `UnprocessableEntity` | Validation | Semantically invalid request | Fails business rules/constraints | | 429 | `TooManyRequests` | Rate Limiting | Rate limit or quota exceeded | Too many requests per time period | | 500 | `InternalServerError` | Server | Internal server error | Server-side processing issue | | 503 | `ServiceUnavailable` | Server | Service temporarily unavailable | Maintenance, high load | | 507 | `InsufficientStorage` | Server | Insufficient storage to complete request | Storage quota exhausted | ## Error codes by service This section provides a comprehensive reference of all possible error codes organized by service and endpoint. > [accordion] Chat Completions API > > ### Text generation > > **Endpoint:** `POST /v1/completion` > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `BadRequest` | 400 | Invalid model parameter | Model name not supported or malformed | > | `InvalidInputParameters` | 400 | Invalid prompt format | Empty prompt or invalid encoding | > | `InvalidContentType` | 400 | Invalid parameters | Invalid `temperature`, `max_tokens`, or other parameters | > | `BadCredentials` | 401 | Invalid API key | Missing or malformed API key | > | `BadToken` | 401 | API key expired | API key has expired | > | `InsufficientAccessRights` | 403 | Insufficient permissions | API key lacks required permissions | > | `QuotaExceeded` | 429 | Rate limit exceeded | Too many requests per minute | > | `CompletionModelQuotaError` | 429 | Quota exceeded | Monthly usage limit reached | > | `CompletionModelUnavailableError` | 500 | Model unavailable | AI model temporarily unavailable | > | `CompletionModelInternalError` | 500 | Service overloaded | High load, retry with backoff | > > ### Chat completions > > **Endpoint:** `POST /v1/chat/completions` > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `BadRequest` | 400 | Invalid messages format | Malformed messages array or role | > | `InvalidInputParameters` | 400 | Invalid model parameter | Model not supported for chat | > | `InvalidContentType` | 400 | Invalid tool configuration | Malformed tools or `tool_choice` | > | `BadRequest` | 400 | Invalid streaming parameters | Invalid stream or `stream_options` | > | `CompletionModelUnsafeRequestError` | 400 | Content policy violation | Request contains prohibited content | > | `BadCredentials` | 401 | Authentication failed | Invalid or missing API key | > | `BadToken` | 401 | Authentication failed | Invalid or missing API key | > | `InsufficientAccessRights` | 403 | Model access denied | Account lacks access to requested model | > | `QuotaExceeded` | 429 | Rate limit exceeded | Too many requests per minute | > | `CompletionModelQuotaError` | 429 | Model quota exceeded | Model-specific usage limit reached | > | `CompletionModelInternalError` | 500 | Model processing error | Internal error in model inference | > | `CompletionModelUnavailableError` | 503 | Model temporarily unavailable | Model service is down for maintenance | > [accordion] Files API > > ### Upload files > > **Endpoint:** `POST /v1/files` > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `BadRequest` | 400 | Invalid file format | Unsupported file type | > | `InvalidInputParameters` | 400 | File too large | File exceeds size limit | > | `InvalidContentType` | 400 | Invalid file content | Corrupted or malformed file | > | `BadCredentials` | 401 | Authentication required | Missing or invalid API key | > | `BadToken` | 401 | Authentication required | Missing or invalid API key | > | `InsufficientAccessRights` | 403 | Upload permission denied | Account lacks file upload permissions | > | `BadRequest` | 413 | Payload too large | Request body exceeds size limit | > | `QuotaExceeded` | 429 | Upload rate limit exceeded | Too many file uploads per minute | > | `InternalError` | 500 | File processing error | Error processing uploaded file | > | `QuotaExceeded` | 507 | Storage quota exceeded | Account storage limit reached | > > ### Get file > > **Endpoint:** `GET /v1/files/{file_id}` > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `BadCredentials` | 401 | Authentication required | Missing or invalid API key | > | `BadToken` | 401 | Authentication required | Missing or invalid API key | > | `InsufficientAccessRights` | 403 | Access denied | No permission to access this file | > | `ResourceNotFound` | 404 | File not found | File ID doesn't exist | > | `ResourceNotFound` | 410 | File gone | File has been deleted or expired | > [accordion] Knowledge Graphs API > > ### Create graph > > **Endpoint:** `POST /v1/knowledge-graphs` > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `BadRequest` | 400 | Invalid graph configuration | Malformed graph parameters | > | `InvalidInputParameters` | 400 | Invalid graph name | Name contains invalid characters | > | `BadRequest` | 400 | Duplicate graph name | Graph with this name already exists | > | `BadCredentials` | 401 | Authentication required | Missing or invalid API key | > | `BadToken` | 401 | Authentication required | Missing or invalid API key | > | `InsufficientAccessRights` | 403 | Graph creation denied | Account lacks graph creation permissions | > | `QuotaExceeded` | 429 | Graph creation rate limit | Too many graphs created per hour | > | `InternalError` | 500 | Graph creation failed | Internal error creating graph | > > ### Add file to graph > > **Endpoint:** `POST /v1/knowledge-graphs/{graph_id}/files` > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `BadRequest` | 400 | Invalid file format | File type not supported for graphs | > | `InvalidInputParameters` | 400 | File processing failed | Error parsing file content | > | `BadCredentials` | 401 | Authentication required | Missing or invalid API key | > | `BadToken` | 401 | Authentication required | Missing or invalid API key | > | `InsufficientAccessRights` | 403 | Graph access denied | No permission to modify this graph | > | `ResourceNotFound` | 404 | Graph not found | Graph ID does not exist | > | `BadRequest` | 409 | File already in graph | File is already associated with graph | > | `QuotaExceeded` | 429 | File processing rate limit | Too many files processed per minute | > > ### Query graph > > **Endpoint:** `POST /v1/knowledge-graphs/{graph_id}/query` > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `BadRequest` | 400 | Invalid query format | Malformed query parameters | > | `InvalidInputParameters` | 400 | Query too complex | Query exceeds complexity limits | > | `BadCredentials` | 401 | Authentication required | Missing or invalid API key | > | `BadToken` | 401 | Authentication required | Missing or invalid API key | > | `InsufficientAccessRights` | 403 | Query permission denied | No permission to query this graph | > | `ResourceNotFound` | 404 | Graph not found | Graph ID doesn't exist | > | `QuotaExceeded` | 429 | Query rate limit exceeded | Too many queries per minute | > | `InternalError` | 500 | Query processing error | Internal error processing query | > [accordion] Applications API > > ### Create application > > **Endpoint:** `POST /v1/applications` > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `BadRequest` | 400 | Invalid application configuration | Malformed application parameters | > | `InvalidInputParameters` | 400 | Invalid blueprint configuration | Blueprint syntax or configuration error | > | `BadRequest` | 400 | Duplicate application name | Application with this name already exists | > | `BadCredentials` | 401 | Authentication required | Missing or invalid API key | > | `BadToken` | 401 | Authentication required | Missing or invalid API key | > | `InsufficientAccessRights` | 403 | Application creation denied | Account lacks application creation permissions | > | `QuotaExceeded` | 429 | Application creation rate limit | Too many applications created per hour | > | `InternalError` | 500 | Application creation failed | Internal error creating application | > > ### Generate application job > > **Endpoint:** `POST /v1/applications/{app_id}/jobs` > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `BadRequest` | 400 | Invalid job parameters | Malformed job request | > | `InvalidInputParameters` | 400 | Missing required inputs | Required input parameters not provided | > | `BadCredentials` | 401 | Authentication required | Missing or invalid API key | > | `BadToken` | 401 | Authentication required | Missing or invalid API key | > | `InsufficientAccessRights` | 403 | Job execution denied | No permission to execute jobs for this app | > | `ResourceNotFound` | 404 | Application not found | Application ID doesn't exist | > | `BadRequest` | 409 | Job already running | Application has a job already in progress | > | `QuotaExceeded` | 429 | Job execution rate limit | Too many jobs executed per minute | > | `InternalError` | 500 | Job execution failed | Internal error executing job | > [accordion] Tools API > > ### PDF parser > > **Endpoint:** `POST /v1/tools/pdf-parser` > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `BadRequest` | 400 | Invalid PDF file | Corrupted or unsupported PDF | > | `InvalidInputParameters` | 400 | PDF too large | PDF exceeds size limits | > | `BadRequest` | 400 | PDF password protected | PDF requires password to access | > | `BadCredentials` | 401 | Authentication required | Missing or invalid API key | > | `BadToken` | 401 | Authentication required | Missing or invalid API key | > | `InsufficientAccessRights` | 403 | Parser access denied | Account lacks PDF parser permissions | > | `QuotaExceeded` | 429 | Parser rate limit | Too many parsing requests per minute | > | `InternalError` | 500 | PDF parsing error | Internal error parsing PDF | > [accordion] Guardrails > > Guardrail errors occur when content is blocked by configured safety controls. For more information, see [Configure guardrails](/home/guardrails). > > ### Content blocked by guardrail > > | Error Type | HTTP Status | Description | Possible Causes | > | - | - | - | - | > | `GuardrailBlockedError` | 400 | Content blocked by guardrail | Input or output violated guardrail policy | > | `BadRequest` | 400 | Bedrock guardrail violation | Content blocked by AWS Bedrock guardrail policy (PII, content filter, denied topic) | > | `BadRequest` | 400 | Azure Content Safety violation | Content blocked by Azure text moderation (harmful content category exceeded threshold) or Prompt Shields (prompt injection detected) | > | `BadCredentials` | 401 | Guardrail authentication failed | Invalid AWS credentials for Bedrock guardrail or invalid Azure API key for Content Safety | > | `InsufficientAccessRights` | 403 | Guardrail access denied | Missing permissions for guardrail provider | > | `ResourceNotFound` | 404 | Guardrail not found | Invalid guardrail ID or version (Bedrock) or invalid endpoint URL (Azure Content Safety) | > | `InternalError` | 500 | Guardrail processing error | Error communicating with guardrail provider | > | `InternalError` | 503 | Guardrail service unavailable | Guardrail provider service is down | > > **Example guardrail error:** > > ```json theme={null} > { > "tpe": "BadRequest", > "errors": [ > { > "description": "Content blocked by guardrail: PII detected", > "key": "fail.guardrail.blocked", > "extras": { > "guardrail_name": "pii-filter", > "entity_type": "CREDIT_CARD" > } > } > ], > "extras": {} > } > ``` > > **How to Fix:** > > * Review the blocked entity type or violation reason in the error response > * Remove or mask sensitive content before retrying > * Check guardrail configuration if blocks are unexpected > * See [Guardrails documentation](/home/guardrails) for configuration options ## Error categories ### Authentication and authorization errors #### 401 Unauthorized | Status | Error code | Type | Description | Common causes | | - | - | - | - | - | | 401 | `BadCredentials` | Authentication | Invalid API key | Missing Authorization header, invalid API key format | | 401 | `BadToken` | Authentication | API key expired | API key has expired | **Example Response:** ```json theme={null} { "tpe": "Unauthorized", "errors": [ { "description": "Invalid token", "key": "fail.unauthorized.badToken", "extras": {} } ], "extras": {} } ``` **How to Fix:** * Verify your API key is correct * Ensure you've included the `Authorization: Bearer ` header * Check that your API key hasn't expired * See [API Keys documentation](/api-reference/api-keys) for more details #### 403 Forbidden | Status | Error code | Type | Description | Common causes | | - | - | - | - | - | | 403 | `InsufficientAccessRights` | Authorization | API key lacks required permissions | Insufficient permissions, wrong API key type | **Example Response:** ```json theme={null} { "tpe": "Forbidden", "errors": [ { "description": "Insufficient access rights", "key": "fail.forbidden.insufficientAccessRights", "extras": {} } ], "extras": {} } ``` **How to Fix:** * Verify your API key has the required permissions * Check if you're using the correct API key type * Contact support if permissions seem incorrect ### Request validation errors #### 400 Bad Request | Status | Error code | Type | Description | Common causes | | - | - | - | - | - | | 400 | `BadRequest` | Validation | Invalid request parameters | Missing required fields, invalid format | | 400 | `InvalidInputParameters` | Validation | Invalid parameter values | Out of range values, unsupported options | | 400 | `InvalidContentType` | Validation | Invalid content type | Malformed JSON, wrong content-type header | **Example Response:** ```json theme={null} { "tpe": "BadRequest", "errors": [ { "description": "Invalid input parameters", "key": "fail.badRequest.invalidParameters", "extras": {} } ], "extras": {} } ``` **How to Fix:** * Check required fields and data formats * Validate parameter values against API documentation * Ensure request body is valid JSON * See specific endpoint documentation for required parameters #### 404 Not Found | Status | Error code | Type | Description | Common causes | | - | - | - | - | - | | 404 | `ResourceNotFound` | Validation | Requested resource doesn't exist | Invalid resource ID, deleted resource | **Example Response:** ```json theme={null} { "tpe": "NotFound", "errors": [ { "description": "Resource is not found", "key": "fail.notFound.resource", "extras": {} } ], "extras": {} } ``` **How to Fix:** * Verify the resource ID is correct * Check if the resource has been deleted * Ensure the endpoint URL is correct ### Rate limiting and quota errors #### 429 Too Many Requests | Status | Error code | Type | Description | Common causes | | - | - | - | - | - | | 429 | `QuotaExceeded` | Rate Limiting | Too many requests in time period | Exceeding per-minute or per-day limits | | 429 | `CompletionModelQuotaError` | Rate Limiting | Model quota exceeded | Monthly usage limit reached | **Example Response:** ```json theme={null} { "tpe": "TooManyRequests", "errors": [ { "description": "Quota exceeded", "key": "fail.tooManyRequests.quotaExceeded", "extras": {} } ], "extras": {} } ``` **How to Fix:** * Implement exponential backoff * Check your rate limits in the dashboard * Consider upgrading your plan for higher limits * See [Rate Limits documentation](/api-reference/rate-limits) for details ### Server and processing errors #### 500 Internal Server Error | Status | Error code | Type | Description | Common causes | | - | - | - | - | - | | 500 | `InternalError` | Server | Unexpected server error | Server-side processing issue | | 500 | `CompletionModelInternalError` | Server | Model processing error | Internal error in model inference | **Example Response:** ```json theme={null} { "tpe": "InternalServerError", "errors": [ { "description": "Internal server error", "key": "fail.internalServerError.generic", "extras": {} } ], "extras": {} } ``` **How to Fix:** * Retry the request after a short delay * Check if the issue persists * Contact support if the error continues #### 503 Service Unavailable | Status | Error code | Type | Description | Common causes | | - | - | - | - | - | | 503 | `CompletionModelUnavailableError` | Server | Model temporarily unavailable | Model service is down for maintenance | **Example Response:** ```json theme={null} { "tpe": "ServiceUnavailable", "errors": [ { "description": "Service temporarily unavailable", "key": "fail.serviceUnavailable.temporary", "extras": {} } ], "extras": {} } ``` **How to Fix:** * Wait and retry after some time * Check service status page * Implement retry logic with exponential backoff ## AI model-specific errors For AI content generation endpoints, the API may return additional error types: ### Model errors | Error Type | Description | | - | - | | `CompletionModelUnavailableError` | AI model is temporarily unavailable | | `CompletionModelInternalError` | Internal error in model processing | | `CompletionModelQuotaError` | Model usage quota exceeded | | `CompletionModelUnauthorizedError` | Invalid model access credentials | | `CompletionModelUnderlyingRequestError` | Error in underlying model request | | `CompletionModelUnsafeRequestError` | Request contains unsafe content | | `CompletionModelNoPredictionError` | Model couldn't generate a prediction | **Example model error:** ```json theme={null} { "tpe": "CompletionModelQuotaError", "errors": [ { "description": "Model usage quota exceeded", "key": "fail.model.quotaExceeded", "extras": {} } ], "extras": {} } ``` ## SDK error types The official Writer SDKs provide structured error handling with specific exception types: ### Python SDK errors | Error Type | HTTP Status | Description | | - | - | - | | `APIConnectionError` | N/A | Network connectivity issues, timeouts, DNS failures | | `APITimeoutError` | N/A | Request timeout exceeded | | `BadRequestError` | 400 | Invalid request parameters or malformed request body | | `AuthenticationError` | 401 | Missing or invalid API key | | `PermissionDeniedError` | 403 | Valid API key but insufficient permissions | | `NotFoundError` | 404 | Requested resource doesn't exist | | `UnprocessableEntityError` | 422 | Request is well-formed but contains semantic errors | | `RateLimitError` | 429 | Rate limit or quota exceeded | | `InternalServerError` | ≥500 | Internal server error | ### JavaScript/Node.js SDK errors | Error Type | HTTP Status | Description | | - | - | - | | `connection_error` | N/A | Network connectivity issues, timeouts, DNS failures | | `timeout_error` | N/A | Request timeout exceeded | | `bad_request` | 400 | Invalid request parameters or malformed request body | | `authentication_error` | 401 | Missing or invalid API key | | `permission_denied` | 403 | Valid API key but insufficient permissions | | `not_found` | 404 | Requested resource doesn't exist | | `unprocessable_entity` | 422 | Request is well-formed but contains semantic errors | | `rate_limit_error` | 429 | Rate limit or quota exceeded | | `internal_server_error` | ≥500 | Internal server error | ### Error handling example This example shows how to handle common error cases when making API requests using the Writer SDKs. ```python Python theme={null} from writerai import Writer import writerai # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() try: response = client.chat.chat( messages=[ { "role": "user", "content": "Write a haiku about programming" } ], model="palmyra-x5" ) print("Success:", response.choices[0].message.content) except writerai.APIConnectionError as e: print("Network error:", e) print("Cause:", e.__cause__) except writerai.RateLimitError as e: print("Rate limited:", e) print("Status code:", e.status_code) # SDK automatically handles retries with exponential backoff except writerai.AuthenticationError as e: print("Authentication failed:", e) print("Status code:", e.status_code) # Refresh API key or redirect to login except writerai.BadRequestError as e: print("Invalid request:", e) print("Status code:", e.status_code) except writerai.InternalServerError as e: print("Server error:", e) print("Status code:", e.status_code) # SDK automatically retries 5xx errors except writerai.APIStatusError as e: print("API error:", e) print("Status code:", e.status_code) print("Response:", e.response) ``` ```javascript JavaScript theme={null} import Writer from '@writer/writer-node'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer({}); try { const response = await client.chat.chat({ messages: [ { role: 'user', content: 'Write a haiku about programming' } ], model: 'palmyra-x5' }); console.log('Success:', response.choices[0].message.content); } catch (error) { if (error.code === 'bad_request') { console.error('Invalid request:', error.message); } else if (error.code === 'authentication_error') { console.error('Authentication failed:', error.message); // Refresh API key or redirect to login } else if (error.code === 'rate_limit_error') { console.error('Rate limited:', error.message); // SDK automatically handles retries with exponential backoff } else if (error.code === 'internal_server_error') { console.error('Server error:', error.message); // SDK automatically retries 5xx errors } else if (error.code === 'connection_error') { console.error('Network error:', error.message); } else { console.error('Unexpected error:', error.message); } } ``` ## Troubleshooting common errors ### 400 Bad request * Verify all required parameters are included * Check parameter value formats and constraints * Ensure request body is valid JSON ### 401 Unauthorized * Verify API key is correct and not expired * Check that the API key has the required permissions * Ensure the Authorization header is properly formatted ### 403 Forbidden * Check if your organization/team has access to the requested resource * Verify that the feature is enabled for your plan * Contact support if you believe this is an error ### 429 Too many requests * Implement exponential backoff retry logic * Check your current usage against rate limits * Consider upgrading your plan for higher limits ### 500 Internal server error * Retry the request after a short delay * Check the [Writer status page](https://status.writer.com/) for known issues * Contact support if the error persists ## Next steps * [API keys](/api-reference/api-keys): learn how to authenticate with Writer APIs * [Rate limits](/api-reference/rate-limits): understand API rate limiting and quotas * [Python SDK](https://github.com/writer/writer-python): official Python library with built-in error handling * [Node.js SDK](https://github.com/writer/writer-node): official JavaScript/Node.js library with built-in error handling # Handle errors Source: https://dev.writer.com/api-reference/error-handling > [!NOTE] > > This table outlines the HTTP status codes you may encounter when using the > API, along with descriptions to help you understand and troubleshoot issues. | Error code | Description | | - | - | | **400** | **Bad request error:** Indicates an issue with the format or content of your request. This error may also encompass other 4XX status errors not specifically listed here. | | **401** | **Authentication error:** There's an issue with your API key, or it's missing from your request headers resulting in unauthorized access. | | **403** | **Permission error:** Your API key doesn't have permission to access the requested resource. | | **404** | **Model not found error:** The specified model couldn't be found. This may be due to an incorrect URL or model ID. | | **429** | **Rate limit exceeded:** You have exceeded the allotted number of requests per time period for your account. Please wait and try your request again later. | | **500** | **API error:** An unexpected error occurred within our systems. If this persists, contact support for further assistance. | | **503** | **Service unavailable:** The server is currently unable to handle the request due to a temporary overload or maintenance. Please retry your request after some time. | | **504** | **Timeout error:** The server didn't receive a timely response from an upstream server. Please retry your request after some time. | **Best practices** > [card] Validate requests > > Ensure that all requests are correctly formatted and include all necessary > parameters and authentication information before sending them to the server. You can check the [API reference](/api-reference) for the correct information. > [card] Check API key > > Ensure that you are using a valid API key, specific to either the API/SDK or Writer Framework. Use the [API Quickstart](/home/quickstart) for the former and the [Writer Framework Quickstart](/framework/quickstart) for the latter. > [card] Check for firewalls > > Ensure that firewalls or security settings are not blocking the Writer API or your application or service using the Writer API or SDK. > [card] Monitor and log errors > > Continuously monitor and log errors on your side to identify patterns or > recurring issues that may require changes to your application or further > investigation. # Delete file Source: https://dev.writer.com/api-reference/file-api/delete-file delete /v1/files/{file_id} Permanently delete a file from the system. This action cannot be undone. # Download file Source: https://dev.writer.com/api-reference/file-api/download-file get /v1/files/{file_id}/download Download the binary content of a file. The response will contain the file data in the appropriate MIME type. # Retry failed files Source: https://dev.writer.com/api-reference/file-api/files-retry post /v1/files/retry Retry processing of files that previously failed to process. This will re-attempt the processing of the specified files. # List files Source: https://dev.writer.com/api-reference/file-api/get-all-files get /v1/files Retrieve a paginated list of files with optional filtering by status, graph association, and file type. # Retrieve file Source: https://dev.writer.com/api-reference/file-api/get-file get /v1/files/{file_id} Retrieve detailed information about a specific file, including its metadata, status, and associated graphs. # Upload file Source: https://dev.writer.com/api-reference/file-api/upload-files post /v1/files Upload a new file to the system. Supports various file formats including PDF, DOC, DOCX, PPT, PPTX, JPG, PNG, EML, HTML, SRT, CSV, XLS, and XLSX. File uploads do not accept team parameters. When you attach a file to a Knowledge Graph, the file inherits the team scope of that Knowledge Graph. # Add file to graph Source: https://dev.writer.com/api-reference/kg-api/add-file-to-graph post /v1/graphs/{graph_id}/file Add a file to a Knowledge Graph. Team access is inherited from the Knowledge Graph; the file itself does not carry team parameters. > [!NOTE] > > Knowledge Graphs can be deployed org-wide (accessible to every team in the organization) or [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5). Both are accessible via the API and SDK. > > * **With an org-scoped API key**, control team scope from the request body: pass `team_ids` on [create](/api-reference/kg-api/create-graph) or [update](/api-reference/kg-api/update-graph), or filter [list](/api-reference/kg-api/list-graphs) with the `team_ids` query parameter. Omit `team_ids` on list to see only org-wide Knowledge Graphs. > * **With a team-scoped API key**, every request is automatically restricted to the key's team. Create assigns to that team; list and retrieve return only that team's Knowledge Graphs; body `team_ids` is not accepted. # Create graph Source: https://dev.writer.com/api-reference/kg-api/create-graph post /v1/graphs Create a new Knowledge Graph. By default, the new Knowledge Graph is org-wide (accessible to every team in the organization). To deploy the Knowledge Graph to specific teams instead, provide a `team_ids` array in the request body. When the request is authenticated with a team-scoped API key, the new Knowledge Graph is automatically assigned to that key's team and `team_ids` in the body is not accepted. > [!NOTE] > > Knowledge Graphs can be deployed org-wide (accessible to every team in the organization) or [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5). Both are accessible via the API and SDK. > > * **With an org-scoped API key**, control team scope from the request body: pass `team_ids` on [create](/api-reference/kg-api/create-graph) or [update](/api-reference/kg-api/update-graph), or filter [list](/api-reference/kg-api/list-graphs) with the `team_ids` query parameter. Omit `team_ids` on list to see only org-wide Knowledge Graphs. > * **With a team-scoped API key**, every request is automatically restricted to the key's team. Create assigns to that team; list and retrieve return only that team's Knowledge Graphs; body `team_ids` is not accepted. # Delete graph Source: https://dev.writer.com/api-reference/kg-api/delete-graph delete /v1/graphs/{graph_id} Delete a Knowledge Graph. > [!NOTE] > > Knowledge Graphs can be deployed org-wide (accessible to every team in the organization) or [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5). Both are accessible via the API and SDK. > > * **With an org-scoped API key**, control team scope from the request body: pass `team_ids` on [create](/api-reference/kg-api/create-graph) or [update](/api-reference/kg-api/update-graph), or filter [list](/api-reference/kg-api/list-graphs) with the `team_ids` query parameter. Omit `team_ids` on list to see only org-wide Knowledge Graphs. > * **With a team-scoped API key**, every request is automatically restricted to the key's team. Create assigns to that team; list and retrieve return only that team's Knowledge Graphs; body `team_ids` is not accepted. # List graphs Source: https://dev.writer.com/api-reference/kg-api/list-graphs get /v1/graphs Retrieve a list of Knowledge Graphs. By default, the response contains only org-wide Knowledge Graphs. To include Knowledge Graphs that are deployed to specific teams, pass one or more team IDs in the `team_ids` query parameter. Requests authenticated with a team-scoped API key always return only that key's team; passing a different value in `team_ids` is rejected. > [!NOTE] > > Knowledge Graphs can be deployed org-wide (accessible to every team in the organization) or [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5). Both are accessible via the API and SDK. > > * **With an org-scoped API key**, control team scope from the request body: pass `team_ids` on [create](/api-reference/kg-api/create-graph) or [update](/api-reference/kg-api/update-graph), or filter [list](/api-reference/kg-api/list-graphs) with the `team_ids` query parameter. Omit `team_ids` on list to see only org-wide Knowledge Graphs. > * **With a team-scoped API key**, every request is automatically restricted to the key's team. Create assigns to that team; list and retrieve return only that team's Knowledge Graphs; body `team_ids` is not accepted. # Question Source: https://dev.writer.com/api-reference/kg-api/question post /v1/graphs/question Ask a question to specified Knowledge Graphs. > [!NOTE] > > Knowledge Graphs can be deployed org-wide (accessible to every team in the organization) or [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5). Both are accessible via the API and SDK. > > * **With an org-scoped API key**, control team scope from the request body: pass `team_ids` on [create](/api-reference/kg-api/create-graph) or [update](/api-reference/kg-api/update-graph), or filter [list](/api-reference/kg-api/list-graphs) with the `team_ids` query parameter. Omit `team_ids` on list to see only org-wide Knowledge Graphs. > * **With a team-scoped API key**, every request is automatically restricted to the key's team. Create assigns to that team; list and retrieve return only that team's Knowledge Graphs; body `team_ids` is not accepted. # Remove file from graph Source: https://dev.writer.com/api-reference/kg-api/remove-file-from-graph delete /v1/graphs/{graph_id}/file/{file_id} Remove a file from a Knowledge Graph. > [!NOTE] > > Knowledge Graphs can be deployed org-wide (accessible to every team in the organization) or [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5). Both are accessible via the API and SDK. > > * **With an org-scoped API key**, control team scope from the request body: pass `team_ids` on [create](/api-reference/kg-api/create-graph) or [update](/api-reference/kg-api/update-graph), or filter [list](/api-reference/kg-api/list-graphs) with the `team_ids` query parameter. Omit `team_ids` on list to see only org-wide Knowledge Graphs. > * **With a team-scoped API key**, every request is automatically restricted to the key's team. Create assigns to that team; list and retrieve return only that team's Knowledge Graphs; body `team_ids` is not accepted. # Retrieve graph Source: https://dev.writer.com/api-reference/kg-api/retrieve-graph get /v1/graphs/{graph_id} Retrieve a Knowledge Graph. > [!NOTE] > > Knowledge Graphs can be deployed org-wide (accessible to every team in the organization) or [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5). Both are accessible via the API and SDK. > > * **With an org-scoped API key**, control team scope from the request body: pass `team_ids` on [create](/api-reference/kg-api/create-graph) or [update](/api-reference/kg-api/update-graph), or filter [list](/api-reference/kg-api/list-graphs) with the `team_ids` query parameter. Omit `team_ids` on list to see only org-wide Knowledge Graphs. > * **With a team-scoped API key**, every request is automatically restricted to the key's team. Create assigns to that team; list and retrieve return only that team's Knowledge Graphs; body `team_ids` is not accepted. # Update graph Source: https://dev.writer.com/api-reference/kg-api/update-graph put /v1/graphs/{graph_id} Update the name, description, web connector URLs, or team assignment of a Knowledge Graph. Including a `team_ids` array replaces the whole team assignment: an empty array makes the Knowledge Graph org-wide, one or more team IDs scope it to exactly those teams. Omitting `team_ids` leaves the current team assignment unchanged. Team-scoped API keys cannot change the team assignment of a Knowledge Graph. > [!NOTE] > > Knowledge Graphs can be deployed org-wide (accessible to every team in the organization) or [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5). Both are accessible via the API and SDK. > > * **With an org-scoped API key**, control team scope from the request body: pass `team_ids` on [create](/api-reference/kg-api/create-graph) or [update](/api-reference/kg-api/update-graph), or filter [list](/api-reference/kg-api/list-graphs) with the `team_ids` query parameter. Omit `team_ids` on list to see only org-wide Knowledge Graphs. > * **With a team-scoped API key**, every request is automatically restricted to the key's team. Create assigns to that team; list and retrieve return only that team's Knowledge Graphs; body `team_ids` is not accepted. # Paginate API results Source: https://dev.writer.com/api-reference/pagination The Writer API supports pagination for list endpoints. By default, the API returns 50 results per page. See below for more information about how to paginate your API requests. ## Pagination parameters The following parameters are available for pagination in the API: | Parameter | Type | Description | | - | - | - | | `limit` | `integer` | The number of items to return per page. The default is 50. The maximum is 100. | | `order` | `string` | The order in which to return the items, based on the `created_at` field for the resource. The default is `desc`. The possible values are `asc` and `desc`. | | `before` | `string` | The ID of first object in the previous page. This parameter instructs the API to return the previous page of results. | | `after` | `string` | The ID of the last object in the next page. This parameter instructs the API to return the next page of results. | ## Pagination response The API returns the following pagination information in the response body: | Parameter | Type | Description | | - | - | - | | `has_more` | `boolean` | Indicates whether there are more pages of results. | | `first_id` | `string` | The ID of the first object in the collection. | | `last_id` | `string` | The ID of the last object in the collection. | ## Pagination example: Retrieving files ### Retrieve two most recently created files The following cURL command retrieves the two most recently created files. ```bash theme={null} curl -X GET "https://api.writer.com/v1/files?limit=2" \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" ``` The response body contains the two most recently created files, along with the pagination information: * The `has_more` parameter is `true`, indicating that there are more files to retrieve * The `first_id` parameter is the ID of the first file in the collection * The `last_id` parameter is the ID of the last file in the collection ```json theme={null} { "data": [ { "id": "c6006e1f", "created_at": "2025-06-04T18:19:12.495984Z", "name": "paper.pdf", "graph_ids": [], "status": "completed" }, { "id": "57c3754c", "created_at": "2025-06-04T18:19:09.973779Z", "name": "meeting_notes.pdf", "graph_ids": [], "status": "completed" } ], "has_more": true, "first_id": "c6006e1f", "last_id": "57c3754c" } ``` ### Retrieve the next page of results To retrieve the next page of results, you can use the `after` parameter to specify the ID of the last object in the previous page. ```bash theme={null} curl -X GET "https://api.writer.com/v1/files?limit=2&after=57c3754c" \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" ``` ## SDK support The Python and JavaScript SDKs provide iterators that automatically handle pagination for you. See more information about pagination in the [Python SDK](https://github.com/writer/writer-python/blob/main/README.md#pagination) and [JavaScript SDK](https://github.com/writer/writer-node/blob/main/README.md#pagination) documentation. # Understand rate limits Source: https://dev.writer.com/api-reference/rate-limits Understand API rate limits for Writer endpoints. Learn about RPM and TPM limits, best practices, and retry strategies for optimal performance. > [!NOTE] > > For custom rate limits, **[contact Sales](https://go.writer.com/contact-sales)**. To ensure optimal service performance and fairness in resource allocation, our endpoints enforce the following rate limits. 1. **RPM (requests per minute)**: 400 2. **TPM (token per min)**: 25,000 ## Best practices > [accordion] Monitor request rates > > Implement mechanisms in your applications to track and regulate the > frequency of your requests to stay within the prescribed limits. > [accordion] Adaptive retry strategies > > In cases where you exceed these limits, employ adaptive retry strategies > with exponential backoff to handle retries efficiently and reduce the > likelihood of consecutive limit breaches. > [accordion] Response to HTTP 429 status codes > > Prepare to handle HTTP 429 (too many requests) responses by pausing or > slowing down request rates. # Secure your integration Source: https://dev.writer.com/api-reference/security Ensure compliance and secure communications between Writer and your server. This page covers transport-layer security (TLS) for API traffic. For data-at-rest encryption and key management, see [Encryption Key Management](/home/encryption-key-management). Writer API supports TLS 1.3 by default and TLS 1.2+ in other cases. ## Using TLS and HTTPS TLS refers to the process of securely transmitting data between the client—the app or browser that your customer is using—and your server. This was originally performed using the SSL (Secure Sockets Layer) protocol. However, this is outdated and no longer secure, and has been replaced by TLS. The term “SSL” continues to be used colloquially when referring to TLS and its function to protect transmitted data. Payment pages must make use of a modern version of TLS (for example, TLS 1.2) as it significantly reduces the risk of you or your customers being exposed to a man-in-the-middle attack. TLS attempts to accomplish the following: * Encrypt and verify the integrity of traffic between the client and your server * Verify that the client is communicating with the correct server. In practice, this usually means verifying that the owner of the domain and the owner of the server are the same entity. This helps prevent man-in-the-middle attacks. Without it, there’s no guarantee that you’re encrypting traffic to the right recipient. Additionally, your customers are more comfortable sharing sensitive information on pages visibly served over HTTPS, which can help increase your customer conversion rate. If need be, you can test your integration without using HTTPS, and enable it once you’re ready to accept live charges. However, all interactions between your server and Writer must use TLS 1.2 (i.e, when using our libraries). ## Setting up TLS SERVING RESOURCES SECURELY\ You should make sure that any resources (JavaScript, CSS, images, etc.) are also served over TLS to avoid a mixed content warning being shown to your customers in their browser. A digital certificate—a file issued by a certification authority (CA)—is needed in order to use TLS. When installed, this certificate assures the client that it’s really communicating with the server it expects to be talking to, not an impostor. You should get a digital certificate from a reputable certificate provider, such as: * Let’s Encrypt * DigiCert * NameCheap\ Certificates can vary in cost, depending on the type of certificate and provider. Let’s Encrypt is a certificate authority that provides certificates for free. Conceptually, setting up TLS is very straightforward: a certificate is purchased from a suitable provider, and then your server is configured to use it. The actual process does tend to be somewhat complex, and we recommend you follow the installation guide of the provider you use. As TLS is a complex suite of cryptographic tools, it's easy to miss a few details. We recommend using the SSL Server Test by Qualys SSL Labs to make sure you have everything set up in a secure way. ## Additional security considerations It can be a security risk to include JavaScript from other sites as your security becomes dependent on theirs. If they’re ever compromised, an attacker may be able to execute arbitrary code on your page. In practice, many sites make use of JavaScript for services like Google Analytics, even on secure pages. Nonetheless, it’s something to be aware of, and ideally minimize. If you’re making use of webhooks, we recommend using TLS for the endpoint to avoid traffic being intercepted and the notifications altered (sensitive information is never included in a webhook event). While complying with the Data Security Standards is important, it shouldn’t be where you stop thinking about security. Some good resources to learn about web security are: * OWASP * SANS * NIST\ Out-of-scope card data that you can safely store\ Writer returns non-sensitive card information in the response to a charge request. This includes the card type, the last four digits of the card, and the expiration date. This information is not subject to PCI compliance, so you are able to store any of these properties in your database. # Parse PDF Source: https://dev.writer.com/api-reference/tool-api/pdf-parser post /v1/tools/pdf-parser/{file_id} Parse PDF to other formats. > [!WARNING] > > **Deprecation notice**: The [parse PDF API endpoint](/api-reference/tool-api/pdf-parser) at `/v1/tools/pdf-parser/{file_id}` is deprecated and will be removed on **December 22, 2025**. > > **Migration path**: We plan to introduce a prebuilt PDF parsing tool for chat completions that will provide similar functionality. This tool will work similarly to other prebuilt tools like the [LLM tool](/home/model-delegation). We will provide more details about this alternative when it becomes available. # Annotated Text Source: https://dev.writer.com/components/annotatedtext Shows text with annotations ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/annotatedtext.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=78fb88811d7e3486ed8f72e02339ea92) ## Overview The **Annotated Text** component displays text with visual annotations and highlights. It allows users to see text with embedded annotations that are color-coded to distinguish different types of content or sections. Annotated text is essential for educational content, document review systems, and any interface where text needs visual distinction between different types of content. It provides a way to highlight important terms and sections without cluttering the main display. ## Common use cases * **Educational content**: Provide explanations and definitions for complex terms * **Document review**: Show comments, suggestions, and feedback on text * **Code documentation**: Highlight and explain code snippets with annotations * **Research papers**: Show citations, references, and additional context * **Legal documents**: Display legal annotations and explanations ## How it works 1. **Text content**: Displays the main text content with embedded annotations 2. **Annotation markers**: Shows visual indicators for annotated sections 3. **Styling**: Customize appearance of annotations and text with colors and CSS classes The component displays text with embedded annotations that are visually highlighted using color coding and styling to distinguish different types of content or sections. ## Configuration options ### Basic settings * **Annotated text**: The main text with embedded annotation markers, must be a JSON string or a state reference to an array ### Advanced settings * **Enable markdown**: Adds markdown support for automatically sanitizing unsafe elements * **Enable copy buttons**: Adds a control bar with both copy text and JSON buttons * **Rotate hue**: Rotates the hue of annotated text colors depending on the content of the string ### Styling options * **Text color**: Set the color of the main text * **Annotation colors**: Set colors for different annotation types * **Custom CSS classes**: Apply additional styling ## Example ### Contract review and analysis This example shows how to create a contract review interface with highlighted terms and clauses. **Interface:** * File input component for file upload * Annotated text component for annotated contract content **Annotated Text configuration:** * **Annotated text**: JSON array containing contract text with embedded annotations in the format `["text", ["highlighted term", "label"], "more text"]` ## Best practices 1. **Clear annotations**: Make annotation content concise and informative 2. **Visual indicators**: Use clear visual cues to show where annotations exist 3. **Performance**: Limit the number of annotations to avoid overwhelming users 4. **Consistent styling**: Use consistent annotation styling throughout your interface 5. **Context relevance**: Ensure annotations provide relevant and helpful information ## Fields
Name Type Description Options
Annotated text Object Value array with text/annotations. Must be a JSON string or a state reference to an array. \-
Reference Color The colour to be used as reference for chroma and luminance, and as the starting point for hue rotation. \-
Seed value Number Choose a different value to reshuffle colours. \-
Rotate hue Boolean If active, rotates the hue depending on the content of the string. If turned off, the reference colour is always used. \-
Enable markdown Boolean If active, the output will be sanitized; unsafe elements will be removed. \-
Enable copy button Boolean Enable a copy button that lets users to copy the contents in this field to their clipboard \-
Button Color - \-
Button text Color - \-
Primary text Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Button Source: https://dev.writer.com/components/button A standalone button component that can be linked to a click event handler. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/button.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=9d815fb527db70a4663f7a3ea2dd7575) ## Fields
Name Type Description Options
Text Text - \-
Icon Text Lucide icon name in kebab-case, e.g. "badge-check". \-
Disabled Boolean Disables all event handlers. \-
Button Color - \-
Button text Color - \-
Button shadow Shadow - \-
Separator Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-click > > Capture single clicks. > > ```python theme={null} > def handle_button_click(state): > > # Increment counter when the button is clicked > > state["counter"] += 1 > ``` # Chatbot Source: https://dev.writer.com/components/chatbot A chatbot component to build human-to-AI interactions. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/chatbot.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=925fc9ec7ff5b6210519f0076e9d81ba) Connect it to an LLM by handling the `wf-chatbot-message` event, which is triggered every time the user sends a message. You can add `actions` to messages, which are buttons that trigger the `wf-chatbot-action-click`. See the stubs for more details. ## Fields
Name Type Description Options
Conversation Object An array with messages or a variable that contains your conversation as an object. \-
Assistant initials Text - \-
User initials Text - \-
Enable markdown Boolean If active, the output will be sanitized; unsafe elements will be removed. \-
Enable file upload Text -
  1. Single file
  2. Multiple files
  3. No
Enable image paste Boolean Allow users to paste images directly into the chat input using Ctrl/Cmd+V. \-
Placeholder Text - \-
Assistant role Color - \-
User role Color - \-
Avatar Color - \-
Avatar text Color - \-
Accent Color - \-
Container background Color - \-
Primary text Color - \-
Secondary text Color - \-
Separator Color - \-
Button Color - \-
Button text Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-chatbot-message > > Triggered when the user sends a message. > > ```python theme={null} > def handle_message_simple(payload, state): > > # payload contains a dict in the form { "role": "user", "message": "hello"} > > state["conversation"] += [payload] > state["conversation"] += [{ > "role": "assistant", > "content": "Hello human" if payload == "Hello" else "I don't understand" > }] > > # Handle streaming by appending to the last message > > import time > for i in range(10): > conv = state["conversation"] > conv[-1]["content"] += f" {i}" > state["conversation"] = conv > time.sleep(0.5) > ``` > [accordion] wf-chatbot-action-click > > Handle clicks on actions. > > ```python theme={null} > def handle_action_simple(payload, state): > > # payload contains the "data" property of the action > > if payload == "change_title": > state["app_background_color"] = "red" > > # Make an action available when adding a message > > def handle_message_with_action(payload, state): > state["conversation"] += [payload] > state["conversation"] += [{ > "role": "assistant", > "content": "I don't know, but check this out.", > "actions": [{ > "subheading": "Resource", > "name": "Surprise", > "desc": "Click to be surprised", > "data": "change_title" > }] > }] > ``` > [accordion] wf-file-change > > Triggered when files are uploaded > > ```python theme={null} > def handle_file_upload(state, payload): > > # An array of dictionaries is provided in the payload > # The dictionaries have the properties name, type and data > # The data property is a file-like object > > uploaded_files = payload > for i, uploaded_file in enumerate(uploaded_files): > name = uploaded_file.get("name") > file_data = uploaded_file.get("data") > with open(f"{name}-{i}.jpeg", "wb") as file_handle: > file_handle.write(file_data) > ``` # Checkbox Input Source: https://dev.writer.com/components/checkboxinput A user input component that allows users to choose multiple values from a list of options using checkboxes. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/checkboxinput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=2339dfe24b24547585529dff24aa7199) ## Fields
Name Type Description Options
Label Text - \-
Options Key-Value Key-value object with options. Must be a JSON string or a state reference to a dictionary. \-
Orientation Text Specify how to lay out the options.
  1. Vertical
  2. Horizontal
Primary text Color - \-
Accent Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-options-change > > Sent when the selected options change. > > ```python theme={null} > def onchange_handler(state, payload): > > # Set the state variable "selected" to the selected options. > # The payload will be a list, as multiple options are allowed. > > state["selected"] = payload > ``` # Column Source: https://dev.writer.com/components/column A layout component that organizes its child components in columns. Must be inside a Column container component. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/column.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=67c206cffd38c41c9ffbe67a81d0b01a) ## Fields
Name Type Description Options
Title Text - \-
Width (factor) Number Relative size when compared to other columns in the same container. A column of width 2 will be double the width of one with width 1. \-
Sticky Boolean - \-
Collapsible Boolean - \-
Start collapsed Boolean Only applied when the column is collapsible. \-
Separator Color - \-
Padding Padding - \-
Content alignment (H) Align (H) - \-
Content alignment (V) Align (V) - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Column Container Source: https://dev.writer.com/components/columns Serves as container for Column components ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/columns.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=e702dcb5955fde558967268f8932cc2b) ## Fields
Name Type Description Options
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# DataFrame Source: https://dev.writer.com/components/dataframe A component to display Pandas DataFrames. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/dataframe.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=c444e32b85b12ede5bb8e41a99eca8f5) ## Fields
Name Type Description Options
Data Text Must be a state reference to a Pandas dataframe or PyArrow table. Alternatively, a URL for an Arrow IPC file. \-
Show index Boolean Shows the dataframe's index. If an Arrow table is used, shows the zero-based integer index. \-
Enable search Boolean - \-
Enable adding a record Boolean - \-
Enable updating a record Boolean - \-
Enable download Boolean Allows the user to download the data as CSV. \-
Actions Key-Value Define rows actions \-
Enable markdown Boolean If active, the output will be sanitized; unsafe elements will be removed. \-
Display row count Number Specifies how many rows to show simultaneously. \-
Wrap text Boolean Not wrapping text allows for an uniform grid, but may be inconvenient if your data contains longer text fields. \-
Primary text Color - \-
Secondary text Color - \-
Accent Color - \-
Separator Color - \-
Background Color - \-
Font style Text -
  1. normal
  2. monospace
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-dataframe-add > > Capture adding a row. > > ```python theme={null} > # Subscribe this event handler to the `wf-dataframe-add` event > # > # more on : https://dev.writer.com/framework/dataframe > def on_record_add(state, payload): > payload['record']['sales'] = 0 # default value inside the dataframe > state['mydf'].record_add(payload) # should contain an EditableDataFrame instance > ``` > [accordion] wf-dataframe-update > > Capture a cell change. > > ```python theme={null} > # Subscribe this event handler to the `wf-dataframe-update` event > # > # more on : https://dev.writer.com/framework/dataframe > def on_record_change(state, payload): > state['mydf'].record_update(payload) # should contain an EditableDataFrame instance > ``` > [accordion] wf-dataframe-action > > Remove or open a row. > > ```python theme={null} > # Subscribe this event handler to the `wf-dataframe-action` event > # > # more on : https://dev.writer.com/framework/dataframe > def on_record_action(state, payload): > # state['mydf'] should contains an EditableDataFrame instance > record_index = payload['record_index'] > if payload['action'] == 'remove': > state['mydf'].record_remove(payload) # should contain an EditableDataFrame instance > if payload['action'] == 'open': > state['record'] = state['mydf'].record(record_index) # dict representation of record > ``` # Date Input Source: https://dev.writer.com/components/dateinput A user input component that allows users to select a date using a date picker interface. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/dateinput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=3b6ac36de9d370ad186445ca5890b8a0) ## Fields
Name Type Description Options
Label Text - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-date-change > > Capture changes to this control. > > ```python theme={null} > > def onchange_handler(state, payload): > > # Set the state variable "new_date" to the new value, provided as a YYYY-MM-DD string. > > state["new_date"] = payload > ``` # File Input Source: https://dev.writer.com/components/fileinput A user input component that allows users to upload files. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/fileinput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=84f95658a2dc7fe861dea099da831b44) ## Fields
Name Type Description Options
Label Text - \-
Allowed file types Text Provides hints for browsers to select the correct file types. You can specify extensions and MIME types separated by comma, or leave empty to accept any file. \-
Allow multiple files Boolean - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-file-change > > Capture changes to this control. > > ```python theme={null} > def onchange_handler(state, payload): > > # An array of dictionaries is provided in the payload > # The dictionaries have the properties name, type and data > # The data property is a file-like object > > uploaded_files = payload > for i, uploaded_file in enumerate(uploaded_files): > name = uploaded_file.get("name") > file_data = uploaded_file.get("data") > with open(f"{name}-{i}.jpeg", "wb") as file_handle: > file_handle.write(file_data) > ``` # Heading Source: https://dev.writer.com/components/heading A text component used to display headings or titles in different sizes and styles. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/heading.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=3d8b97932c7ed2d32b1c3797db808c5e) ## Fields
Name Type Description Options
Text Text Add text directly, or reference state elements with @. \-
Heading type Text -
  1. h1 (Big)
  2. h2 (Normal)
  3. h3 (Small)
  4. h4 (Smallest)
Alignment Text -
  1. Left
  2. Center
  3. Right
Primary text Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Horizontal Stack Source: https://dev.writer.com/components/horizontalstack A layout component that stacks its child components horizontally, wrapping them to the next row if necessary. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/horizontalstack.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=482d20aa0670d593a86ba7c75c125bc8) ## Fields
Name Type Description Options
Padding Padding - \-
Content alignment (H) Align (H) - \-
Content alignment (V) Align (V) - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# HTML Element Source: https://dev.writer.com/components/html A generic component that creates customisable HTML elements, which can serve as containers for other components. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/html.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=e91906d9d569514e09b3ed67d6a8298c) You can configure the element type, styles, and attributes to fit your design requirements. You can link them to state for advanced use cases, such as custom animations. All valid HTML tags are supported, including tags such as `iframe`, allowing you to embed external sites. Take into account the potential risks of adding custom HTML to your app, including XSS. Be specially careful when injecting user-generated data. ## Fields
Name Type Description Options
Element Text Set the type of HTML element to create, e.g., 'div', 'section', 'span', etc. \-
Styles Object Define the CSS styles to apply to the HTML element using a JSON object or a state reference to a dictionary. \-
Attributes Object Set additional HTML attributes for the element using a JSON object or a dictionary via a state reference. \-
HTML inside Text Define custom HTML to be used inside the element. It will be wrapped in a div and rendered after children components. \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# IFrame Source: https://dev.writer.com/components/iframe A component to embed an external resource in an iframe. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/iframe.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=f4aba06e4441d3099c6af3e1f2f54328) ## Fields
Name Type Description Options
Source Text A valid URL \-
Referrer Policy Text Define which referrer is sent when fetching the resource
  1. no-referrer
  2. no-referrer-when-downgrade
  3. origin
  4. origin-when-cross-origin
  5. same-origin
  6. strict-origin
  7. strict-origin-when-cross-origin
  8. unsafe-url
Separator Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-load > > Fires when the resource has successfully loaded. > > ```python theme={null} > def load_handler(state): > > # Sets status message when resource is loaded > > state["status"] = "Page loaded" > ``` # Image Source: https://dev.writer.com/components/image A component to display images. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/image.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=015843c9ddf0cefab72faf8e53e6adc5) Use your app's static folder to serve images directly. For example, `static/my_image.png`. Alternatively, pass a Matplotlib figure via state. `state["my_fig"] = fig` and then setting the *Image* source to `@{fig}` You can also use packed files or bytes: `state["img_b"] = wf.pack_bytes(img_bytes, "image/png")` `state["img_f"] = wf.pack_file(img_file, "image/png")` ## Fields
Name Type Description Options
Source Text A valid URL. Alternatively, you can provide a state reference to a Matplotlib figure or a packed file. \-
Caption Text Leave blank to hide. \-
Max width (px) Number - \-
Max height (px) Number - \-
Secondary text Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-click > > Capture single clicks. > > ```python theme={null} > def click_handler(state): > > # Increment counter when the image is clicked > > state["counter"] += 1 > ``` # JSON Viewer Source: https://dev.writer.com/components/jsonviewer A component to explore JSON data as a hierarchy. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/jsonviewer.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=ff2e334d157c3cdc5eac0ae716a49c47) ## Fields
Name Type Description Options
Data Object - \-
Initial depth Number Sets the initial viewing depth of the JSON tree hierarchy. Use -1 to display the full hierarchy. \-
Hide root Boolean Don't show the type of the root node when it's an Object or an Array. \-
Enable copy button Boolean Enable a copy button that lets users to copy the contents in this field to their clipboard \-
JSON indentation Width - \-
Secondary text Color - \-
Separator Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Link Source: https://dev.writer.com/components/link A component to create a hyperlink. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/link.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=aeb68e5c7bfe61311af4c85a80a69213) ## Fields
Name Type Description Options
URL Text Specify a URL or choose a page. Keep in mind that you can only link to pages for which a key has been specified. \-
Target Text Specifies where to open the linked document.
  1. Self
  2. Blank
  3. Parent
  4. Top
Rel Text Specifies the relationship between the current document and the linked document. \-
Text Text The text to display in the link. \-
Primary text Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Message Source: https://dev.writer.com/components/message A component that displays a message in various styles, including success, error, warning, and informational. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/message.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=d524a6480f207b32ea31aea16532b149) ## Overview The **Message** component displays status messages, notifications, and feedback to users. It uses prefix characters to determine the message type and styling automatically. Message components support different types (success, error, warning, loading, info) with appropriate styling and can display dynamic content from state variables. They're essential for creating responsive, user-friendly interfaces that keep users informed. ## Common use cases * **Status updates**: Show progress messages during processing operations * **Error notifications**: Display validation errors or system failures * **Success confirmations**: Confirm successful actions or completions * **Loading states**: Show animated loading messages during operations * **Form validation**: Display field validation errors and warnings ## How it works 1. **Message content**: Display static text or reference state variables 2. **Prefix-based types**: Use prefix characters to determine message type automatically. For example, `+` makes the message green, `-` makes it red, and `%` provides a dynamic loading icon. 3. **Dynamic updates**: Content updates automatically when state variables change 4. **Visual styling**: Each message type has distinct colors and styling 5. **Conditional display**: Messages can show or hide based on conditions The component provides immediate feedback to users about the state of their interactions and system operations. ## Configuration options ### Basic settings * **Message**: The text content to display (supports state variable references) * **Prefix characters**: Use prefixes to determine message type automatically. For example, `+` in front of the message makes it green: `+Operation completed successfully`. ### Message types and prefixes * **Success**: Prefix with `+` (for example, `"+Operation completed successfully"`) * **Error**: Prefix with `-` (for example, `"-An error occurred"`) * **Warning**: Prefix with `!` (for example, `"!Please check your input"`) * **Loading**: Prefix with `%` (for example, `"%Processing your request..."`) * **Info**: No prefix (for example, `"This is an informational message"`) ### Styling options * **Success color**: Customize success message background color (default: Green3) * **Error color**: Customize error message background color (default: Orange2) * **Warning color**: Customize warning message background color (default: #FFE999) * **Info color**: Customize info message background color (default: Blue2) * **Loading color**: Customize loading message background color (default: Blue2) * **Primary text color**: Set the text color * **Custom CSS classes**: Apply additional styling ## Example ### Processing status updates Create a workflow that shows different status messages during file processing. **Interface:** * File input to upload a file * Button component to start file processing * Message component for status updates **Message configuration:** * **Message**: `@{status_message}` (with `%` prefix for loading, `+` for success, `-` for errors) ![Message configuration](https://mintcdn.com/writer/pM8WhgC5nDcujQ4i/images/agent-builder/components/message-configuration.png?fit=max\&auto=format\&n=pM8WhgC5nDcujQ4i\&q=85\&s=9551475f5c4202ba6800c522ef98a62a) ## Best practices 1. **Clear messaging**: Use concise, clear language that users can understand immediately 2. **Appropriate types**: Choose the correct message type for the content (info, success, warning, error) 3. **Dynamic content**: Use state variables to show relevant, up-to-date information 4. **Conditional display**: Show messages only when relevant to avoid interface clutter 5. **Consistent styling**: Maintain consistent message styling across your interface 6. **Context**: Provide enough context for users to understand and act on the message ## Fields
Name Type Description Options
Message Text Prefix with '+' for a success message, with '-' for error, '!' for warning, '%' for loading. No prefix for info. Leave empty to hide. \-
Success Color - \-
Error Color - \-
Warning Color - \-
Info Color - \-
Loading Color - \-
Primary text Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Metric Source: https://dev.writer.com/components/metric A component that prominently displays a metric value and associated information. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/metric.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=659159fc10c3e8b6607febfbb60b5bff) ## Fields
Name Type Description Options
Name Text - \-
Value Text The main value to be displayed. It's not limited to numbers. \-
Description Text - \-
Note Text Prefix with '+' for a positive message, with '-' for a negative message. \-
Primary text Color - \-
Secondary text Color - \-
Positive Color - \-
Neutral Color - \-
Negative Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Multiselect Input Source: https://dev.writer.com/components/multiselectinput A user input component that allows users to select multiple values from a searchable list of options. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/multiselectinput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=d4f1b3922858c3241cc961bc59a9c3ad) ## Fields
Name Type Description Options
Label Text - \-
Options Key-Value Key-value object with options. Must be a JSON string or a state reference to a dictionary. \-
Placeholder Text Text to show when no options are selected. \-
Maximum count Number The maximum allowable number of selected options. Set to zero for unlimited. \-
Accent Color The colour of the chips created for each selected option. \-
Chip text Color The colour of the text in the chips. \-
Primary text Color - \-
Container background Color - \-
Separator Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-options-change > > Sent when the selected options change. > > ```python theme={null} > def onchange_handler(state, payload): > > # Set the state variable "selected" to the selected option > > state["selected"] = payload > ``` # Number Input Source: https://dev.writer.com/components/numberinput A user input component that allows users to enter numeric values. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/numberinput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=9ac0193e8bc4b79c02f96941b0dc3f4b) ## Fields
Name Type Description Options
Label Text - \-
Placeholder Text - \-
Minimum value Number - \-
Max value Number - \-
Step Number - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-number-change > > Capture changes as they happen. > > ```python theme={null} > > def onchange_handler(state, payload): > > # Set the state variable "new_val" to the new value > > state["new_val"] = payload > ``` > [accordion] wf-number-change-finish > > Capture changes once this control has lost focus. > > ```python theme={null} > > def onchange_handler(state, payload): > > # Set the state variable "new_val" to the new value > > state["new_val"] = payload > ``` # Page Source: https://dev.writer.com/components/page A container component representing a single page within the application. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/page.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=64979436113cfd5e25e7b99c74b6599b) ## Fields
Name Type Description Options
Page key Identifying Key Unique identifier. It's needed to enable navigation to this Page. \-
Page mode Text -
  1. Compact
  2. Wide
Accent Color - \-
Primary text Color - \-
Secondary text Color - \-
Emptiness Color Page background color \-
Container background Color - \-
Container shadow Shadow - \-
Separator Color - \-
Button Color - \-
Button text Color - \-
Button shadow Shadow - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-keydown > > Captures all key activity while this page is open. > > ```python theme={null} > > def handle_keydown(state, payload): > # The payload is a dictionary containing the key code and modifier keys. > # For example, > # { > # "key": "ArrowDown", > # "ctrl_key": False, > # "shift_key": False, > # "meta_key": False > # } > > key_activated = payload.get("key") > delta = 0 > if key_activated == "ArrowLeft": > delta += -10 > elif key_activated == "ArrowRight": > delta += 10 > > shift_key = payload.get("shift_key") > if shift_key: > delta *= 2 # Shift makes it go faster > > state["position"] += delta > > ``` > [accordion] wf-page-open > > Emitted when the page is opened. > > ```python theme={null} > > def handle_page_open(state, payload): > page_key = payload > state["message"] = f"The page {page_key} has been opened." > > ``` # Pagination Source: https://dev.writer.com/components/pagination A component that can help you paginate records, for example from a Repeater or a DataFrame. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/pagination.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=242ed1a2e60edda6f05cc508ad4f4bfd) ## Fields
Name Type Description Options
Page Number The current page number. \-
Page Size Number The number of items per page. \-
Total Items Number The total number of items \-
Page Size Options Text A comma-separated list of page size options. If it's empty, the user can't change the page size. Set your default page size as the first option. \-
Show All Option Boolean Show an option to show all records. \-
Jump To Boolean Show an option to jump to a specific page. \-
## Events > [accordion] wf-change-page > > Fires when the user pick a page > > ```python theme={null} > def handle_page_change(state, payload): > page = payload > state["page"] = page > > records = _load_records_from_db(start = state["page"] * state["pageSize"], limit = state["pageSize"]) > # update a repeater > state["highlighted_members"] = {r.id: r for r in records} > ``` > [accordion] wf-change-page-size > > Fires when the user change the page size. > > ```python theme={null} > def handle_page_size_change(state, payload): > state['pageSize'] = payload > > records = _load_records_from_db(start = state["page"] * state["pageSize"], limit = state["pageSize"]) > # update a repeater > state["highlighted_members"] = {r.id: r for r in records} > ``` # PDF Source: https://dev.writer.com/components/pdf A component to embed PDF documents. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/pdf.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=46b35fb047b13acdaf7d2538cdb04c4d) ## Fields
Name Type Description Options
PDF source Text A valid URL. Alternatively, you can provide a state reference to a packed PDF file. \-
Highlights Object A list of highlights to be applied to the PDF as a JSON array of strings. \-
Selected highlight match Number The index of the selected highlight match. \-
Page Number The page to be displayed. \-
Enable controls Boolean Show controls to navigate the PDF. \-
Container background Color - \-
Separator Color - \-
Primary text Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Plotly Graph Source: https://dev.writer.com/components/plotlygraph A component that displays Plotly graphs. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/plotlygraph.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=d73f45de15672a4c982cb82acb37ab10) You can listen to events triggered by Plotly.js and add interactivity to your charts. For example, implement cross-filtering. ## Fields
Name Type Description Options
Graph specification Object Plotly graph specification. Pass it using state, e.g. @, or paste a JSON specification. \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] plotly-click > > Sends a list with the clicked points. > > ```python theme={null} > ``` > [accordion] plotly-selected > > Sends a list with the selected points. > > ```python theme={null} > ``` > [accordion] plotly-deselect > > Triggered when points are deselected. > > ```python theme={null} > ``` # Progress Bar Source: https://dev.writer.com/components/progressbar A component to display a progression. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/progressbar.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=ed78987befd23991e3d2d9758da124fa) ## Fields
Name Type Description Options
Label Text - \-
Value Number - \-
Minimum value Number - \-
Maximum value Number - \-
Display percentage Boolean - \-
Accent Color - \-
Primary text Color - \-
Separator Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-click > > Triggered when the Progress bar is clicked. > > ```python theme={null} > def handle_progress_bar_click(): > print("The Progress bar was clicked") > ``` # Radio Input Source: https://dev.writer.com/components/radioinput A user input component that allows users to choose a single value from a list of options using radio buttons. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/radioinput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=62f8fbd28517eeb9e69b3f04df059665) ## Fields
Name Type Description Options
Label Text - \-
Options Key-Value Key-value object with options. Must be a JSON string or a state reference to a dictionary. \-
Orientation Text Specify how to lay out the options.
  1. Vertical
  2. Horizontal
Primary text Color - \-
Accent Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-option-change > > Sent when the selected option changes. > > ```python theme={null} > def onchange_handler(state, payload): > > # Set the state variable "selected" to the selected radio option > > state["selected"] = payload > ``` # Slider Range Input Source: https://dev.writer.com/components/rangeinput A user input component that allows users to select numeric values range using a range slider with optional constraints like min, max, and step. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/rangeinput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=97dd38e810528289dc0a7ef53d95694a) ## Fields
Name Type Description Options
Label Text - \-
Minimum value Number - \-
Maximum value Number - \-
Step size Number - \-
Accent Color - \-
Popover color Color - \-
Popover background Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-range-change > > Capture changes to this control. > > ```python theme={null} > > def onchange_handler(state, payload): > > # Set the state variables "from" & "to" to the new range > state["from"] = payload[0] > state["to"] = payload[1] > ``` # Rating Input Source: https://dev.writer.com/components/ratinginput A user input component that allows users to provide a rating. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/ratinginput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=c6c89acc844e5cc114074d2c2c1c9916) ## Fields
Name Type Description Options
Label Text - \-
Feedback Text -
  1. Stars
  2. Faces
  3. Hearts
Minimum value Number Valid values are 0 and 1. \-
Max value Number Valid values are between 2 and 11. \-
Step Number Valid values are between 0.25 and 1. \-
Accent Color - \-
Primary text Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-number-change > > ```python theme={null} > > def onchange_handler(state, payload): > > # Set the state variable "rating" to the new value > > state["rating"] = payload > ``` # Repeater Source: https://dev.writer.com/components/repeater A container component that repeats its child components based on a dictionary. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/repeater.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=fe9fc34c90e919d197cda24ad9971849) ## Overview The **Repeater** component dynamically creates copies of its child components based on a dictionary or array. It's similar to a for-each loop in programming, but for UI elements. Use Repeaters when you need to display lists, collections, or any data where you don't know the exact number of items in advance. Inside a Repeater, you can access: * `@{item}`: the current item's value * `@{itemId}`: the current item's index (for arrays) or key (for dictionaries) ## Common use cases * **Dynamic lists**: Display files, tasks, messages, or any collection of items * **Search results**: Show filtered or API-fetched data * **User-generated content**: Display comments, reviews, or form responses * **Product catalogs**: Render product cards or inventory items * **Data tables**: Create rows based on database queries or structured output ## How it works 1. **Data source**: Bind the Repeater to a state variable containing an array or dictionary 2. **Child components**: Add components inside the Repeater that define the template 3. **Variable access**: Use `@{item}` and `@{itemId}` to display data for each iteration 4. **Nested Repeaters**: Nest Repeaters to display hierarchical data structures 5. **Input binding**: Bind input components to specific items using `@{itemId}` for interactive lists ## Configuration options ### Basic settings * **Repeater object**: The state variable containing the array or dictionary to iterate over (for example, `@{myList}`) * **Key variable name**: The variable name for accessing the current item's key or index (default: `itemId`) * **Value variable name**: The variable name for accessing the current item's value (default: `item`) ### Visibility Set custom visibility conditions to show the Repeater only when data is available (for example, `myList` to hide when empty). ## Using inputs within Repeaters When you add input components (like Text Input, Text Area Input, or other form fields) inside a Repeater, you need to properly bind them to capture user input for each repeated item. ### Binding inputs to dictionary items The most reliable approach is to use a dictionary as your Repeater data source and bind inputs using the `itemId` to target specific dictionary keys: ``` state_variable[itemId].property_name ``` **Example - Text Area Input inside a Repeater** If your state variable is `products` and you want each product to have a `description` property that users can edit: 1. Set up your Repeater with **Repeater object**: `@{products}` 2. Add a Text Area Input inside the Repeater 3. Set the Text Area Input's **Link variable** to: `products[itemId].description` This creates or updates the `description` key for each specific product in your dictionary. As users type in each Text Area Input, the corresponding product's description updates in your state. ### Managing editable lists with temporary state For more complex scenarios where you need to edit one item at a time: 1. **Create a temporary state variable** to hold the draft being edited (for example, `current_draft`) 2. **Track which item is being edited** using a state variable like `editing_item_id` 3. **Show input fields conditionally** using visibility rules that check if `@{itemId} == @{editing_item_id}` 4. **Display read-only content** for items that aren't being edited 5. **Copy data** from the temporary variable back to your main data structure when the user saves This pattern prevents multiple items from being edited simultaneously and provides a clearer user experience when editing items in a list. ### Best practices for Repeater inputs 1. **Use dictionaries over arrays**: Dictionaries make it easier to target specific items using `itemId` as the key 2. **Provide clear feedback**: Show which item is being edited with conditional styling or visibility 3. **Validate input**: Check that required fields are filled before processing 4. **Consider performance**: Large lists with many input components can impact performance; use pagination if needed 5. **Test empty states**: Ensure your Repeater handles empty data gracefully ## Example: Dynamic task list with input This example shows how to create an editable task list where users can update task descriptions. **Interface:** * Button to add new tasks * Repeater bound to `tasks` dictionary * Text Input inside Repeater for editing task names * Button inside Repeater to delete tasks **Repeater configuration:** * **Repeater object**: `@{tasks}` * **Key variable name**: `itemId` * **Value variable name**: `item` **Text Input configuration (inside Repeater):** * **Link variable**: `tasks[itemId].name` * **Placeholder**: "Enter task name" This setup allows each task to maintain its own editable name field. ## Dynamic tabs Repeaters can be used to create tabs dynamically based on your data. Place a **Repeater** inside a **Tab Container**, then add a **Tab** component inside the Repeater. **Example structure:** * Tab Container * Repeater (bound to `@{categories}`) * Tab (with name `@{item.name}`) * Your content here Each item in your data generates a new tab. This is useful for category-based views, multi-entity interfaces, or any scenario where the number of tabs depends on your data. ## Dynamic columns Similarly, you can create dynamic column layouts by placing a **Repeater** inside a **Column Container** with **Column** components inside the Repeater. This allows for responsive, data-driven layouts. ## Working with pagination For large datasets, combine Repeaters with the **Pagination** component to improve performance. The Pagination component provides events (`wf-change-page`, `wf-change-page-size`) that you can handle in your blueprints to update the data displayed in your Repeater. **Example pattern:** 1. Add a Pagination component to your interface 2. Handle the `wf-change-page` event to load the appropriate data slice 3. Update the state variable bound to your Repeater with the paginated data This approach prevents rendering hundreds or thousands of items at once, which can impact performance. ## Additional resources For more on building with Repeaters in Writer Framework, including nested Repeaters, see the examples on this page. ## Fields
Name Type Description Options
Repeater object Object Include a state reference to the dictionary used for repeating the child components. Alternatively, specify a JSON object. \-
Key variable name Text Set the name of the variable that will store the key of the current repeater object entry. \-
Value variable name Text Set the name of the variable that will store the value of the current repeater object entry. \-
# Reuse Component Source: https://dev.writer.com/components/reuse Those components are used to reuse other components. Reused components share the same state and are updated together. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/reuse.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=1905ae27e21b99defffc661180140ab5) ## Fields
Name Type Description Options
Component id Text The id of the component to reuse. \-
# Root Source: https://dev.writer.com/components/root The root component of the application, which serves as the starting point of the component hierarchy. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/root.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=ad1add9fb4d2198426dd7c920bd67acd) ## Fields
Name Type Description Options
App name Text The app name will be shown in the browser's title bar. \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
Button Color - \-
Button shadow Shadow - \-
Accent Color - \-
Padding Padding - \-
Primary text Color - \-
Button text Color - \-
Emptiness Color Page background color \-
Container shadow Shadow - \-
Secondary text Color - \-
Separator Color - \-
Content alignment (V) Align (V) - \-
Content alignment (H) Align (H) - \-
Content width Width Configure content width using CSS units, e.g. 100px, 50%, 10vw, etc. \-
## Events > [accordion] wf-app-open > > Captures the first application load, including page key and route vars. > > ```python theme={null} > def handle_app_open(state): > # The payload is a dictionary with the page key and all the route variables in the URL hash. > # For example, if the current URL is http://localhost:3000/#/animal=duck&colour=yellow > # you will get the following dictionary > # { > # "page_key": "main", > # "route_vars": { > # "animal": "duck", > # "colour": "yellow" > # } > # } > > page_key = payload.get("page_key") > route_vars = payload.get("route_vars") > ``` > [accordion] wf-hashchange > > Capture changes to the URL hash, including page key and route vars. > > ```python theme={null} > def handle_hashchange(state, payload): > # The payload is a dictionary with the page key and all the route variables in the URL hash. > # For example, if the current URL is http://localhost:3000/#main/animal=duck&colour=yellow > # you will get the following dictionary > # { > # "page_key": "main", > # "route_vars": { > # "animal": "duck", > # "colour": "yellow" > # } > # } > > page_key = payload.get("page_key") > route_vars = payload.get("route_vars") > > if not route_vars: > return > > if route_vars.get("animal") == "duck": > state["message"] = "You've navigated to the Duck zone." > else: > state["message"] = "You're not in the Duck zone. > ``` # Section Source: https://dev.writer.com/components/section A container component that divides the layout into sections, with an optional title. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/section.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=e929d071887d63abfe02df5a3e67cf64) ## Fields
Name Type Description Options
Title Text Leave blank to hide. \-
Collapsible Boolean - \-
Start collapsed Boolean Only applied when the component is collapsible. \-
Accent Color - \-
Primary text Color - \-
Secondary text Color - \-
Container background Color - \-
Container shadow Shadow - \-
Separator Color - \-
Button Color - \-
Button text Color - \-
Button shadow Shadow - \-
Padding Padding - \-
Content alignment (H) Align (H) - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Select Input Source: https://dev.writer.com/components/selectinput A user input component that allows users to select a single or multiples value(s) from a searchable list of options. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/selectinput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=2b485ff4fe89672ae95afdc12024423c) ## Overview The **Select Input** component provides a dropdown interface for selecting single or multiple values from a searchable list of options. It offers a clean, accessible way to present multiple choices while maintaining a compact interface. Select inputs are essential for forms and interfaces where users need to choose from predefined options. They provide better user experience than text inputs for categorical data and help ensure data consistency and validation. ## Common use cases * **Form selections**: Choose options in registration and configuration forms * **Category filtering**: Filter content by categories or types with single or multiple selections * **Configuration settings**: Select preferences and settings from predefined options * **Data entry**: Choose from standardized options for consistent data entry ## How it works 1. **Label**: Provide a clear label for the select input field 2. **Options**: Define available choices as key-value pairs in JSON format 3. **Dropdown**: Display options in a searchable dropdown interface 4. **Selection**: Allow users to select one or multiple options from the list 5. **Binding**: Connect to a state variable to store the selected value 6. **Events**: Trigger workflows when selections change The component automatically updates the bound state variable when users make selections, and can trigger events for real-time processing or validation. ## Configuration options ### Basic settings * **Label**: Text label displayed preceding the select input field * **Allow Multi-select**: Toggle to enable selection of multiple options from the dropdown (default: off) * **Options**: Key-value object with available options (must be a JSON string or state reference to a dictionary) * **Placeholder**: Text to display when no options are selected * **Maximum count**: The maximum allowable number of selected options (set to zero for unlimited) - only available when multi-select is enabled ### Binding settings * **Link Variable**: Connect the result of this component to a dynamic variable for use across the agent ### Styling options * **Accent color**: Set the focus and highlight color for the select input * **Primary text color**: Set the main text color for options and labels * **Container background color**: Set the background color of the dropdown container * **Separator color**: Set the border and divider color * **Custom CSS classes**: Apply additional styling with custom CSS classes (separated by spaces) ### Events * **wf-option-change**: Triggered when a single option changes (only available when multi-select is off) - payload contains the selected option * **wf-options-change**: Triggered when multiple options change (only available when multi-select is enabled) - payload contains array of selected options ## Example ### User registration form This example shows how to create a registration form with select inputs. **Interface:** * Text Input components for personal information * Select Input components for preferences * Button component for submission **Select Input configuration:** * **Label**: "Country," "Account Type," "Time Zone" * **Options**: Various country, account type, and timezone options * **Link Variable**: "country," "account," "timezone" ### Multi-select tag management Create a tag management interface for content categorization. **Interface:** * Select Input component with multi-select enabled * Button component for saving **Select Input configuration:** * **Label**: "Content Tags" * **Allow Multi-select**: Enabled * **Options**: JSON object with tag categories * **Placeholder**: "Select tags for your content" * **Link Variable**: "tags" ## Best practices 1. **Clear labeling**: Use descriptive labels that explain the selection purpose and context 2. **Logical ordering**: Arrange options in logical order (alphabetical, numerical, or by frequency of use) 3. **Option clarity**: Use clear, concise option text that users understand without ambiguity 4. **Accessibility**: Ensure select inputs are keyboard navigable and screen reader friendly This component provides a searchable dropdown for selecting one or multiple values. Usage: supply the Options field with a key-value object; open the dropdown and use the search box at the top to filter options by label (and detail, when provided). Configuration: Enable multi-selection via the 'Allow Multi-select' field; set a placeholder and limit selections with 'Maximum count' (applies only to multi-select). Limitations: search is client-side, case-insensitive, and matches label/detail text only (not the option key); no remote/async search; very large option lists are filtered in-memory. ## Fields
Name Type Description Options
Label Text - \-
Allow Multi-select Boolean Select more than one option from the dropdown. \-
Options Key-Value Key-value object with options. Must be a JSON string or a state reference to a dictionary. \-
Placeholder Text Text to show when no options are selected. \-
Maximum count Number The maximum allowable number of selected options. Set to zero for unlimited. \-
Accent Color - \-
Primary text Color - \-
Chip text Color The colour of the text in the chips. \-
Container background Color - \-
Separator Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-option-change > > Sent when the selected option changes. > > ```python theme={null} > def onchange_handler(state, payload): > > # Set the state variable "selected" to the selected option > > state["selected"] = payload > ``` > [accordion] wf-options-change > > Sent when the selected options change. > > ```python theme={null} > def onchange_handler(state, payload): > > # Set the state variable "selected" to the selected option > > state["selected"] = payload > ``` # Separator Source: https://dev.writer.com/components/separator A visual component to create a separation between adjacent elements. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/separator.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=ad529dc521eb92eb9f6301044fa2ef7a) *Separator* components are used to separate layout elements. They can be used in most containers, including *Column container* to separate columns. If the container flows horizontally (like a *Horizontal Stack* or a *Column container*) the *Separator* will be a vertical line. Otherwise, it'll be a horizontal line. ## Fields
Name Type Description Options
Separator Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Sidebar Source: https://dev.writer.com/components/sidebar A container component that organizes its children in a sidebar. Its parent must be a Page component. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/sidebar.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=b1a685c1120bb35a896e70fbcda6bf31) ## Fields
Name Type Description Options
Start collapsed Boolean - \-
Background Color - \-
Accent Color - \-
Primary text Color - \-
Secondary text Color - \-
Container background Color - \-
Container shadow Shadow - \-
Separator Color - \-
Button Color - \-
Button text Color - \-
Button shadow Shadow - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Slider Input Source: https://dev.writer.com/components/sliderinput A user input component that allows users to select numeric values using a slider with optional constraints like min, max, and step. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/sliderinput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=ac02c4d2112cadc7f0c399fbaf107922) ## Fields
Name Type Description Options
Label Text - \-
Minimum value Number - \-
Maximum value Number - \-
Step size Number - \-
Accent Color - \-
Popover color Color - \-
Popover background Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-number-change > > Capture changes to this control. > > ```python theme={null} > > def onchange_handler(state, payload): > > # Set the state variable "new_val" to the new value > > state["new_val"] = payload > ``` # Step Source: https://dev.writer.com/components/step A container component that displays its child components as a step inside a Step container. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/step.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=951225f2bbc297f6ff353dfa346a7cd4) ## Fields
Name Type Description Options
Name Text - \-
Padding Padding - \-
Completed Boolean Use a state reference to dynamically mark this step as complete. \-
Content alignment (H) Align (H) - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Step Container Source: https://dev.writer.com/components/steps A container component for displaying Step components, allowing you to implement a stepped blueprint. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/steps.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=e187a4b54b3d9fb3dee3761d33e157de) ## Fields
Name Type Description Options
Accent Color - \-
Primary text Color - \-
Secondary text Color - \-
Container background Color - \-
Container shadow Shadow - \-
Separator Color - \-
Button Color - \-
Button text Color - \-
Button shadow Shadow - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Switch Input Source: https://dev.writer.com/components/switchinput A user input component with a simple on/off status. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/switchinput.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=a7c8e23a278a0399ace156799dde5567) ## Fields
Name Type Description Options
Label Text - \-
Accent Color - \-
Primary text Color - \-
Separator Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-toggle > > Sent when the switch is toggled. > > ```python theme={null} > def handle_toggle(state, payload): > > # The payload will be a bool > > state["its_on"] = payload > ``` # Tab Source: https://dev.writer.com/components/tab A container component that displays its child components as a tab inside a Tab container. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/tab.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=ae10c4cffa8deaba1aaa42ccdb6fa202) ## Fields
Name Type Description Options
Name Text - \-
Padding Padding - \-
Content alignment (H) Align (H) - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Tab Container Source: https://dev.writer.com/components/tabs A container component for organising and displaying Tab components in a tabbed interface. ![](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/components/tabs.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=4d0cd3f2d5386d72cd6e0f864e879783) ## Fields
Name Type Description Options
Accent Color - \-
Primary text Color - \-
Secondary text Color - \-
Container background Color - \-
Container shadow Shadow - \-
Separator Color - \-
Button Color - \-
Button text Color - \-
Button shadow Shadow - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-tab-change > > Sent when the active tab changes. > > ```python theme={null} > def tab_change_handler(state, payload): > > # The payload contains the name of the newly activated tab > > state["active_tab"] = payload > ``` # Tags Source: https://dev.writer.com/components/tags A component to display coloured tag pills. ![](https://mintcdn.com/writer/dHnl9w_Om9ycQRLE/framework/public/components/tags.png?fit=max\&auto=format\&n=dHnl9w_Om9ycQRLE\&q=85\&s=e063b7fc90bfb6b61b52e86c618888e5) ## Fields
Name Type Description Options
Tags Key-Value Key-value object with tags. Must be a JSON string or a state reference to a dictionary. \-
Reference Color The colour to be used as reference for chroma and luminance, and as the starting point for hue rotation. \-
Seed value Number Choose a different value to reshuffle colours. \-
Rotate hue Boolean If active, rotates the hue depending on the content of the string. If turned off, the reference colour is always used. \-
Primary text Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-tag-click > > Triggered when a tag is clicked. > > ```python theme={null} > def handle_tag_click(state, payload): > state["selected_tag_id"] = payload > ``` # Text Source: https://dev.writer.com/components/text A component to display plain text or formatted text using Markdown syntax. ![](https://mintcdn.com/writer/dHnl9w_Om9ycQRLE/framework/public/components/text.png?fit=max\&auto=format\&n=dHnl9w_Om9ycQRLE\&q=85\&s=a0e34a7cd67c60ef8f982e5bc99dabf5) ## Fields
Name Type Description Options
Text Text Add text directly, or reference state elements with @. \-
Enable markdown Boolean The Markdown output will be sanitised; unsafe elements will be removed. \-
Alignment Text -
  1. Left
  2. Center
  3. Right
Enable copy button Boolean Enable a copy button that lets users to copy the contents in this field to their clipboard \-
Primary text Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-click > > Capture single clicks. > > ```python theme={null} > def click_handler(state): > > # Increment counter when the text is clicked > > state["counter"] += 1 > ``` # Text area Input Source: https://dev.writer.com/components/textareainput A user input component that allows users to enter multi-line text values. ![](https://mintcdn.com/writer/dHnl9w_Om9ycQRLE/framework/public/components/textareainput.png?fit=max\&auto=format\&n=dHnl9w_Om9ycQRLE\&q=85\&s=7d78bb7c819b5751d77d38bff4e6ea8e) ## Overview The **Text area Input** component allows users to enter multi-line text values. It's designed for longer text content like descriptions, comments, reviews, or any content that requires multiple lines. ## Common use cases * **Long-form content**: Collect essays, articles, or detailed descriptions * **User feedback**: Gather reviews, comments, or support requests * **Data entry**: Allow users to paste large amounts of text or data * **Configuration**: Collect complex configuration settings or parameters ## How it works 1. **Multi-line input**: Users can enter text across multiple lines 2. **Manual resizing**: Users can resize the text area by dragging the bottom corner 3. **State binding**: Content automatically saves to the specified state variable 4. **Real-time events**: Triggers events as users type or finish editing 5. **Configurable rows**: Set the initial number of rows to display The component provides a familiar text editing experience with manual resizing for longer content entry. ## Configuration options ### Basic settings * **Label**: Text label displayed above the input field * **Placeholder**: Hint text shown when the field is empty * **Rows**: Number of rows to display (default: `5`) * **Link variable**: The name of the state variable that stores the input value ### Styling options * **Custom CSS classes**: Apply additional styling ### Events * **wf-change**: Triggered as users type (real-time) - payload contains the text area content * **wf-change-finish**: Triggered when users finish editing (on blur) - payload contains the text area content ## Example ### Customer feedback form This example shows how to create a customer feedback form with a text area for detailed comments. **Interface:** * Text Input for customer name * Text area Input for feedback details * Button to submit the form **Text area Input configuration:** * Label: "Your feedback" * Placeholder: "Please share your experience with our product..." * State element: `customer_feedback` * Rows: 4 ![Text area Input configuration](https://mintcdn.com/writer/pM8WhgC5nDcujQ4i/images/agent-builder/components/textareainput-configuration.png?fit=max\&auto=format\&n=pM8WhgC5nDcujQ4i\&q=85\&s=d00e7359cce0d8fefcdf2818f0229bf8) ## Fields
Name Type Description Options
Label Text - \-
Placeholder Text - \-
Rows Number - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Text Input Source: https://dev.writer.com/components/textinput A user input component that allows users to enter single-line text values. ![](https://mintcdn.com/writer/dHnl9w_Om9ycQRLE/framework/public/components/textinput.png?fit=max\&auto=format\&n=dHnl9w_Om9ycQRLE\&q=85\&s=aa0cc5b8fd4e316f7dc7a9f13fb2dbf4) ## Overview The **Text Input** component allows users to enter single-line text values. It's the most basic form of user input and is essential for collecting information from users in your agent. Text inputs automatically bind to state variables, making it easy to capture and use user input in your blueprint workflows. They support various styling options and can be configured for different use cases, including password fields. ## Common use cases * **User information**: Collect names, emails, phone numbers, and other personal data * **Search queries**: Allow users to search through data or content * **Configuration values**: Let users set preferences or parameters * **Form fields**: Collect data as part of larger forms * **Password entry**: Secure input for sensitive information ## How it works 1. **Label**: Provide a clear label for the input field 2. **Placeholder**: Add helpful placeholder text to guide users 3. **Binding**: Connect to a state variable to store the input value 4. **Events**: Trigger workflows when users type or finish editing 5. **Styling**: Customize appearance with colors and CSS classes, and add a password mode for sensitive information The component automatically updates the bound state variable as users type, and can trigger events for real-time processing or validation. ## Configuration options ### Basic settings * **Label**: The field label displayed above the input * **Placeholder**: Hint text shown when the field is empty * **Link variable**: The name of the state variable that stores the input value ### Styling options * **Password mode**: Toggle to hide input for sensitive data (default is disabled) * **Accent color**: Set the focus color for the input field * **Custom CSS classes**: Apply additional styling ### Events * **wf-change**: Triggered as users type (real-time) - payload contains the input value * **wf-change-finish**: Triggered when users finish editing (on blur) - payload contains the input value ## Example ### Search interface This example shows how to create a search interface with a text input. The search query is stored in the `search_query` state variable. For the blueprint workflow, you can access the `search_query` state variable to see the user's query. **Interface:** * Text Input component for the search query * Button component to trigger the search * Results container to display matches **Search text input configuration:** * **Label**: "Search" * **Placeholder**: "Enter search terms..." * **Link variable**: `search_query` ![Text Input configuration](https://mintcdn.com/writer/pM8WhgC5nDcujQ4i/images/agent-builder/components/textinput-configuration.png?fit=max\&auto=format\&n=pM8WhgC5nDcujQ4i\&q=85\&s=bcac6a24540b4f8833d2af0b5d35ad61) ## Best practices 1. **Clear labels**: Use descriptive labels that clearly indicate what information is needed 2. **Helpful placeholders**: Provide examples or guidance in placeholder text 3. **Appropriate validation**: Validate input on both client and server side 4. **Real-time feedback**: Use the `wf-change` event for immediate user feedback 5. **Password security**: Use password mode for sensitive information ## Fields
Name Type Description Options
Label Text - \-
Placeholder Text - \-
Password mode Boolean - \-
Accent Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Time Input Source: https://dev.writer.com/components/timeinput A user input component that allows users to select a time. ![](https://mintcdn.com/writer/dHnl9w_Om9ycQRLE/framework/public/components/timeinput.png?fit=max\&auto=format\&n=dHnl9w_Om9ycQRLE\&q=85\&s=3d11d45afa17bf645a69103e890f74b7) ## Fields
Name Type Description Options
Label Text - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-time-change > > Capture changes to this control. > > ```python theme={null} > > def onchange_handler(state, payload): > > # Set the state variable "new_time" to the new value, provided as a hh:mm string (in 24-hour format that includes leading zeros). > > state["new_time"] = payload > ``` # Timer Source: https://dev.writer.com/components/timer A component that emits an event repeatedly at specified time intervals, enabling time-based refresh. ![](https://mintcdn.com/writer/dHnl9w_Om9ycQRLE/framework/public/components/timer.png?fit=max\&auto=format\&n=dHnl9w_Om9ycQRLE\&q=85\&s=033c952ea8a45dc5e1bfd30ff1d1a6f4) ## Fields
Name Type Description Options
Interval (ms) Number How much time to wait between ticks. A tick is considered finished when its event is handled. \-
Active Boolean Whether the timer should trigger tick events. \-
Accent Color - \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
## Events > [accordion] wf-tick > > Emitted when the timer ticks. > > ```python theme={null} > def handle_timer_tick(state): > > # Increment counter when the timer ticks > > state["counter"] += 1 > ``` # Video Player Source: https://dev.writer.com/components/videoplayer A Video player component that can play various video formats. ![](https://mintcdn.com/writer/dHnl9w_Om9ycQRLE/framework/public/components/videoplayer.png?fit=max\&auto=format\&n=dHnl9w_Om9ycQRLE\&q=85\&s=b7ac2f9091c2198a695401869f95de5d) Use your app's static folder to serve videos directly. For example, `static/my_video.mp4`. Alternatively, you can pack bytes or files in state: `state["vid_b"] = wf.pack_bytes(vid_bytes, "video/mp4")` `state["vid_f"] = wf.pack_file(vid_file, "video/mp4")` Afterwards, you can reference the video using the syntax `@{vid_f}`. ## Fields
Name Type Description Options
Source Text The URL of the video file. Alternatively, you can pass a file via state. \-
Enable controls Boolean Display Video player controls. \-
Autoplay Boolean Autoplay the video when the component is loaded. \-
Loop Boolean Loop the video when it reaches the end. \-
Muted Boolean Mute the video by default. \-
Custom CSS classes Text CSS classes, separated by spaces. You can define classes in custom stylesheets. \-
# Adobe Experience Manager connector Source: https://dev.writer.com/connectors/adobe-experience-manager Connect WRITER Agent to Adobe Experience Manager to manage AEM content, sites, pages, content fragments, assets, launches, and Cloud Manager infrastructure This guide shows you how to configure the [Adobe Experience Manager](https://business.adobe.com/products/experience-manager/adobe-experience-manager.html) connector for WRITER Agent. After setting up this connector, WRITER Agent can manage AEM content, sites, pages, content fragments, assets, and launches with full CRUD operations, and access Cloud Manager programs, environments, pipelines, and repositories in read-only mode. ## Set up the Adobe Experience Manager connector Configure the Adobe Experience Manager connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. > [!NOTE] > > Dynamic client registration means Adobe dynamically creates and manages > OAuth credentials during the setup process. You don't need to create your own > OAuth application or provide a client ID and client secret. ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Adobe Experience Manager connector 3. Enter a profile name and description for the connector 4. Select who has access by default (all users or specific teams) 5. Select **Next** to proceed to connection configuration 6. Select **Dynamic client registration** as the connection type 7. Select which tools to enable for your agents 8. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Adobe Workfront connector Source: https://dev.writer.com/connectors/adobe-workfront Configure the Adobe Workfront connector for WRITER Agent using dynamic client registration or self-managed OAuth, and authorize your Workfront account. This guide shows you how to configure the [Adobe Workfront](https://business.adobe.com/products/workfront.html) connector for WRITER Agent. After setting up this connector, WRITER Agent can search and summarize Workfront projects, tasks, issues, users, and portfolios, read comments and approval workflows, and browse reporting dashboards. ## Set up the Adobe Workfront connector Configure the Adobe Workfront connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The connector supports two authentication options: * **Dynamic client registration (DCR)**: Adobe creates and manages the OAuth credentials during setup. You don't create an OAuth application or provide a client ID and client secret. * **Self-managed OAuth**: Create your own Adobe OAuth application and provide its client ID and client secret. ### Authorize the WRITER redirect URL in Workfront Before users connect with either authentication option, a Workfront administrator must add the WRITER redirect URL to the instance's authorized redirect URLs: 1. In Workfront, select the **Main Menu** icon, select **Setup**, then select **System > Preferences** 2. In the **MCP preferences** area, next to **Authorized redirect URLs**, select **Manage URLs** 3. Enter a **Label** to identify the integration, such as `WRITER Agent`, then enter the WRITER redirect URL: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 4. Select **Add**, then select **Save** For detailed instructions, see Adobe's [Add or remove an authorized redirect URL](https://experienceleague.adobe.com/en/docs/workfront/using/administration-and-setup/manage-wf/security/configure-security-preferences#add-or-remove-an-authorized-redirect-url) guide. ### Create an Adobe OAuth app for self-managed OAuth If you choose self-managed OAuth, ask your Adobe IMS organization administrator to create a user-authentication credential in [Adobe Developer Console](https://developer.adobe.com/console). > [!WARNING] > > Use Adobe Developer Console, not the legacy OAuth2 Applications screen in Workfront. Adobe stopped allowing new legacy apps on November 1, 2026, and existing legacy apps stop working on February 1, 2027. For more information, see Adobe's [Workfront authentication migration guide](https://experienceleague.adobe.com/en/docs/workfront/using/administration-and-setup/configure-integrations/migrate-oauth2-to-developer-console). 1. Create a project, select **Add API**, and choose **Adobe Workfront** under **Experience Cloud** 2. Choose **User Authentication**, then **OAuth Web App**. Don't choose **OAuth Server-to-Server** 3. Configure the redirect fields for your WRITER deployment: * **Default Redirect URI**: `https://app.writer.com/mcp/oauth/callback` * **Redirect URI pattern**: `https://app\.writer\.com/mcp/oauth/callback` * For an EU deployment, use `https://app.eu2.writer.com/mcp/oauth/callback` and the pattern `https://app\.eu2\.writer\.com/mcp/oauth/callback` instead > [!NOTE] > > The redirect URI pattern is a regular expression, so the periods are escaped. Workfront's **Authorized redirect URLs** list takes the plain URL instead. 4. Save the API configuration, then open the credential details and copy the **Client ID** and **Client Secret** for use in [Control Center](#configure-the-connector-in-control-center) 5. On the credential's **Scopes** tab, verify that it includes the scopes WRITER requests: `AdobeID`, `openid`, `profile`, `email`, `additional_info.projectedProductContext`, `read_pc.workfront`, `read_organizations`, and `session` For detailed instructions, see Adobe's [OAuth user credential setup guide](https://developer.adobe.com/developer-console/docs/guides/services/services-add-api-oauth-user-authentication). ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Adobe Workfront connector 3. Enter a profile name and description for the connector 4. Select who has access by default, either all users or specific teams 5. Select **Next** to proceed to connection configuration 6. Select **Dynamic client registration** or [**self-managed**](#create-an-adobe-oauth-app-for-self-managed-oauth) OAuth as the connection type 7. Select which tools to enable for your agents 8. If you use [**self-managed**](#create-an-adobe-oauth-app-for-self-managed-oauth) OAuth, enter your Adobe client ID and client secret 9. Complete the OAuth authorization flow with your Adobe account and select the Workfront instance you want to connect ## Next steps Use these guides to manage connector access and work with connected tools: * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about WRITER's MCP gateway architecture # Asana connector Source: https://dev.writer.com/connectors/asana Connect WRITER Agent to Asana for workspaces, tasks, projects, and workload insights This guide shows you how to configure the [Asana](https://asana.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can access workspaces and team members, create, read, update, and delete tasks and subtasks, and retrieve task details, comments, dependencies, and project structure—enabling AI-driven task creation, project summaries, and workload insights. ## Set up the Asana connector Configure the Asana connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Asana connector supports two authentication options: * **WRITER-managed OAuth** (recommended): Writer provides the OAuth application. No setup required - just authorize access to your Asana workspace. * **Organization-managed OAuth**: Create your own Asana OAuth application for custom branding and control. > [!NOTE] > > Most users should choose WRITER-managed OAuth for faster setup. Only use organization-managed OAuth if you need custom branding or have specific security requirements. ### Create an Asana OAuth application (organization-managed only) If you choose to create a self-managed OAuth application to connect, create an MCP app in the Asana developer console: 1. Navigate to the [Asana developer console](https://app.asana.com/0/developer-console) and sign in 2. Select **Create new app** 3. Enter your app name (for example, "My MCP Client") 4. Select **MCP app** as the app type 5. Select **Create app** 6. In the left sidebar, select **OAuth** and add the Writer redirect URI to Redirect URLs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 7. In the left sidebar, select **Manage distribution**. Under **Distribution method**, choose **Specific workspaces** (and add at least one workspace) or **Any workspace**, then select **Save changes** 8. Navigate to **Basic information** and copy the **Client ID** and **Client secret** for use in [Control Center](#configure-the-connector-in-control-center) For more information, see [Integrating with Asana's MCP Server](https://developers.asana.com/docs/integrating-with-asanas-mcp-server) documentation. ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Asana connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) * **Managed by**: WRITER-managed or self-managed (your own OAuth app) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret (if using self-managed OAuth) 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Atlassian connector Source: https://dev.writer.com/connectors/atlassian Connect WRITER Agent to Atlassian to access Jira and Confluence content and manage work items and pages This guide shows you how to configure the [Atlassian](https://www.atlassian.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can search and read Jira issues and Confluence pages, create and update Jira work items, and create and edit Confluence pages. ## Set up the Atlassian connector Configure the Atlassian connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. > [!NOTE] > > Dynamic client registration means Atlassian dynamically creates and manages > OAuth credentials during the setup process. You don't need to create your own > OAuth application or provide a client ID and client secret. ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Atlassian connector 3. Enter a profile name and description for the connector 4. Select who has access by default (all users or specific teams) 5. Select **Next** to proceed to connection configuration 6. Select **Dynamic client registration** as the connection type 7. Select which tools to enable for your agents 8. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Contentful connector Source: https://dev.writer.com/connectors/contentful Connect WRITER Agent to Contentful to manage content entries, assets, and locales across your Contentful spaces This guide shows you how to configure the [Contentful](https://www.contentful.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can publish and archive content entries, list locales, and perform other content management operations across your Contentful spaces. ## Set up the Contentful connector Configure the Contentful connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. > [!NOTE] > > Dynamic client registration means Contentful dynamically creates and manages > OAuth credentials during the setup process. You don't need to create your own > OAuth application or provide a client ID and client secret. ### Configure the connector in Control Center Create the connector profile and connection settings in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Search for **Contentful** and select the connector 3. On the **Profile** step, enter a profile name and description for the connector, and select who has access by default (all users or specific teams) 4. Select **Next** to continue to the **Type** step 5. Select the connection level: user level (each user authenticates their own account) or org level (shared connection to a single account) 6. Select **Dynamic client registration** as the **Managed by** option 7. Select **Next** to continue to the **Tools** step 8. Select which tools to enable for your agents, then select **Save** ### Authorize the connector in Contentful When the OAuth authorization flow opens Contentful, grant access to your organization, spaces, and tool categories: 1. Log in to your Contentful account when prompted 2. Select **Authorize** to allow the Contentful Remote MCP application to access your content 3. Select the **Organization** where you install Contentful's Remote MCP Server 4. Under **Select spaces and environments**, select the **Space** and **Environment** to grant access to 5. Select **Add row** to grant access to additional spaces or environments 6. Under **Configure Contentful access**, select which tool categories the MCP server can access for the selected space and environment (for example, entries, assets, content types, environments, or AI Actions) 7. Choose read-only or read/write access for each category you enable 8. Expand **Content lifecycle actions** to configure entry-related actions like publishing and archiving 9. Select **I recognize and trust this URL** to confirm the redirect URL, then select **Agree** to authorize the WRITER MCP Client 10. Confirm you see **Connected to Contentful**, then close the tab ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Databricks connector Source: https://dev.writer.com/connectors/databricks Connect WRITER Agent to Databricks using MCP to access SQL, Unity Catalog functions, and Genie spaces This guide shows you how to configure the [Databricks](https://www.databricks.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like querying Databricks SQL, accessing Unity Catalog functions, and interacting with Genie spaces through Databricks' managed MCP servers. > [!NOTE] > > Databricks managed MCP servers are currently in Beta. Workspace administrators control access to this feature through the Databricks **Previews** page. If you don't see MCP servers available in your workspace, navigate to **Settings** → **Previews** and search for "Managed MCP Servers" to enable the feature. This feature is not available for free-tier accounts. ## Set up the Databricks connector Configure the Databricks connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Databricks connector uses OAuth to authenticate with Databricks-managed MCP servers. > [!NOTE] > > The Databricks connector only supports organization-managed OAuth. WRITER-managed OAuth is not available for Databricks. ### Obtain your Databricks MCP server URL Before configuring the connector in Control Center, locate your MCP server endpoint in your Databricks workspace: 1. Log in to your [Databricks workspace](https://accounts.cloud.databricks.com/) 2. Navigate to **AI/ML → Agents → MCP Servers** 3. Select the managed MCP server you want to connect (for example, SQL or Genie) 4. Copy the MCP server endpoint URL for use in [Control Center](#configure-the-connector-in-control-center) The URL format depends on the type of MCP server: | Server type | Example URL format | | - | - | | Vector search | `https:///api/2.0/mcp/vector-search/{catalog}/{schema}` | | DBSQL | `https:///api/2.0/mcp/sql` | | Genie space | `https:///api/2.0/mcp/genie/{genie_space_id}` | | Unity Catalog functions | `https:///api/2.0/mcp/functions/{catalog}/{schema}` | For more details about Databricks managed MCP servers and how to get the IDs for specific server types, see [Databricks MCP documentation](https://docs.databricks.com/aws/en/generative-ai/mcp/managed-mcp). ### Create a Databricks OAuth application Create an OAuth 2.0 application in Databricks: 1. Navigate to the [Databricks Account Console](https://accounts.cloud.databricks.com/) 2. Select **Settings** in the left navigation 3. Select **App connections** 4. Select **Add connection** 5. Enter an application name (for example, "Writer MCP connector") 6. Add the Writer redirect URI: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 7. Select **All APIs** under Access Scopes 8. Ensure **Generate a client secret** is selected 9. Set the access token TTL (for example, 10 minutes) and refresh token TTL (for example, 129600 minutes or 90 days) 10. Select **Create** 11. Copy the client ID and client secret for use in [Control Center](#configure-the-connector-in-control-center) For detailed instructions, see [Databricks OAuth documentation](https://docs.databricks.com/aws/en/generative-ai/mcp/connect-external-services#create-the-databricks-oauth-application). ### Configure the connector in Control Center After creating your Databricks OAuth application: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Databricks connector 3. Select who has access by default (all users or specific teams) 4. Enter your Databricks MCP server endpoint URL as the **URL** 5. Enter your OAuth client ID and client secret ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # FactSet connector Source: https://dev.writer.com/connectors/factset Connect WRITER Agent to FactSet to access financial data, equity fundamentals, and market analytics This guide shows you how to configure the [FactSet](https://www.factset.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like accessing global equity fundamentals, earnings data, financial statements, estimates, and industry analytics. ## Set up the FactSet connector Configure the FactSet connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The FactSet connector requires organization-managed OAuth authentication with private key JWT authentication method. > [!NOTE] > > The FactSet connector only supports organization-managed OAuth. You must create your own FactSet OAuth application. WRITER-managed OAuth is not available for FactSet. ### Create a FactSet OAuth application Create an OAuth 2.0 application in FactSet: 1. Contact FactSet to enable OAuth 2.0 access for your account 2. Configure your OAuth application with FactSet and grant access to the [required OAuth scopes](#required-oauth-scopes) 3. Generate a private key for JWT authentication 4. Add the Writer redirect URI if required by FactSet 5. Note your client ID and authentication credentials For detailed instructions, see [FactSet's OAuth 2.0 documentation](https://developer.factset.com/learn/authentication-oauth2). #### Required OAuth scopes * `api|content/eventsandtranscripts/v2` - Access events and transcripts * `api|content/fundamentals` - Access fundamental financial data * `api|content/estimates` - Access estimates and forecasts > [!NOTE] > > OAuth scopes are fixed per connector and cannot be customized based on enabled tools. When users authorize the FactSet connector, they will grant all the scopes listed above, even if you disable certain tools in Control Center. ### Configure the connector in Control Center After creating your FactSet OAuth application: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the FactSet connector 3. Select who has access by default (all users or specific teams) 4. Select the connection level: User level (each user authenticates their own account) or org level (shared connection to a single account) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID 7. Upload or configure your private key for JWT authentication 8. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Figma connector Source: https://dev.writer.com/connectors/figma Configure the Figma connector for WRITER Agent with WRITER-managed OAuth, or prepare self-managed OAuth with MCP access enabled by your account manager. This guide shows you how to configure the [Figma](https://www.figma.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can access Figma design files, inspect node metadata, capture screenshots, and bridge design-to-code workflows using Code Connect. Choose an OAuth option and authorize your Figma account so your agents can use the connector's enabled tools. ## Set up the Figma connector Configure the Figma connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. Choose one of these authentication options: * **WRITER-managed OAuth**: WRITER provides the OAuth application. Authorize access to your Figma account. * **Self-managed OAuth**: Use your own OAuth application. Contact your account manager to have MCP use enabled before configuring the connector. ### Create a Figma OAuth app for self-managed OAuth If you choose self-managed OAuth, create a Figma app and save its credentials for Control Center. > [!WARNING] > > Ask your account manager to enable MCP use for your OAuth application > before you authorize the connector. 1. Open [My Apps in Figma](https://www.figma.com/developers/apps) 2. Select **Create a new app** in the upper-right corner 3. Name your app and choose the Figma team or organization that owns it 4. Select **Create** 5. Copy the **Client ID** and **Client Secret**, and store both securely. Figma displays the secret only during app creation 6. Select **Done**. Figma saves the app as a draft and opens its configuration screen 7. On the **OAuth credentials** page, add the WRITER redirect URI to **Redirect URLs**: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 8. On the **Publish** page, select whether your app is private or public, then select **Publish** For detailed instructions, see [Figma's app configuration guide](https://developers.figma.com/docs/rest-api/oauth-apps/#configure-an-oauth-app). ### Configure the connector in Control Center After choosing your authentication option, complete these steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Figma connector 3. Select who has access by default, either all users or specific teams 4. Select the connection level and whether OAuth is **WRITER-managed** or [**self-managed**](#create-a-figma-oauth-app-for-self-managed-oauth) 5. Select which tools to enable for your agents 6. If you use [**self-managed**](#create-a-figma-oauth-app-for-self-managed-oauth) OAuth, enter your OAuth client ID and client secret after your account manager enables MCP use 7. Complete the OAuth authorization flow with your Figma account ## Next steps Use these guides to manage connector access and work with connected tools: * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about WRITER's MCP gateway architecture # Gmail connector Source: https://dev.writer.com/connectors/gmail Connect WRITER Agent to Gmail to manage emails, search messages, and automate email workflows This guide shows you how to configure the [Gmail](https://mail.google.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like listing email threads, retrieving messages, searching by filters and labels, drafting emails, and sending messages. ## Set up the Gmail connector Configure the Gmail connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. > [!NOTE] > > The Gmail connector only supports organization-managed OAuth. You must create your own Gmail OAuth application. Writer-managed OAuth is not available for Gmail. > [!NOTE] > > Google OAuth credentials expire after 6 months of inactivity. If the Gmail connector is not used for 6 months, users will need to re-authenticate. ### Create a Google OAuth application Create a new Google OAuth application in the Google Cloud Console: 1. Navigate to the [Google Cloud Console](https://console.cloud.google.com/) 2. Create a new project or select an existing project 3. Enable the Gmail API for your project 4. Configure the OAuth consent screen with your application details 5. Create OAuth 2.0 credentials (Web application type) 6. Add the Writer redirect URI to authorized redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 7. Configure the [required OAuth scopes](#required-oauth-scopes) for your application 8. Copy the client ID and client secret for use in Control Center For detailed instructions, see [Google's OAuth 2.0 documentation](https://support.google.com/cloud/answer/15549257). #### Required OAuth scopes * `https://www.googleapis.com/auth/gmail.labels` - View and manage labels * `https://www.googleapis.com/auth/gmail.send` - Send email on the user's behalf * `https://www.googleapis.com/auth/gmail.readonly` - View email messages and settings * `https://www.googleapis.com/auth/gmail.compose` - Manage drafts and compose emails * `https://www.googleapis.com/auth/gmail.insert` - Add emails to the mailbox * `https://www.googleapis.com/auth/gmail.modify` - Modify email metadata * `https://mail.google.com/` - Full Gmail access > [!NOTE] > > OAuth scopes are fixed per connector and cannot be customized based on enabled tools. When users authorize the Gmail connector, they will grant all the scopes listed above, even if you disable certain tools in Control Center. ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Gmail connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Gong connector Source: https://dev.writer.com/connectors/gong Connect WRITER Agent to Gong to access call transcripts, meeting summaries, and sales analytics This guide shows you how to configure the [Gong](https://www.gong.io/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like retrieving call transcripts, meeting summaries, performance scorecards, engagement metadata, and conversation analytics. ## Set up the Gong connector Configure the Gong connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Gong connector supports API key authentication or OAuth 2.0 authentication (contact Gong to enable OAuth). ### Obtain Gong API credentials For API key authentication: 1. Log in to your Gong account 2. Navigate to Settings > API 3. Create a new API key 4. Copy the API key for use in Control Center 5. Note your Gong tenant URL (for example: `https://yourcompany.api.gong.io`) For detailed instructions, see [Gong's API authentication guide](https://help.gong.io/docs/receive-access-to-the-api). ### Configure the connector in Control Center After obtaining your Gong API credentials: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Gong connector 3. Select who has access by default (all users or specific teams) 4. Select which tools to enable for your agents 5. Enter your API key credentials 6. Enter your Gong tenant URL (for example: `https://yourcompany.api.gong.io`) ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Google BigQuery connector Source: https://dev.writer.com/connectors/google-bigquery Connect WRITER Agent to Google BigQuery to securely query and analyze data in your BigQuery data warehouse This guide shows you how to configure the [Google BigQuery](https://cloud.google.com/bigquery) connector for WRITER Agent. After setting up this connector, WRITER Agent can execute SQL queries, list datasets and tables, and retrieve metadata to surface data insights, answer analytical questions, and generate reports based on your BigQuery data warehouse. ## Set up the Google BigQuery connector Configure the Google BigQuery connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Google BigQuery connector requires organization-managed OAuth authentication. > [!NOTE] > > The Google BigQuery connector only supports organization-managed OAuth. You > must create your own Google Cloud OAuth application. Writer-managed OAuth is > not available for Google BigQuery. > [!NOTE] > > Google OAuth credentials expire after 6 months of inactivity. If the Google > BigQuery connector is not used for 6 months, users will need to > re-authenticate. ### Enable the BigQuery MCP server Before configuring the connector, enable the BigQuery API and MCP server in your Google Cloud project: 1. Navigate to the [Google Cloud Console](https://console.cloud.google.com/) 2. Select your project or [create a new one](https://console.cloud.google.com/projectselector2) 3. [Enable the BigQuery API](https://console.cloud.google.com/apis/library/bigquery.googleapis.com) for your project (enabled by default for new projects) 4. Enable the BigQuery MCP server by running the following command in the [Google Cloud Shell](https://console.cloud.google.com/cloudshell) or your local terminal with the [Google Cloud CLI](https://cloud.google.com/sdk/docs/install) installed: ```bash theme={null} gcloud beta services mcp enable bigquery.googleapis.com \ --project=PROJECT_ID ``` Replace `PROJECT_ID` with your Google Cloud project ID. > [!NOTE] > > After March 17, 2026, the BigQuery remote MCP server is automatically enabled > when you enable BigQuery. For detailed instructions, see [Google's BigQuery MCP server documentation](https://docs.cloud.google.com/bigquery/docs/use-bigquery-mcp). ### Create a Google OAuth application Create a new Google OAuth application in the Google Cloud Console: 1. Navigate to the [Google Cloud Console](https://console.cloud.google.com/) 2. Select the same project where you enabled the BigQuery MCP server 3. Navigate to **APIs & Services** → **Credentials** 4. Configure the OAuth consent screen with your application details 5. Create OAuth 2.0 credentials (Web application type) 6. Add the Writer redirect URI to authorized redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 7. Configure the [required OAuth scopes](#required-oauth-scopes) for your application 8. Copy the client ID and client secret for use in [Control Center](#configure-the-connector-in-control-center) For detailed instructions, see [Google's OAuth 2.0 documentation](https://support.google.com/cloud/answer/15549257). #### Required OAuth scopes * `https://www.googleapis.com/auth/bigquery` - View and manage your data in BigQuery ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Google BigQuery connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools # Google Calendar connector Source: https://dev.writer.com/connectors/google-calendar Connect WRITER Agent to Google Calendar to manage events, schedule meetings, and automate calendar workflows This guide shows you how to configure the [Google Calendar](https://calendar.google.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like reading calendar events, creating new events, updating existing events, and managing calendar schedules. ## Set up the Google Calendar connector Configure the Google Calendar connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Google Calendar connector requires organization-managed OAuth authentication. > [!NOTE] > > The Google Calendar connector only supports organization-managed OAuth. You must create your own Google Calendar OAuth application. Writer-managed OAuth is not available for Google Calendar. > [!NOTE] > > Google OAuth credentials expire after 6 months of inactivity. If the Google Calendar connector is not used for 6 months, users will need to re-authenticate. ### Create a Google OAuth application Create a new Google OAuth application in the Google Cloud Console: 1. Navigate to the [Google Cloud Console](https://console.cloud.google.com/) 2. Create a new project or select an existing project 3. Enable the Google Calendar API for your project 4. Configure the OAuth consent screen with your application details 5. Create OAuth 2.0 credentials (Web application type) 6. Add the Writer redirect URI to authorized redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 7. Configure the [required OAuth scopes](#required-oauth-scopes) for your application 8. Copy the client ID and client secret for use in Control Center For detailed instructions, see [Google's OAuth 2.0 documentation](https://support.google.com/cloud/answer/15549257). #### Required OAuth scopes * `https://www.googleapis.com/auth/calendar` - Full access to calendars * `https://www.googleapis.com/auth/calendar.events` - Manage calendar events ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Google Calendar connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Google Docs connector Source: https://dev.writer.com/connectors/google-docs Connect WRITER Agent to Google Docs to read, edit, and manage documents This guide shows you how to configure the [Google Docs](https://docs.google.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like retrieving document content, searching within documents, editing paragraphs and sections, and inserting new content while maintaining formatting. ## Set up the Google Docs connector Configure the Google Docs connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Google Docs connector requires organization-managed OAuth authentication. > [!NOTE] > > The Google Docs connector only supports organization-managed OAuth. You must create your own Google Docs OAuth application. Writer-managed OAuth is not available for Google Docs. > [!NOTE] > > Google OAuth credentials expire after 6 months of inactivity. If the Google Docs connector is not used for 6 months, users will need to re-authenticate. ### Create a Google OAuth application Create a new Google OAuth application in the Google Cloud Console: 1. Navigate to the [Google Cloud Console](https://console.cloud.google.com/) 2. Create a new project or select an existing project 3. Enable the Google Docs API for your project 4. Configure the OAuth consent screen with your application details 5. Create OAuth 2.0 credentials (Web application type) 6. Add the Writer redirect URI to authorized redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 7. Configure the [required OAuth scopes](#required-oauth-scopes) for your application 8. Copy the client ID and client secret for use in Control Center For detailed instructions, see [Google's OAuth 2.0 documentation](https://support.google.com/cloud/answer/15549257). #### Required OAuth scopes * `https://www.googleapis.com/auth/documents` - Read and write access to Google Docs ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Google Docs connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Google Drive connector Source: https://dev.writer.com/connectors/google-drive Connect WRITER Agent to Google Drive to manage files, folders, and sharing across My Drive and shared drives This guide shows you how to configure the [Google Drive](https://drive.google.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like listing and searching files, inspecting metadata, creating folders, copying or deleting items, exporting Google formats (PDF, DOCX, CSV), and managing sharing on My Drive and shared drives. ## Set up the Google Drive connector Configure the Google Drive connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Google Drive connector requires organization-managed OAuth authentication. > [!NOTE] > > The Google Drive connector only supports organization-managed OAuth. You must create your own Google Drive OAuth application. Writer-managed OAuth is not available for Google Drive. > [!NOTE] > > Google OAuth credentials expire after 6 months of inactivity. If the Google Drive connector is not used for 6 months, users will need to re-authenticate. ### Create a Google OAuth application Create a new Google OAuth application in the Google Cloud Console: 1. Navigate to the [Google Cloud Console](https://console.cloud.google.com/) 2. Create a new project or select an existing project 3. Enable the [Google Drive API](https://console.cloud.google.com/marketplace/product/google/drive.googleapis.com) for your project 4. Configure the OAuth consent screen with your application details 5. Create OAuth 2.0 credentials (Web application type) 6. Add the Writer redirect URI to authorized redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 7. Configure the [required OAuth scopes](#required-oauth-scopes) for your application 8. Copy the client ID and client secret for use in Control Center For detailed instructions, see [Google's OAuth 2.0 documentation](https://support.google.com/cloud/answer/15549257). #### Required OAuth scopes * `https://www.googleapis.com/auth/drive` - Full access to Google Drive files and folders ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Google Drive connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Google Sheets connector Source: https://dev.writer.com/connectors/google-sheets Connect WRITER Agent to Google Sheets to read, update, and analyze spreadsheet data This guide shows you how to configure the [Google Sheets](https://sheets.google.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like reading sheets and ranges, searching data using filters, writing or updating cells and rows, appending data, and performing batch edits. ## Set up the Google Sheets connector Configure the Google Sheets connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Google Sheets connector requires organization-managed OAuth authentication. > [!NOTE] > > The Google Sheets connector only supports organization-managed OAuth. You must create your own Google Sheets OAuth application. Writer-managed OAuth is not available for Google Sheets. > [!NOTE] > > Google OAuth credentials expire after 6 months of inactivity. If the Google Sheets connector is not used for 6 months, users will need to re-authenticate. ### Create a Google OAuth application Create a new Google OAuth application in the Google Cloud Console: 1. Navigate to the [Google Cloud Console](https://console.cloud.google.com/) 2. Create a new project or select an existing project 3. Enable the Google Sheets API for your project 4. Configure the OAuth consent screen with your application details 5. Create OAuth 2.0 credentials (Web application type) 6. Add the Writer redirect URI to authorized redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 7. Configure the [required OAuth scopes](#required-oauth-scopes) for your application 8. Copy the client ID and client secret for use in Control Center For detailed instructions, see [Google's OAuth 2.0 documentation](https://support.google.com/cloud/answer/15549257). #### Required OAuth scopes * `https://www.googleapis.com/auth/spreadsheets` - Read and write access to Google Sheets ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Google Sheets connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # HubSpot connector Source: https://dev.writer.com/connectors/hubspot Connect WRITER Agent to HubSpot to access CRM data, contacts, deals, and pipeline insights This guide shows you how to configure the [HubSpot](https://www.hubspot.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like retrieving and searching CRM records including contacts, companies, deals, tickets, engagements, and notes. > [!NOTE] > > The HubSpot connector provides read-only access to CRM data. It does not support creating or updating records. ## Set up the HubSpot connector Configure the HubSpot connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The HubSpot connector supports two authentication options: * **WRITER-managed OAuth** (recommended): Writer provides the OAuth application. No setup required - just authorize access to your HubSpot account. * **Organization-managed OAuth**: Create your own HubSpot OAuth application for custom branding and control. > [!NOTE] > > Most users should choose WRITER-managed OAuth for faster setup. Only use organization-managed OAuth if you need custom branding or have specific security requirements. ### Create a HubSpot OAuth application (organization-managed only) If you choose to create a self-managed OAuth application to connect, create an OAuth 2.0 application in HubSpot: 1. Navigate to your [HubSpot developer account](https://developers.hubspot.com/) 2. Create a new app or select an existing app 3. Configure OAuth settings with the [required scopes](#required-oauth-scopes) 4. Add the Writer redirect URI to Redirect URLs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 5. Copy the client ID and client secret For detailed instructions, see [HubSpot's OAuth documentation](https://developers.hubspot.com/docs/api/oauth). #### Required OAuth scopes * `oauth` - Base OAuth access * `crm.objects.tickets.read` - Read ticket data * `crm.objects.users.read` - Read user information * `crm.objects.products.read` - Read product catalog * `crm.objects.line_items.read` - Read line item details * `crm.objects.carts.read` - Read shopping cart data * `crm.objects.subscriptions.read` - Read subscription information * `crm.objects.owners.read` - Read object ownership data * `crm.objects.orders.read` - Read order information * `crm.objects.invoices.read` - Read invoice data * `crm.objects.quotes.read` - Read quote information > [!NOTE] > > OAuth scopes are fixed per connector and cannot be customized based on enabled tools. When users authorize the HubSpot connector, they will grant all the scopes listed above, even if you disable certain tools in Control Center. ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the HubSpot connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) * **Managed by**: WRITER-managed or self-managed (your own OAuth app) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret (if using self-managed OAuth) 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Microsoft Calendar connector Source: https://dev.writer.com/connectors/microsoft-calendar Connect WRITER Agent to Microsoft Calendar to manage events and schedules This guide shows you how to configure the [Microsoft Calendar](https://www.microsoft.com/en-us/microsoft-365/outlook/calendar) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like accessing events, calendars, and scheduling information. ## Set up the Microsoft Calendar connector Configure the Microsoft Calendar connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Microsoft Calendar connector supports two authentication options: * **WRITER-managed OAuth** (recommended): Writer provides the OAuth application. No setup required - just authorize access to your Microsoft Calendar. * **Organization-managed OAuth**: Create your own Microsoft OAuth application for custom branding and control. > [!NOTE] > > Most users should choose WRITER-managed OAuth for faster setup. Only use organization-managed OAuth if you need custom branding or have specific security requirements. ### Create a Microsoft OAuth application (organization-managed only) If you choose to create a self-managed OAuth application to connect, first create a new Microsoft OAuth application in Microsoft Entra ID (Azure AD): 1. Navigate to the [Microsoft Entra admin center](https://entra.microsoft.com/) 2. Go to Applications > App registrations 3. Create a new registration 4. Configure authentication with Web platform 5. Add the Writer redirect URI to Redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 6. Add API permissions for the [required Microsoft Graph scopes](#required-oauth-scopes) 7. Create a client secret in Certificates & secrets 8. Copy the application (client) ID and client secret For detailed instructions, see [Microsoft's OAuth 2.0 documentation](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow). #### Required OAuth scopes * `User.Read` - Read user profile information * `Calendars.Read` - Read user calendars * `Calendars.ReadWrite` - Read and write user calendars * `offline_access` - Maintain access to data ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Microsoft Calendar connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) * **Managed by**: WRITER-managed or self-managed (your own OAuth app) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret (if using self-managed OAuth) 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Microsoft OneDrive connector Source: https://dev.writer.com/connectors/microsoft-onedrive Connect WRITER Agent to OneDrive to access and manage files and folders This guide shows you how to configure the [Microsoft OneDrive](https://www.microsoft.com/en-us/microsoft-365/onedrive) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like accessing files and folders stored in OneDrive, reading file content, managing documents, and searching across cloud storage. ## Set up the Microsoft OneDrive connector Configure the Microsoft OneDrive connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Microsoft OneDrive connector supports two authentication options: * **WRITER-managed OAuth** (recommended): Writer provides the OAuth application. No setup required - just authorize access to your OneDrive. * **Organization-managed OAuth**: Create your own Microsoft OAuth application for custom branding and control. > [!NOTE] > > Most users should choose WRITER-managed OAuth for faster setup. Only use organization-managed OAuth if you need custom branding or have specific security requirements. ### Create a Microsoft OAuth application (organization-managed only) If you choose to create a self-managed OAuth application to connect, first create a new Microsoft OAuth application in Microsoft Entra ID (Azure AD): 1. Navigate to the [Microsoft Entra admin center](https://entra.microsoft.com/) 2. Go to Applications > App registrations 3. Create a new registration 4. Configure authentication with Web platform 5. Add the Writer redirect URI to Redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 6. Add API permissions for the [required Microsoft Graph scopes](#required-oauth-scopes) 7. Create a client secret in Certificates & secrets 8. Copy the application (client) ID and client secret For detailed instructions, see [Microsoft's OAuth 2.0 documentation](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow). #### Required OAuth scopes * `Files.ReadWrite` - Read and write user files * `User.Read` - Read user profile information * `offline_access` - Maintain access to data ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Microsoft OneDrive connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) * **Managed by**: WRITER-managed or self-managed (your own OAuth app) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret (if using self-managed OAuth) 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Microsoft Outlook connector Source: https://dev.writer.com/connectors/microsoft-outlook Connect WRITER Agent to Microsoft Outlook to manage emails and communications This guide shows you how to configure the [Microsoft Outlook](https://www.microsoft.com/en-us/microsoft-365/outlook) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like accessing emails, folders, contacts, and mail settings. ## Set up the Microsoft Outlook connector Configure the Microsoft Outlook connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Microsoft Outlook connector supports two authentication options: * **WRITER-managed OAuth** (recommended): Writer provides the OAuth application. No setup required - just authorize access to your Microsoft Outlook. * **Organization-managed OAuth**: Create your own Microsoft OAuth application for custom branding and control. > [!NOTE] > > Most users should choose WRITER-managed OAuth for faster setup. Only use organization-managed OAuth if you need custom branding or have specific security requirements. ### Create a Microsoft OAuth application (organization-managed only) If you choose to create a self-managed OAuth application to connect, first create a new Microsoft OAuth application in Microsoft Entra ID (Azure AD): 1. Navigate to the [Microsoft Entra admin center](https://entra.microsoft.com/) 2. Go to Applications > App registrations 3. Create a new registration 4. Configure authentication with Web platform 5. Add the Writer redirect URI to Redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 6. Add API permissions for the [required Microsoft Graph scopes](#required-oauth-scopes) 7. Create a client secret in Certificates & secrets 8. Copy the application (client) ID and client secret For detailed instructions, see [Microsoft's OAuth 2.0 documentation](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow). #### Required OAuth scopes * `User.Read` - Read user profile information * `Mail.ReadWrite` - Read and write access to user mail * `Mail.Send` - Send mail as the user * `offline_access` - Maintain access to data ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Microsoft Outlook connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) * **Managed by**: WRITER-managed or self-managed (your own OAuth app) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret (if using self-managed OAuth) 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Microsoft SharePoint connector Source: https://dev.writer.com/connectors/microsoft-sharepoint Connect WRITER Agent to SharePoint to access sites, documents, and collaboration content This guide shows you how to configure the [Microsoft SharePoint](https://www.microsoft.com/en-us/microsoft-365/sharepoint) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like accessing SharePoint sites, reading documents and lists, searching content across your organization's SharePoint environment, and managing files stored in document libraries. ## Set up the Microsoft SharePoint connector Configure the Microsoft SharePoint connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Microsoft SharePoint connector supports two authentication options: * **WRITER-managed OAuth** (recommended): Writer provides the OAuth application. No setup required - just authorize access to your SharePoint. * **Organization-managed OAuth**: Create your own Microsoft OAuth application for custom branding and control. > [!NOTE] > > Most users should choose WRITER-managed OAuth for faster setup. Only use organization-managed OAuth if you need custom branding or have specific security requirements. ### Create a Microsoft OAuth application (organization-managed only) If you choose to create a self-managed OAuth application to connect, first create a new Microsoft OAuth application in Microsoft Entra ID (Azure AD): 1. Navigate to the [Microsoft Entra admin center](https://entra.microsoft.com/) 2. Go to Applications > App registrations 3. Create a new registration 4. Configure authentication with Web platform 5. Add the Writer redirect URI to Redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 6. Add API permissions for the [required Microsoft Graph scopes](#required-oauth-scopes) 7. Create a client secret in Certificates & secrets 8. Copy the application (client) ID and client secret For detailed instructions, see [Microsoft's OAuth 2.0 documentation](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow). #### Required OAuth scopes For self-managed OAuth, choose one of the following scope configurations based on the level of access you need: * **Option A — Broad access**: Add the following scopes to grant read and manage access across all site collections: * `Sites.Read.All` - Read items in all site collections * `Sites.Manage.All` - Create, edit, and delete items and lists in all site collections * `Files.ReadWrite.All` - Read and write files the user can access * `offline_access` - Maintain access to data * **Option B — Selected sites only**: Add the following scopes, then have a tenant admin grant `FullControl` on specific sites through the [Microsoft Graph API](https://learn.microsoft.com/en-us/graph/permissions-selected-overview?tabs=http). This avoids granting access to your entire SharePoint environment. * `Sites.Selected` - Access selected site collections * `User.Read` - Read user profile information * `offline_access` - Maintain access to data ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Microsoft SharePoint connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) * **Managed by**: WRITER-managed or self-managed (your own OAuth app) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret (if using self-managed OAuth) 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Microsoft Teams connector Source: https://dev.writer.com/connectors/microsoft-teams Connect WRITER Agent to Microsoft Teams to access channels, messages, and team collaboration This guide shows you how to configure the [Microsoft Teams](https://www.microsoft.com/en-us/microsoft-teams) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like accessing teams, channels, messages, and collaboration settings. ## Set up the Microsoft Teams connector Configure the Microsoft Teams connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Microsoft Teams connector supports two authentication options: * **WRITER-managed OAuth** (recommended): Writer provides the OAuth application. No setup required - just authorize access to your Microsoft Teams. * **Organization-managed OAuth**: Create your own Microsoft OAuth application for custom branding and control. > [!NOTE] > > Most users should choose WRITER-managed OAuth for faster setup. Only use organization-managed OAuth if you need custom branding or have specific security requirements. ### Create a Microsoft OAuth application (organization-managed only) If you choose to create a self-managed OAuth application to connect, first create a new Microsoft OAuth application in Microsoft Entra ID (Azure AD): 1. Navigate to the [Microsoft Entra admin center](https://entra.microsoft.com/) 2. Go to Applications > App registrations 3. Create a new registration 4. Configure authentication with Web platform 5. Add the Writer redirect URI to Redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 6. Add API permissions for the [required Microsoft Graph scopes](#required-oauth-scopes) 7. Create a client secret in Certificates & secrets 8. Copy the application (client) ID and client secret For detailed instructions, see [Microsoft's OAuth 2.0 documentation](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow). #### Required OAuth scopes * `User.Read` - Read user profile information * `Team.ReadBasic.All` - Read basic team information * `Channel.ReadBasic.All` - Read basic channel information * `ChannelMessage.ReadWrite` - Read and write channel messages * `ChannelMessage.Read.All` - Read all channel messages * `ChannelMessage.Send` - Send messages to channels * `ChannelSettings.ReadWrite.All` - Read and write channel settings * `Chat.Create` - Create chats * `Chat.ReadBasic` - Read basic chat information * `Chat.Read` - Read chat messages * `Chat.ReadWrite` - Read and write chat messages * `Chat.ReadWrite.All` - Read and write all chat messages * `ChatMessage.Read` - Read chat messages * `ChatMessage.Send` - Send chat messages * `ChatMember.ReadWrite` - Manage chat members * `Group.Read.All` - Read all groups * `Group.ReadWrite.All` - Read and write all groups * `TeamMember.ReadWrite.All` - Manage team members * `offline_access` - Maintain access to data ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Microsoft Teams connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) * **Managed by**: WRITER-managed or self-managed (your own OAuth app) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret (if using self-managed OAuth) 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # PitchBook connector Source: https://dev.writer.com/connectors/pitchbook Connect WRITER Agent to PitchBook to access private market data and investment analytics This guide shows you how to configure the [PitchBook](https://pitchbook.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like exploring private market data including company profiles, funding rounds, valuations, investor information, and deal histories. ## Set up the PitchBook connector Configure the PitchBook connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The PitchBook connector uses API key authentication. ### Obtain a PitchBook API key Create an API key in PitchBook: 1. Log in to your PitchBook account 2. Navigate to API settings or contact PitchBook support for API access 3. Generate a new API key 4. Copy the API key for use in Control Center For detailed instructions, see [PitchBook's API documentation](https://pitchbook.com/help/PitchBook-api). ### Configure the connector in Control Center After obtaining your PitchBook API key: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the PitchBook connector 3. Select who has access by default (all users or specific teams) 4. Select which tools to enable for your agents 5. Enter your PitchBook API key ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Salesforce connector Source: https://dev.writer.com/connectors/salesforce Connect WRITER Agent to Salesforce to query CRM data, manage records, run reports, and automate workflows This guide shows you how to configure the [Salesforce](https://www.salesforce.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can query and manage CRM records, run reports, execute SOQL/SOSL searches, interact with Chatter, and automate Salesforce workflows. ## Set up the Salesforce connector Configure the Salesforce connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Salesforce connector supports two authentication options: * **WRITER-managed OAuth** (recommended): Writer provides the OAuth application. No setup required—just authorize access to your Salesforce account. * **Organization-managed OAuth**: Create your own Salesforce External Client Application for custom branding and control. > [!NOTE] > > Most users should choose WRITER-managed OAuth for faster setup. Only use organization-managed OAuth if you need custom branding or have specific security requirements. ### Configure Salesforce Before connecting, verify the following in your Salesforce environment: 1. Confirm that the Salesforce user account has API access enabled 2. Verify the user has appropriate permissions for the objects and operations you plan to use 3. Ensure any required Salesforce features (reports, Chatter, Bulk API) are enabled for your org ### Install the Writer app from Salesforce AgentExchange (WRITER-managed only) If you choose WRITER-managed OAuth, install the Writer Salesforce Connector package in your Salesforce org from AgentExchange. A Salesforce admin must complete this step. 1. Go to the [Writer for Sales Personalization](https://appexchange.salesforce.com/appxListingDetail?listingId=68c1909f-4f6e-45cb-a07f-35afbeb421e5) listing on Salesforce AgentExchange 2. Select **Get It Now** ![The Writer for Sales Personalization listing on Salesforce AgentExchange, with the Get It Now button in the left sidebar](https://mintcdn.com/writer/_bLOdxV3ekvpkTVV/images/connectors/salesforce-agentexchange-listing.png?fit=max\&auto=format\&n=_bLOdxV3ekvpkTVV\&q=85\&s=517449b06a3f1c7b9a0f96486aeb9a3f) 3. Select the Salesforce account to install the package into, then select **Install in Production** ![The Install in Production dialog, showing the connected Salesforce account and the Install in Production button](https://mintcdn.com/writer/_bLOdxV3ekvpkTVV/images/connectors/salesforce-install-production.png?fit=max\&auto=format\&n=_bLOdxV3ekvpkTVV\&q=85\&s=8c9afd023a814074bb8886c474f58dde) 4. Review the installation details, select the checkbox to agree to the terms and conditions, then select **Confirm and Install** ![The Confirm Installation Details dialog, showing the package version, subscription, and organization, with the Confirm and Install button](https://mintcdn.com/writer/_bLOdxV3ekvpkTVV/images/connectors/salesforce-confirm-install.png?fit=max\&auto=format\&n=_bLOdxV3ekvpkTVV\&q=85\&s=3fae3a29c0e4418ce7b74cc0a9ebd13b) 5. Log in to Salesforce when prompted to continue the installation 6. Select **Install for All Users**, then select **Install** 7. Wait for the installation to complete, then select **Done** 8. In Salesforce, go to **Setup** > **Installed Packages** and confirm that **Writer Salesforce Connector** appears in the list with a status of **Active** ![The Installed Packages page in Salesforce Setup, showing Writer Salesforce Connector with an Active status](https://mintcdn.com/writer/_bLOdxV3ekvpkTVV/images/connectors/salesforce-installed-packages.png?fit=max\&auto=format\&n=_bLOdxV3ekvpkTVV\&q=85\&s=d66021a926c5ed60cb2a9eb9ab1ff634) ### Create a Salesforce External Client Application (organization-managed only) If you choose to create a self-managed OAuth application to connect, create an External Client Application (ECA) in Salesforce: 1. In Salesforce Setup, search for **External** in Quick Find, select **External Client App Manager**, then select **New External Client App** 2. Complete the required fields in the **Basic Information** section 3. Expand **API (Enable OAuth Settings)** and select **Enable OAuth** 4. Add the Writer redirect URI to the **Callback URL**: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 5. Select the [required OAuth scopes](#required-oauth-scopes) 6. Configure [flow enablement settings](#flow-enablement-settings) 7. Configure [security settings](#security-settings) 8. Select **Create** 9. Go to the app's **Settings** > **OAuth Settings** and copy the **Consumer Key** and **Consumer Secret** For detailed instructions, see [Salesforce's External Client Apps documentation](https://help.salesforce.com/s/articleView?id=xcloud.external_client_apps.htm). #### Required OAuth scopes * `api` - Manage user data via APIs * `refresh_token`, `offline_access` - Perform requests at any time * `openid` - Access unique user identifiers * `sfap_api` - Access the Salesforce API Platform #### Flow enablement settings Under **Flow Enablement**, select the following options: * Enable Client Credentials Flow * Enable Authorization Code and Credentials Flow * Enable Token Exchange Flow * Require secret for Token Exchange Flow #### Security settings In the **Security** section, select the following options: * Require secret for Web Server Flow * Require secret for Refresh Token Flow * Require Proof Key for Code Exchange (PKCE) extension for Supported Authorization Flows * Enable Refresh Token Rotation * Limit Idle Refresh Token Time-to-Live (TTL) to 30 Days * Enforce Refresh Token IP Allowlist ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Salesforce connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) * **Managed by**: WRITER-managed or self-managed (your own OAuth app) 5. Select which tools to enable for your agents 6. On the **Connect** step, enter your **Tenant URL** in the format `{instance URL}/services/data/v62.0`, for example: ``` https://yourcompany.my.salesforce.com/services/data/v62.0 ``` 7. If using self-managed OAuth, also enter your **OAuth client ID** and **client secret** 8. Complete the OAuth authorization flow ## Install on a Salesforce sandbox AgentExchange doesn't support installing packages directly into sandbox orgs. To try the Salesforce connector in a sandbox before deploying to production, install the package directly using a URL in the following format: ``` https://{tenant}--{sandbox name}.sandbox.lightning.force.com/packagingSetupUI/ipLanding.app?apvId=04tal000007CLflAAG ``` For example: ``` https://writer--demo.sandbox.lightning.force.com/packagingSetupUI/ipLanding.app?apvId=04tal000007CLflAAG ``` Then follow the same installation steps as [Install the Writer app from Salesforce AgentExchange](#install-the-writer-app-from-salesforce-agentexchange-writer-managed-only), starting from selecting the account to install the package into. ## FAQ The following questions cover common Salesforce connector setup issues. > [accordion] How do I build my Tenant URL? > > The Tenant URL is your Salesforce My Domain plus the API path `/services/data/v62.0`. Don't use a Lightning app URL (`*.lightning.force.com`). > > 1. In Salesforce, go to **Setup** > **My Domain** and copy the domain, for example `yourcompany.my.salesforce.com` > 2. Add `https://` at the start: `https://yourcompany.my.salesforce.com` > 3. Add `/services/data/v62.0` at the end: `https://yourcompany.my.salesforce.com/services/data/v62.0` > > The completed Tenant URL looks like this: > > ``` > https://yourcompany.my.salesforce.com/services/data/v62.0 > ``` ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Salesforce Marketing Cloud connector Source: https://dev.writer.com/connectors/salesforce-marketing-cloud Set up the Salesforce Marketing Cloud connector for WRITER Agent: create an app, configure the tenant URL, and authorize with Dynamic Client Registration. This guide shows you how to configure the Salesforce Marketing Cloud connector for WRITER Agent. After setting up this connector, WRITER Agent can work with content, contacts, data extensions, journeys, and automations within the permission scopes granted to your installed package. Create an app in Marketing Cloud Engagement, then enter your tenant URL in Control Center and authorize the connection. ## Prepare your Marketing Cloud app Before you register the connector with [**Dynamic Client Registration (DCR)**](/home/mcp-gateway#set-up-oauth), create an installed package in Marketing Cloud Engagement to get the client ID and tenant ID for the MCP server URL. 1. In Marketing Cloud Engagement Setup, go to **Apps**, then select **Installed Packages** 2. Select **New**, enter a name for the package, then save your changes 3. On the package's detail page, select **Add Component** 4. For the component type, select **API Integration**, then select **Next** 5. For the integration type, select **Public App**, then select **Next** 6. In the **Redirect URIs** section, enter `https://salesforce.com` as a temporary placeholder. You replace this value in a later step 7. In the **Scope** section, select only the permission scopes the connector needs for the tasks you assign your agents. For example, to let agents create and modify data extensions, select the **Data Extensions** read and write scopes 8. Save the component, then note the **Client ID** (a 24-character alphanumeric string) and the **Tenant ID** on the package's detail page. The tenant ID is the part of your Authentication Base URI before `.auth.marketingcloudapis.com`. For example, if your Authentication Base URI is `https://mcphchq9d5b8mlzeyc2v1example.auth.marketingcloudapis.com/`, your tenant ID is `mcphchq9d5b8mlzeyc2v1example` 9. In the **API Integration** section, select **Edit**, then replace the placeholder redirect URI with your regional callback URL, substituting your tenant ID and client ID: * US: `https://mai-mce-mcp-cdp1.sfdc-yfeipo.svc.sfdcfc.net/t/{tenantId}/c/{clientId}/api/mcp/oauth/callback` * EU: `https://mai-mce-mcp-cdp1.sfdc-yzvdd4.svc.sfdcfc.net/t/{tenantId}/c/{clientId}/api/mcp/oauth/callback` 10. Select the region closest to you. The region only affects connection latency; Salesforce's MCP servers don't store any data they access For more information, see Salesforce's [MCP server setup instructions](https://developer.salesforce.com/docs/marketing/mce-mcp/guide/mce-mcp-setup.html#create-the-package). ### Get your tenant URL Use the regional MCP server URL from Salesforce's setup guide as the connector's **Tenant URL**. Replace the tenant and client placeholders with your package's values. For the US server, use: ```text theme={null} https://mai-mce-mcp-cdp1.sfdc-yfeipo.svc.sfdcfc.net/t/{tenantId}/c/{clientId}/api/mcp ``` For the EU server, use: ```text theme={null} https://mai-mce-mcp-cdp1.sfdc-yzvdd4.svc.sfdcfc.net/t/{tenantId}/c/{clientId}/api/mcp ``` Use the same region for the app's callback URL and this tenant URL. ## Configure the connector in Control Center After completing the Salesforce app setup, configure the connector in [Control Center](https://app.writer.com/controlcenter): > [!NOTE] > > Dynamic client registration means WRITER Agent dynamically creates and > manages OAuth credentials when you authorize the connection. You still > [create a Marketing Cloud package](#prepare-your-marketing-cloud-app) to > get a client ID and tenant ID for the MCP server URL, but you don't > provide a separate OAuth client secret. 1. Navigate to **Integrations > Connectors** 2. Select the Salesforce Marketing Cloud connector 3. Select who has access by default, either all users or specific teams 4. Select the connection level, select **Dynamic client registration** as the **Managed by** option, and select which tools to enable for your agents 5. Paste the [regional MCP server URL](#get-your-tenant-url) into **Tenant URL** 6. Complete the OAuth authorization flow for your Marketing Cloud account ## Next steps Use these guides to manage connector access and work with connected tools: * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about WRITER's MCP gateway architecture # Semrush connector Source: https://dev.writer.com/connectors/semrush Connect WRITER Agent to Semrush to access SEO, keyword, traffic, and competitive research data This guide shows you how to configure the [Semrush](https://www.semrush.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can access Semrush data through the [Semrush MCP server](https://www.semrush.com/blog/what-is-mcp-connector/), including keyword research, domain analytics, backlink data, traffic analytics, and competitive insights. ## Set up the Semrush connector Configure the Semrush connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. > [!NOTE] > > Dynamic client registration means Semrush dynamically creates and manages > OAuth credentials during the setup process. You don't need to create your own > OAuth application or provide a client ID and client secret. ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Semrush connector 3. Enter a profile name and description for the connector 4. Select who has access by default (all users or specific teams) 5. Select **Next** to proceed to connection configuration 6. Select **Dynamic client registration** as the connection type 7. Select which tools to enable for your agents 8. Complete the OAuth authorization flow After configuration, end users authenticate with their own Semrush account through WRITER Agent the first time they use the connector. ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Slack connector Source: https://dev.writer.com/connectors/slack Connect WRITER Agent to Slack to search messages, manage channels, and automate team communication This guide shows you how to configure the [Slack](https://slack.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can perform operations like searching messages and files, reading conversations, managing channels, viewing user profiles, and sending messages to Slack workspaces. > [!WARNING] > > Enroll in [Slack's MCP beta program](https://docs.slack.dev/ai/mcp-server/) to > use this connector. Contact your Slack partner manager to request access. ## Set up the Slack connector Configure the Slack connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Slack connector supports two authentication options: * **WRITER-managed OAuth** (recommended): Writer provides the OAuth application. No setup required - just authorize access to your Slack workspace. * **Organization-managed OAuth**: Create your own Slack OAuth application for custom branding and control. > [!NOTE] > > Most users should choose WRITER-managed OAuth for faster setup. Only use > organization-managed OAuth if you need custom branding or have specific > security requirements. ### Create a Slack OAuth application (organization-managed only) Create an OAuth 2.0 application in Slack: 1. Navigate to the [Slack API Apps page](https://api.slack.com/apps) 2. Create a new app (select "From scratch") 3. Navigate to **OAuth & Permissions** in the sidebar 4. Under **Scopes**, locate the **User Token Scopes** section (not Bot Token Scopes) and add the [required scopes](#required-oauth-scopes) 5. Add the Writer redirect URI to Redirect URLs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 6. Under **Advanced token security via token rotation**, enable **Token Rotation** 7. Navigate to **Basic Information** 8. Copy the client ID and client secret for use in [Control Center](#configure-the-connector-in-control-center) For detailed instructions, see [Slack's OAuth documentation](https://api.slack.com/authentication/oauth-v2). #### Required OAuth scopes * `search:read.public` - Search public channel content * `search:read.private` - Search private channel content * `search:read.mpim` - Search multi-party direct messages * `search:read.im` - Search direct messages * `search:read.files` - Search files * `search:read.users` - Search user information * `chat:write` - Send messages as the user * `channels:history` - View messages in public channels * `mpim:history` - View messages in multi-party direct messages * `im:history` - View messages in direct messages * `canvases:read` - View Canvas documents * `canvases:write` - Create and edit Canvas documents * `users:read` - View users in the workspace * `users:read.email` - View email addresses of users > [!NOTE] > > OAuth scopes are fixed per connector and cannot be customized based on enabled > tools. When users authorize the Slack connector, they will grant all the > scopes listed above, even if you disable certain tools in Control Center. ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Slack connector 3. Select who has access by default (all users or specific teams) 4. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (shared connection to a single account) * **Managed by**: WRITER-managed or self-managed (your own OAuth app) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret (if using self-managed OAuth) 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Snowflake connector Source: https://dev.writer.com/connectors/snowflake Connect WRITER Agent to Snowflake to access SQL analytics, Cortex tools, object metadata, and semantic views This guide shows you how to configure the [Snowflake](https://www.snowflake.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can translate natural-language queries into Snowflake calls across Cortex tools (Analyst, Search, Agent), SQL operations, object management, and Semantic Manager functions for querying semantic views, dimensions, and metrics. > [!WARNING] > > The Snowflake connector uses Snowflake's native role-based permissions. Users have the same permissions in Writer that they have in Snowflake. For example, if a user's Snowflake role allows write operations like `CREATE TABLE`, `INSERT`, `UPDATE`, or `DELETE`, they can perform those same operations through Writer. ## Set up the Snowflake connector Configure the Snowflake connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Snowflake connector requires organization-managed OAuth authentication. > [!NOTE] > > The Snowflake connector only supports organization-managed OAuth. You must create an MCP Server and configure OAuth in your Snowflake account. WRITER-managed OAuth is not available for Snowflake. ### Create a Snowflake MCP Server Set up an MCP Server and OAuth in Snowflake: 1. In the [Snowflake web interface](https://app.snowflake.com/), open a SQL worksheet and set the database and schema context where the MCP Server should live 2. Create the MCP Server: ```sql theme={null} CREATE MCP SERVER FROM SPECIFICATION $$ tools: - name: "sql_exec_tool" type: "SYSTEM_EXECUTE_SQL" title: "SQL Execution Tool" description: "Execute SQL queries against the connected Snowflake database" - name: "analyst_tool" type: "CORTEX_ANALYST_MESSAGE" title: "Cortex Analyst Tool" identifier: ".." description: "Query data using natural language through Cortex Analyst" - name: "search_tool" type: "CORTEX_SEARCH_SERVICE_QUERY" title: "Cortex Search Tool" identifier: ".." description: "Search unstructured data using Cortex Search" $$; ``` Snowflake currently supports the following MCP tool types: * `SYSTEM_EXECUTE_SQL`: Execute SQL queries against Snowflake * `CORTEX_ANALYST_MESSAGE`: Query data using natural language through semantic views * `CORTEX_SEARCH_SERVICE_QUERY`: Search unstructured data using Cortex Search * `CORTEX_AGENT_RUN`: Invoke a Cortex Agent * `GENERIC`: Call custom user-defined functions or stored procedures 3. Grant the [required Snowflake privileges](https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-agents-mcp#access-control) based on the MCP tools you exposed in step 2: ```sql theme={null} -- Allow the role to access the MCP Server GRANT USAGE ON MCP SERVER TO ROLE ; -- Required for SYSTEM_EXECUTE_SQL GRANT USAGE ON WAREHOUSE TO ROLE ; GRANT USAGE ON DATABASE TO ROLE ; GRANT USAGE ON SCHEMA . TO ROLE ; GRANT SELECT ON ALL TABLES IN SCHEMA . TO ROLE ; -- Required only if you expose Cortex tools -- Cortex Analyst (semantic views) GRANT SELECT ON SEMANTIC VIEW .. TO ROLE ; -- Cortex Search GRANT USAGE ON CORTEX SEARCH SERVICE .. TO ROLE ; ``` 4. Create the [security integration](https://docs.snowflake.com/sql-reference/sql/create-security-integration-oauth-snowflake) with the Writer redirect URI and refresh token support: ```sql theme={null} CREATE OR REPLACE SECURITY INTEGRATION TYPE = OAUTH OAUTH_CLIENT = CUSTOM ENABLED = TRUE OAUTH_CLIENT_TYPE = 'CONFIDENTIAL' OAUTH_REDIRECT_URI = 'https://app.writer.com/mcp/oauth/callback' OAUTH_ISSUE_REFRESH_TOKENS = TRUE; ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 5. Retrieve and copy your **client ID** and **client secret** for use in [Control Center](#configure-the-connector-in-control-center): ```sql theme={null} SELECT SYSTEM$SHOW_OAUTH_CLIENT_SECRETS(''); ``` 6. Note your **Snowflake MCP Server URL**, which combines your tenant URL and MCP Server path for use in [Control Center](#configure-the-connector-in-control-center): ``` https://.snowflakecomputing.com/api/v2/databases//schemas//mcp-servers/ ``` For detailed instructions, see [Snowflake's managed MCP server guide](https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-agents-mcp). ### Configure the connector in Control Center After creating your Snowflake MCP Server and OAuth integration: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Snowflake connector 3. Select who has access by default (all users or specific teams) 4. Enter your Snowflake tenant URL (MCP Server URL), OAuth client ID, and client secret 5. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture * [Snowflake-managed MCP server](https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-agents-mcp): Learn about creating and configuring MCP servers in Snowflake # Webflow connector Source: https://dev.writer.com/connectors/webflow Connect WRITER Agent to Webflow to manage sites, pages, and CMS content This guide shows you how to configure the [Webflow](https://webflow.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can access your Webflow sites, pages, and CMS collections—enabling AI-driven content creation, updates, and site management. ## Set up the Webflow connector Configure the Webflow connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. > [!NOTE] > > The Webflow connector only supports organization-managed OAuth. You must create your own Webflow OAuth application. Writer-managed OAuth is not available for Webflow. ### Create a Webflow OAuth application Create an OAuth application in the Webflow workspace settings: 1. Sign in to [Webflow](https://webflow.com/) and navigate to your workspace 2. Go to **Workspace settings** > **Apps & integrations** 3. Select the **Develop** tab and select **Create new app** 4. Enter your app name (for example, "Writer MCP Client") and a description 5. Add the Writer redirect URI to **Redirect URIs**: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 6. Under **Scopes**, select the permissions your agents need (for example, `sites:read`, `pages:read`, `pages:write`, `cms:read`, `cms:write`) 7. Select **Create app** 8. Copy the **Client ID** and **Client secret** for use in [Control Center](#configure-the-connector-in-control-center) For more information, see [Webflow's OAuth documentation](https://developers.webflow.com/data/reference/oauth-app). ### Configure the connector in Control Center After creating your Webflow OAuth application: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select the Webflow connector 3. Select who has access by default (all users or specific teams) 4. Select the connection level: user level (each user authenticates their own account) or org level (shared connection to a single account) 5. Select which tools to enable for your agents 6. Enter your OAuth client ID and client secret 7. Complete the OAuth authorization flow ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Wrike connector Source: https://dev.writer.com/connectors/wrike Connect WRITER Agent to Wrike to manage tasks, spaces, contacts, and comments across your Wrike account This guide shows you how to configure the [Wrike](https://www.wrike.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can retrieve tasks, spaces, contacts, and task comments to help manage your Wrike projects. ## Set up the Wrike connector Configure the Wrike connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The Wrike connector requires organization-managed OAuth—you must create your own Wrike OAuth application to connect. ### Create a Wrike OAuth application Create an OAuth 2.0 app in Wrike: 1. Go to your Wrike profile, select **Apps & Integrations**, then go to the **API** tab 2. Create a new app and enter an **App name** and **App description** 3. Add the Writer redirect URI to the app's redirect URLs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 4. Create the app 5. Copy the **OAuth Client ID** and **Secret key**—you'll need these when connecting the connector in [Control Center](#configure-the-connector-in-control-center) For detailed instructions, see [Wrike's OAuth 2.0 documentation](https://developers.wrike.com/docs/oauth-20-authorization#initial-setup). ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter), search for **Wrike MCP**, and select the connector 2. Select who has access by default (all teams or specific teams) 3. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (one OAuth connection shared across your organization) * **Managed by**: Self managed (your own OAuth app) 4. Select which tools can be used by default 5. Confirm the redirect URL matches the one you added to your Wrike OAuth app, then enter your OAuth client ID and client secret 6. Complete the OAuth authorization flow to connect to Wrike ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # ZoomInfo connector Source: https://dev.writer.com/connectors/zoominfo Connect WRITER Agent to ZoomInfo to research companies and contacts, and access intent and signal data This guide shows you how to configure the [ZoomInfo](https://www.zoominfo.com/) connector for WRITER Agent. After setting up this connector, WRITER Agent can look up reference data, enrich company signals, and access intent data to support your go-to-market research. ## Set up the ZoomInfo connector Configure the ZoomInfo connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The ZoomInfo connector requires organization-managed OAuth—you must create your own MCP app in the ZoomInfo Developer Portal to connect. > [!NOTE] > > Creating an MCP app requires a DevPortal subscription, assigned by your ZoomInfo admin. ### Create a ZoomInfo MCP app Create an MCP app in the ZoomInfo Developer Portal: 1. Go to the [ZoomInfo Developer Portal](https://developer.zoominfo.com/) and sign in, or open the **API/MCP** tab in the left navigation of the ZoomInfo app 2. Select **Create App** 3. Enter an app name (this name appears on the consent screen users see when they sign in) 4. Select **MCP App** as the app type—this automatically assigns the required data scopes, so no manual scope selection is needed 5. Add the Writer redirect URI to the app's redirect URIs: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 6. Select **Create** 7. Open the app and copy the **Client ID** and **Client Secret**—you'll need these when connecting the connector in [Control Center](#configure-the-connector-in-control-center) ### Configure the connector in Control Center Complete the following steps in Control Center: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter), search for **ZoomInfo**, and select the connector 2. Select who has access by default (all teams or specific teams) 3. Select the connection type: * **Level**: User level (each user authenticates their own account) or org level (one OAuth connection shared across your organization) * **Managed by**: Self managed (your own OAuth app) 4. Select which tools can be used by default 5. Confirm the redirect URL matches the one you added to your ZoomInfo MCP app, then enter your OAuth client ID and client secret 6. Complete the OAuth authorization flow to connect to ZoomInfo ## Next steps * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable connectors in Control Center * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Writer AI module Source: https://dev.writer.com/framework/ai-module This module leverages the [Writer Python SDK](https://pypi.org/project/writer-sdk/) to enable applications to interact with large language models (LLMs) in chat or text completion formats. It provides tools to manage conversation states and to dynamically interact with LLMs using both synchronous and asynchronous methods. ## Getting your API key To utilize the Writer AI module, you'll need to configure the `WRITER_API_KEY` environment variable with an API key obtained from Control Center. Here is a detailed [guide](/home/quickstart) to setup up this key. Once you have your API key, set it as an environment variable on your system: ```bash For macOS and Linux theme={null} export WRITER_API_KEY=your_api_key_here ``` ```bash For Windows theme={null} set WRITER_API_KEY=your_api_key_here ``` You can manage your environment variables using methods that best suit your setup, such as employing tools like [python-dotenv](https://pypi.org/project/python-dotenv/). ## Chat completion with the Conversation class The `Conversation` class manages LLM communications within a chat framework, storing the conversation history and handling the interactions. ```python theme={null} import writer as wf import writer.ai def handle_simple_message(state, payload): # Update the conversation state by appending the incoming user message. state["conversation"] += payload # Stream the complete response from the AI model in chunks. for chunk in state["conversation"].stream_complete(): # Append each chunk of the model's response to the ongoing conversation state. state["conversation"] += chunk # Initialize the application state with a new Conversation object. initial_state = wf.init_state({ "conversation": writer.ai.Conversation(), }) ``` ### Initializing a conversation A `Conversation` can be initialized with either a system prompt or a list of previous messages. It can also accept a default configuration dictionary that sets parameters for all interactions. ```python theme={null} # Initialize with a system prompt for a Financial Analyst specializing in balance sheets conversation = Conversation("You assist clients with analyzing and understanding their balance sheets") # Initialize with a history of messages related to balance sheet queries history = [ {"role": "user", "content": "Can you explain the liabilities section?"}, {"role": "assistant", "content": "Certainly! Liabilities are legally binding obligations payable to another entity."} ] conversation = Conversation(history) # Initialize with a configuration suitable for financial analysis discussions config = {'max_tokens': 200, 'temperature': 0.5} conversation = Conversation("You provide detailed insights into balance sheet components", config=config) ``` ### Adding messages to conversation Messages can be added to a `Conversation` instance using the `+` operator or the `add` method. ```python theme={null} # Using the `+` operator to add a balance sheet-related query conversation += {"role": "user", "content": "Can you break down the assets section of the balance sheet?"} # Using the `add` method to add a balance sheet-related query conversation.add(role="user", content="How should I interpret the equity section?") ``` ### Completing and streaming Conversations The `complete` and `stream_complete` methods facilitate interaction with the LLM based on the accumulated messages and configuration. These methods execute calls to generate responses and return them in the form of a message object, but do not alter the conversation's `messages` list, allowing you to validate or modify the output before deciding to add it to the history. ```python complete theme={null} # Using `complete` to get a single response response = conversation.complete() print("LLM Response:", response) ``` ```python stream_complete theme={null} # Using `stream_complete` to get streamed responses for chunk in conversation.stream_complete(): print("Streamed Message:", chunk) # Manually adding to the conversation conversation += chunk ``` Instance-wide configuration parameters can be complemented or overriden on individual call's level, if a `config` dictionary is provided to the method: ```python theme={null} # Overriding configuration for a specific call response = conversation.complete(config={'max_tokens': 200, 'temperature': 0.5}) ``` ### Using Graphs with Conversation A `Graph` is a collection of files meant to provide their contents to the LLM during conversations. Framework allows you to create, retrieve, update, and delete graphs, as well as manage the files within them. #### Creating and Managing Graphs To create and manipulate graphs, use the following methods: ```python theme={null} from writer.ai import create_graph, retrieve_graph, list_graphs, delete_graph # Create a new graph graph = create_graph(name="Financial Data", description="Quarterly reports") # Retrieve an existing graph by ID graph = retrieve_graph("d90a632b-5c1f-42b8-8748-5b7f769d9a36") # Update a graph graph.update(name="Updated Financial Data", description="Updated description") # Retrieve a list of created graphs graphs = list_graphs() for graph in graphs: # Delete a graph delete_graph(graph) ``` #### Adding and Removing Files from Graphs You can upload files, associate them with graphs, and download or remove them. ```python theme={null} from writer.ai import upload_file # Upload a file file = upload_file(data=b"file content", type="application/pdf", name="Report.pdf") # Add the file to a graph graph.add_file(file) # Remove the file from the graph graph.remove_file(file) ``` #### Applying Graphs to Conversation completion You can utilize graphs within conversations. For instance, you may want to provide the LLM access to a collection of files during an ongoing conversation to query or analyze the file content. When passing a graph to the conversation, the LLM can query the graph to retrieve relevant data. ```python theme={null} # Retrieve a graph graph = retrieve_graph("d90a632b-5c1f-42b8-8748-5b7f769d9a36") # Pass the graph to the conversation for completion response = conversation.complete(tools=graph) ``` Alternatively, you can define a graph using JSON: ```python theme={null} tool = { "type": "graph", "graph_ids": ["d90a632b-5c1f-42b8-8748-5b7f769d9a36"] } response = conversation.complete(tools=tool) ``` ### Using Function Calls with Conversations > [!WARNING] > > Function tools are only available with `palmyra-x4` and `palmyra-x5` models. Framework allows you to register Python functions that can be called automatically during conversations. When the LLM determines a need for specific information or processing, it issues a request to use the local code (your function), and Framework handles that request automatically. #### Defining Function Tools Function tools are defined using either a Python class or a JSON configuration. ```python theme={null} from writer.ai import create_function_tool # Define a function tool with Python callable def calculate_interest(principal: float, rate: float, time: float): return principal * rate * time tool = create_function_tool( name="calculate_interest", callable=calculate_interest, parameters={ "principal": {"type": "float", "description": "Loan principal"}, "rate": {"type": "float", "description": "Interest rate"}, "time": {"type": "float", "description": "Time in years"} } ) response = conversation.complete(tools=tool) ``` Alternatively, you can define a function tool in JSON format, but the callable function must still be passed: ```python theme={null} tool = { "type": "function", "name": "calculate_interest", "callable": calculate_interest, "parameters": { "principal": {"type": "float", "description": "Loan principal"}, "rate": {"type": "float", "description": "Interest rate"}, "time": {"type": "float", "description": "Time in years"} } } response = conversation.complete(tools=tool) ``` Function tools require the following properties: * **`name: str`**: A string that defines how the function is referenced by the LLM. It should describe the function’s purpose. * **`callable: Callable`**: A Python function that will be called automatically when needed by the LLM. * **`parameters: dict`**: A dictionary that specifies what input the function expects. The keys should match the function’s parameter names, and each parameter should have a `type`, and an optional `description`.\ Supported types are: `string`, `number`, `integer`, `float`, `boolean`, `array`, `object` and `null`. #### Automated Function Calling When a conversation involves a tool (either a graph or a function), Framework automatically handles the requests from LLM to use the tools during interactions. If the tool needs multiple steps (for example, querying data and processing it), Framework will handle those steps recursively, calling functions as needed until the final result is returned. By default, to prevent endless recursion, Framework will only handle 5 consecutive tool calls. You can expand it in case it doesn't suit your case – both `complete()` and `stream_complete()` accept a `max_tool_depth` parameter, which configures the maximum allowed recursion depth: ```python theme={null} response = conversation.complete(tools=tool, max_tool_depth=7) ``` ### Providing a Tool or a List of Tools You can pass either a single tool or a list of tools to the `complete()` or `stream_complete()` methods. The tools can be a combination of FunctionTool, Graph, or JSON-defined tools. ```python theme={null} from writer.ai import create_function_tool, retrieve_graph # Define a function tool tool1 = create_function_tool( name="get_data", callable=lambda x: f"Data for {x}", parameters={"x": {"type": "string", "description": "Input value"}} ) # Retrieve a graph graph = retrieve_graph("d90a632b-5c1f-42b8-8748-5b7f769d9a36") # Provide both tools in a list response = conversation.complete(tools=[tool1, graph]) ``` ## Text generation without a conversation state ### Text generation against a string prompt `complete` and `stream_complete` methods are designed for one-off text generation without the need to manage a conversation state. They return the model's response as a string. Each function accepts a `config` dictionary allowing call-specific configurations. ```python complete theme={null} # Using `complete` for a single completion text_response = complete("Explore the benefits of AI.", config={'temperature': 0.3}) print("Completion:", text_response) ``` ```python stream_complete theme={null} # Using `stream_complete` for streamed text completions for text_chunk in stream_complete("Explore the benefits of AI.", config={'temperature': 0.3}): print("Streamed Text:", text_chunk) ``` ### Text generation against graphs The `ask` and `stream_ask` methods allow you to query one or more graphs to generate responses from the information stored within them. #### Two approaches to questioning graphs There are two ways to query graphs, depending on your needs: 1. **Graph-Level Methods** (`Graph.ask`, `Graph.stream_ask`): Used when working with a single graph instance. These methods are tied directly to the Graph object, encapsulating operations within that instance. 2. **Module-Level Methods** (`writer.ai.ask`, `writer.ai.stream_ask`): Designed for querying multiple graphs simultaneously. These methods operate on a broader scale, allowing mixed inputs of graph objects and IDs. > [!NOTE] > > • Use graph-level methods when working with a single graph instance. > • Use module-level methods when querying multiple graphs or when graph IDs are your primary input. #### Parameters Both methods include: • `question: str`: The main query for the LLM. • *Optional* `subqueries: bool` (default: `False`): Allows the LLM to generate additional questions during response preparation for more detailed answers. Enabling this might increase response time. Method-level methods require: • `graphs_or_graph_ids: list[Graph | str]`: A list of graphs to use for the question. You can pass `Graph` objects directly into the list, use graph IDs in string form, or a mix of both. #### Graph-level methods The graph-level methods, `Graph.ask` and `Graph.stream_ask`, are designed for interacting with a single graph. By calling these methods on a specific `Graph` instance, you can easily pose questions and retrieve answers tailored to that graph’s content. ```python ask theme={null} # Retrieve a specific graph graph = retrieve_graph("f47ac10b-58cc-4372-a567-0e02b2c3d479") # Pose a question to the graph and get a complete response response = graph.ask("What are the benefits of renewable energy?") print(response) ``` ```python stream_ask theme={null} # Retrieve a specific graph graph = retrieve_graph("f47ac10b-58cc-4372-a567-0e02b2c3d479") # Pose a question and stream the response in chunks for chunk in graph.stream_ask("Explain the history of solar energy."): print(chunk) ``` #### Module-level methods The module-level methods, `writer.ai.ask` and `writer.ai.stream_ask`, are designed for querying multiple graphs simultaneously. They are useful when you need to aggregate or compare data across multiple graphs. ```python ask theme={null} from writer.ai import ask # Pose a question to multiple graphs response = ask( question="What are the latest advancements in AI?", graphs_or_graph_ids=[ "550e8400-e29b-41d4-a716-446655440000", "123e4567-e89b-12d3-a456-426614174000" ] ) print(response) ``` ```python stream_ask theme={null} from writer.ai import stream_ask # Stream responses from multiple graphs for chunk in stream_ask( question="Describe the key features of renewable energy sources.", graphs_or_graph_ids=[ "550e8400-e29b-41d4-a716-446655440000", "123e4567-e89b-12d3-a456-426614174000" ] ): print(chunk) ``` ## Using the `Tools` class > [!NOTE] > > This document outlines the use of `Tools` in the Writer Framework; for more thorough documentation, check out (this guide)\[[https://dev.writer.com/tools](https://dev.writer.com/tools)]. The `writer.ai.tools` instance provides access to Writer SDK `tools` resources, such as text splitting, medical content comprehension, and PDF parsing. Below is a guide on how to use each method. ### Splitting Content The `split` method divides text into chunks based on a selected strategy. ```python theme={null} from writer.ai import tools content = \ """ This is a long piece of text that needs to be split into smaller parts. Lorem ipsum dolor sit amet... """ chunks = tools.split(content, strategy="llm_split") print(chunks) ``` **Parameters**: * `content` (str): The text to be split. * `strategy` (str): The splitting strategy (`llm_split`, `fast_split`, or `hybrid_split`). **Returns**: A list of text chunks. ### Medical Content Comprehension The `comprehend_medical` method processes medical text and extracts relevant entities based on a specified response type. ```python theme={null} from writer.ai import tools medical_text = "Patient shows symptoms of hypertension and diabetes." entities = tools.comprehend_medical(medical_text, response_type="Entities") print(entities) ``` **Parameters**: * `content` (str): The medical text to process. * `response_type` (str): The type of medical response (`Entities`, `RxNorm`, `ICD-10-CM`, or `SNOMED CT`). **Returns**: A list of extracted medical entities. ### PDF Parsing The `parse_pdf` method extracts text content from a PDF file. The file can be referenced by its ID, or provided as a `File` object. ```python file_id theme={null} from writer.ai import tools file_id = "example-file-id" parsed_content = tools.parse_pdf(file_id, format="text") print(parsed_content) ``` ```python upload_file theme={null} from writer.ai import tools file_object = upload_file( data=pdf_content, type="application/pdf", name="uploaded_file.pdf" ) parsed_content = tools.parse_pdf(file_object, format="text") print(parsed_content) ``` **Parameters**: * `file_id_or_file` (str or File): The file to parse (by ID or as an object). * `format` (str): The format of the extracted content (`text` or `markdown`). **Returns**: The text content of the PDF. # Application state Source: https://dev.writer.com/framework/application-state Each session is assigned a unique application state by the Framework. ## Initializing state To set the initial application state, use the `wf.init_state()` method with a dictionary argument. > [!TIP] > > All user sessions will start with a clone of this initial state. ```py theme={null} import writer as wf # Define the initial state initial_state = wf.init_state({ "counter": 0, }) # Define an event handler that modifies the state # It receives the session state as an argument and mutates it def increment(state): state["counter"] += 1 ``` In the above example, each session begins with a `counter` at 0. As users interact with the application and activate event handlers, their session's `counter` value will change. For instance, if a user triggers the `increment` handler three times, their counter will increase to 3. To access the `counter` value in the Builder, use @. ### Managing nested state elements To include nested elements in your state, use nested dictionaries: ```python theme={null} # Example of nested state initialization wf.init_state({ "counter": 0, "my_app": { "title": "Nested value" } }) ``` You can reference nested elements in the Builder as `@{my_app.title}`. ### Backend-only state elements By default, all of the elements in the session state are sent to the front-end. > [!WARNING] > > All state elements are transmitted to the front-end by default, regardless of their visibility in the user interface. To keep certain state elements private (back-end-only), prefix them with an underscore `_`. This is useful in several scenarios: 1. When data synchronization to the front-end is unnecessary. 2. When data cannot be serialized for the front-end, such as database connections. 3. When data is sensitive to the specific session and should remain confidential. These elements remain in the back-end and cannot be accessed from the Builder. ## Managing files and binary data In components where the Builder interfaces with external data, such as images, it often requires the use of data URLs. The source for an *Image* component, for example, can be a standard URL or a data URL. Packing Files and Binary Data: Files and binary data can be converted to data URLs before they are sent to the front-end. Use `wf.pack_file()` and `wf.pack_bytes()` for this purpose. The `mime_type` argument, while optional, specifies the media type, helping the browser to correctly handle the data. ```python theme={null} import writer as wf # Initialize state with various data types wf.init_state({ # Reference a file by its filesystem path "sales_spreadsheet": wf.pack_file("sales_spreadsheet.xlsx"), # Use a file-like object that implements a .read() method "main_image": wf.pack_file(image_file, mime_type="image/jpeg"), # Convert raw bytes specifying a MIME type "my_bytes": wf.pack_bytes(b"\x31\x33\x33\x37", mime_type="text/plain"), # Directly assign raw bytes without a MIME type "my_raw_bytes": b"\x31\x33\x33\x37", }) ``` ## Handling non-standard data types The front-end cannot directly display complex data types such as Pandas dataframes or Matplotlib figures. Such objects must be serialized before being sent. > [tab] Matplotlib figures > > Matplotlib figures are converted to PNG data URLs, which can be shown using a standard *Image* component. > > ```python theme={null} > wf.init_state({ > "my_matplotlib_fig": fig, > }) > ``` > > The element can be used in an *Image* component in the Builder by setting the source to `@{my_matplotlib_fig}`. Alternatively, as data inside a *File Download* component. > [tab] Plotly graphs > > Plotly graphs are converted to Plotly JS specifications, using JSON. They can be used in *Plotly Graph* components. > [tab] Altair charts > > Altair charts are converted to Vega Lite specifications, based on JSON. They can be used in *Vega Lite Chart* components. > [tab] Pandas dataframes > > Pandas dataframes are converted to JSON and can be used in *Dataframe* components. ## State schema State schema is a feature that allows you to define the structure of the state. This is useful for ensuring that the state is always in the expected format. Schema allows you to use features like * typing checking with mypy / ruff * autocomplete in IDEs * declare dictionaries * automatically calculate mutations on properties more into [Advanced > State schema](./state-schema) ```python theme={null} import writer as wf class AppSchema(wf.WriterState): counter: int initial_state = wf.init_state({ "counter": 0 }, schema=AppSchema) # Event handler # It receives the session state as an argument and mutates it def increment(state: AppSchema): state.counter += 1 ``` # Authentication Source: https://dev.writer.com/framework/authentication The Writer Framework authentication module allows you to restrict access to your application. Framework will be able to authenticate a user through an identity provider such as Google, Microsoft, Facebook, Github, Auth0, etc. > [!WARNING] > > Authentication is done before accessing the application. It is not possible to > trigger authentication for certain pages exclusively. > [!WARNING] > > Static assets from Writer Framework exposed through `/static` and `/extensions` endpoints are not protected behind Authentication. ## Use Basic Auth Basic Auth is a simple authentication method that uses a username and password. Authentication configuration is done in the [server_setup.py module](/framework/custom-server). > [!WARNING] > > Password authentication and Basic Auth are not sufficiently secure for critical applications. If HTTPS encryption fails, a user could potentially intercept passwords in plaintext. Additionally, these methods are vulnerable to brute force attacks that attempt to crack passwords. To enhance security, it is advisable to implement authentication through trusted identity providers such as Google, Microsoft, Facebook, GitHub, or Auth0. ```python server_setup.py theme={null} import os import writer.serve import writer.auth auth = writer.auth.BasicAuth( login=os.getenv('LOGIN'), password=os.getenv('PASSWORD'), ) writer.serve.register_auth(auth) ``` ### Brute force protection A simple brute force protection is implemented by default. If a user fails to log in, the IP of this user is blocked. Writer framework will ban the IP from either the `X-Forwarded-For` header or the `X-Real-IP` header or the client IP address. When a user fails to log in, they wait 1 second before they can try again. This time can be modified by modifying the value of `delay_after_failure`. ![429](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/429.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=2a0e055b6df575a4c9f4ba392111461a) ## Use OIDC provider Authentication configuration is done in the `server_setup.py` [module](/framework/custom-server). The configuration depends on your identity provider. Here is an example configuration for Google. ![Authentication OIDC Principle](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/auth.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=4686c4fa72431516b12cd6ca16b035b1) ```python server_setup.py theme={null} import os import writer.serve import writer.auth oidc = writer.auth.Oidc( client_id="1xxxxxxxxx-qxxxxxxxxxxxxxxx.apps.googleusercontent.com", client_secret="GOxxxx-xxxxxxxxxxxxxxxxxxxxx", host_url=os.getenv('HOST_URL', "http://localhost:5000"), url_authorize="https://accounts.google.com/o/oauth2/auth", url_oauthtoken="https://oauth2.googleapis.com/token", url_userinfo='https://www.googleapis.com/oauth2/v1/userinfo?alt=json' ) writer.serve.register_auth(oidc) ``` ### Use pre-configured OIDC The Writer Framework provides pre-configured OIDC providers. You can use them directly in your application. | Provider | Function | Description | | - | - | - | | Google | `writer.auth.Google` | Allow your users to login with their Google Account | | Github | `writer.auth.Github` | Allow your users to login with their Github Account | | Auth0 | `writer.auth.Auth0` | Allow your users to login with different providers or with login password through Auth0 | #### Google You have to register your application into [Google Cloud Console](https://console.cloud.google.com/). ```python server_setup.py theme={null} import os import writer.serve import writer.auth oidc = writer.auth.Google( client_id="1xxxxxxxxx-qxxxxxxxxxxxxxxx.apps.googleusercontent.com", client_secret="GOxxxx-xxxxxxxxxxxxxxxxxxxxx", host_url=os.getenv('HOST_URL', "http://localhost:5000") ) writer.serve.register_auth(oidc) ``` #### Github You have to register your application into [Github](https://docs.github.com/en/apps/creating-github-apps/registering-a-github-app/registering-a-github-app#registering-a-github-app) ```python server_setup.py theme={null} import os import writer.serve import writer.auth oidc = writer.auth.Github( client_id="xxxxxxx", client_secret="xxxxxxxxxxxxx", host_url=os.getenv('HOST_URL', "http://localhost:5000") ) writer.serve.register_auth(oidc) ``` #### Auth0 You have to register your application into [Auth0](https://auth0.com/). ```python server_setup.py theme={null} import os import writer.serve import writer.auth oidc = writer.auth.Auth0( client_id="xxxxxxx", client_secret="xxxxxxxxxxxxx", domain="xxx-xxxxx.eu.auth0.com", host_url=os.getenv('HOST_URL', "http://localhost:5000") ) writer.serve.register_auth(oidc) ``` ### Authentication workflow ![](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/authentication_oidc.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=44a0e689e6a53f0c45339a1e300e64f6) ### App static assets Static assets in your application are inaccessible. You can use the `app_static_public` parameter to allow their usage. When `app_static_public` is set to `True`, the static assets in your application are accessible without authentication. ```python theme={null} oidc = writer.auth.Auth0( client_id="xxxxxxx", client_secret="xxxxxxxxxxxxx", domain="xxx-xxxxx.eu.auth0.com", host_url=os.getenv('HOST_URL', "http://localhost:5000"), app_static_public=True ) ``` ## User information in event handler When the `user_info` route is configured, user information will be accessible in the event handler through the `session` argument. ```python theme={null} def on_page_load(state, session): email = session['userinfo'].get('email', None) state['email'] = email ``` ## Unauthorize access It is possible to reject a user who, for example, does not have the correct email address. > [!TIP] > > You can also use userinfo inside app. You can restrict access to certain pages > inside the application by using the `session` object. See [User information in > event handler](#user-information-in-event-handler) ```python theme={null} from fastapi import Request import writer.serve import writer.auth oidc = ... def callback(request: Request, session_id: str, userinfo: dict): if userinfo['email'] not in ['nom.prenom123@example.com']: raise writer.auth.Unauthorized(more_info="You can contact the administrator at support.example.com") writer.serve.register_auth(oidc, callback=callback) ``` The default authentication error page look like this: ![](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/auth_unauthorized_default.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=121f690212138f13acaa32b387c2e3ee) | Parameter | Description | | - | - | | status_code | HTTP status code | | message | Error message | | more_info | Additional information | ## Modify user info User info can be modified in the callback. ```python theme={null} from fastapi import Request import writer.serve import writer.auth oidc = ... def callback(request: Request, session_id: str, userinfo: dict): userinfo['group'] = [] if userinfo['email'] in ['fabien@example.com']: userinfo['group'].append('admin') userinfo['group'].append('user') else: userinfo['group'].append('user') writer.serve.register_auth(oidc, callback=callback) ``` ## Custom unauthorized page You can customize the access denial page using your own template. ```python theme={null} import os from fastapi import Request, Response from fastapi.templating import Jinja2Templates import writer.serve import writer.auth oidc = ... def unauthorized(request: Request, exc: writer.auth.Unauthorized) -> Response: templates = Jinja2Templates(directory=os.path.join(os.path.dirname(__file__), "templates")) return templates.TemplateResponse(request=request, name="unauthorized.html", status_code=exc.status_code, context={ "status_code": exc.status_code, "message": exc.message, "more_info": exc.more_info }) writer.serve.register_auth(oidc, unauthorized_action=unauthorized) ``` ## Enable in edit mode Authentication is disabled in edit mode. To activate it, you must trigger the loading of the server_setup module in edition mode. ```bash theme={null} writer edit --enable-server-setup ``` # Backend-driven UI Source: https://dev.writer.com/framework/backend-driven-ui Framework facilitates backend-initiated user interface modifications. These changes are made possible through **Code-Managed Components** (CMCs), distinct from the *Builder-Managed Components* (BMCs). CMCs, unlike BMCs, are dynamically created and modified via back-end code, and cannot be edited (but still can be viewed) within the application builder. It's important to also note that CMCs do not persist in your application's files and exist only during the application runtime, supporting dynamic UI adjustments. > [!NOTE] > > To summarise: > > **CMC** – Code-Managed Component > > * created via **application back-end**; > * **cannot be edited** in builder; > * is **not saved** to `.wf/components-*.jsonl`. > > **BMC** – Builder-Managed Component > > * created via **builder**; > * **can be edited** in builder; > * is **saved** to `.wf/components-*.jsonl`. ## UI manager Framework provides two independent approaches for managing your application's UI: initializing a base UI and making session-specific updates. ### Initializing base UI The `init_ui()` method sets up a UI manager to configure UI components at the application's startup. This creates a component set that is accessible across all sessions: ```python theme={null} import writer as wf with wf.init_ui() as ui: with ui.Page(id="my-page"): ui.Header({"text": "Hello World!"}) ui.ColumnContainer(id="column-container") ``` ### Making session-specific updates For dynamic, session-specific UI updates, the `ui` parameter is used within handler functions. This approach allows for real-time modifications tailored to individual user sessions: ```python theme={null} def display_user_data(ui, state): with ui.find("column-container"): with ui.Column(): ui.Text({"text": f"And welcome {state["username"]}!"}) with ui.Column(): ui.Text({"text": f"Your data: {state["user_data"]}"}) ``` ## UI manager methods ### `find` method You can use the `ui.find(component_id: str)` method to access existing components by ID: ```python theme={null} with ui.find("column-container"): with ui.Column(): ... ``` If the component couldn't be found, the method raises a `RuntimeError`. ### `refresh_with` method You can use the `ui.refresh_with(component_id: str)` method to replace children CMCs of an existing component (referenced by its ID): ```python theme={null} with ui.refresh_with("my-page"): # Previously existing children are cleared ui.Header({"text": "Hello New World!"}) with ui.ColumnContainer(): with ui.Column(): ui.Text({"text": "Nobody here for now..."}) ``` This method also allows to clear children CMCs of a component: ```python theme={null} with ui.refresh_with("my-page"): # Empties the page pass ``` If a targeted component has builder-managed children, they will not be removed. A warning message will be recorded in the application's log for each BMC attempted to be removed. This does not stop the execution of the method – any remaining CMCs will still be removed. As well as with `find` method, it also raises a `RuntimeError` if it fails to find a referenced component. ### `parent` method `ui.parent(component_id: str, level: int = 1)` gives access to the id to parents at higher levels. ```python theme={null} container = ui.parent('my-text') # first parent id container = ui.parent('my-text', 3) # level 3 parent id with ui.find(container): ... ``` ### Component methods UI manager contains methods linked to each front-end component. For example, in previous code snippets we provide a `ui.Text` method, which is used for creating [Text components](https://dev.writer.com/components/text). This method expects `content: dict` as first argument, which enables you to set the field properties of the component, through corresponding keys: ```python theme={null} ui.Text( { "text": "Hello World!", # The text content of the component "useMarkdown": "no", # Will not use Markdown "alignment": "left", # Text is aligned to the left "primaryTextColor": "#000000", # The text color is black "cssClasses": "my-text hello-world" # Apply 'my-text' and 'hello-world' CSS classes } ) ``` In a similar way, every other component method also expects `content` as its first argument: ```python theme={null} ui.VideoPlayer( { "src": "https://example.com/assets/mov/rick-roll-video.mov", "autoplay": "yes", "controls": "no", "muted": "no", "loop": "no", } ) ``` In addition to `content`, a set of fields which is specific to the component type, you can also modify the base properties of the component itself, which are: * **`id: str`**: A unique identifier used for accessing the component after it was created.\ *Providing an identifier that is already taken would result in `RuntimeWarning` and the existing component being overwritten with a newly created one.* ```python theme={null} ui.Text( {"text": "Hello World!"}, id="hello-world-text" ) ``` *If no ID is provided with a component, a UUID is automatically generated for it.* > [!NOTE] > > Make sure to provide an `id` if you intend to `find` the component later\ > As the `find` method relies on `id` of the component, retrieval might get tricky if its `id` was generated randomly. * **`position: int`**: Determines the display order of the component in relation to its siblings.\ Position `0` means that the component is the first child of its parent.\ Position `-2` is used for components – such as [sidebars](https://dev.writer.com/components/sidebar) – that have a specific reserved position not related to their siblings. ```python theme={null} ui.Text( {"text": "Hello Parent, I'm your first child!"}, position=0 ) ``` *Position is calculated automatically for each component, and you should be careful when you override it with predefined value, as this might lead to unexpected results.* * **`parentId: str`**: Determines the parent [container](#container-components) for the component. By default, components recognise the container in the context of which they were defined as their parent. This allows for linking components to their parents outside of context, or for overriding a parent within a context. ```python theme={null} ui.Text( {"text": "Hello Parent, I'm your child too!"}, parentId="dear-parent" ) ``` * **`visible: bool | str`**: Determines the visibility of the component, `True` by default. ```python theme={null} ui.Text({"text": "I'm visible!"}, visible=True) ui.Text({"text": "And I'm not!"}, visible=False) ui.Text({"text": "My visibility depends on the @{my_var}!"}, visible="my_var") ``` * **`handlers: dict[str, callable]`**: Attaches [event handlers](https://dev.writer.com/framework/event-handlers) to the component. Each dictionary key represents an event, and its value is the corresponding handler.: ```python theme={null} def increment(state): state["counter"] += 1 initial_state = wf.init_state({"counter": 0}) ... ui.Button( {"text": "My Counter: @{counter}"}, handlers={"wf-click": increment} ) # You have two options for adding a function # to the `handlers` dictionary: # directly pass the function itself, # or use the function's name as a string. # Both approaches yield the same outcome. ``` *A component can be linked to multiple event handlers.* * **`binding: dict[str, str]`**: Links the component to a state variable via [binding](https://dev.writer.com/framework/builder-basics#binding). The dictionary key is the bindable event, and the value is the state variable's name: ```python theme={null} initial_state = wf.init_state({ "header_text": "Default Text" "counter": 0 }) ... ui.TextInput( {"label": "Bound Text"}, binding={"wf-change": "header_text"} ) # This input will display "Default Text" # Changing the text in this input will modify the `header_text` variable ui.SliderInput( {"minValue": 0, "maxValue": 300, "stepSize": 1}, binding={"wf-number-change": "counter"} ) # This slider will have 0 as a default value # Sliding it will modify the `counter` variable ``` *Unlike handlers, a component can be linked to just one variable via a bindable event. If the `binding` dictionary includes multiple event-variable pairs, a `RuntimeError` will be triggered.* ### Container components Framework provides multiple layout components that can serve as *containers* for other components. You can use `with` keyword to define such layouts: ```python theme={null} with ui.Section({"title": "My Section"}): ui.Text({"text": 'Hello World!'}, id="hello-world") ``` It also allows for "chaining" multiple containers together, creating extensive and deeply-nested layout structures when needed: ```python theme={null} with ui.ColumnContainer(id="cmc-column-container"): with ui.Column(id="cmc-column-1"): with ui.Section({"title": "My Section 1"}): ui.Text({"text": 'Hello World!'}, id="hello-world-1") with ui.Column(id="cmc-column-2"): with ui.Section({"title": "My Section 2"}): ui.Text({"text": 'Hello World again!'}, id="hello-world-2") ``` > [!WARNING] > > Most components depend on being inside of a container. This means, for example, that Text components in code above cannot be created as "orphans", outside a Column or Section. Attempting to do so would raise an `UIError`. By default, components inside container's `with` are being *appended* to it: ```python theme={null} with ui.Column(id="cmc-column-1"): ui.Text({"text": 'Hello World!'}, id="hello-world-1") ... # Retrieves the Column component created before with ui.find(id="cmc-column-1"): # The following component is going to be appended # to the retrieved Column ui.Text({"text": 'Hello World again!'}, id="hello-world-2") ``` This will result in a Column component having two children Text components. To replace or clear the children, use [`refresh_with` method](#refresh_with-method): ```python theme={null} with ui.Column(id="cmc-column-1"): ui.Text({"text": 'Hello World!'}, id="hello-world-1") ... with ui.refresh_with(id="cmc-column-1"): # The following component is going to replace # previously existing children of the retrieved Column ui.Text( {"text": 'To Hello World, or not to Hello World?'}, id="hello-world-new" ) ``` # Backend-initiated actions Source: https://dev.writer.com/framework/backend-initiated-actions Targeted, backend-initiated actions can be triggered from event handlers, using methods of `state`. Internally, this is achieved using Framework's `mail`, ephemeral state that is cleared when it reaches the intended user. ## Triggering a file download The `file_download` method takes the `data` and `file_name` arguments. The first must contain raw bytes (a `bytes` object) or a packed file. As mentioned in the [Application State](/framework/application-state#managing-files-and-binary-data) section of the guide, a packed file is obtained using the `wf.pack_file` or `wf.pack_bytes` methods. ```py theme={null} def handle_file_download(state): # Pack the file as a FileWrapper object data = wf.pack_file("assets/story.txt", "text/plain") file_name = "thestory.txt" state.file_download(data, file_name) ``` ## Adding a notification ![Notifications](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/backend-initiated-actions.notifications.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=ae08937660ab594dfbefadb6b5ef8bab) Framework adds notifications when a runtime error takes place. You can add your own notifications using the `add_notification` method, which takes the `type`, `title` and `message` arguments. `type` must be one of `error`, `warning`, `info`, `success`. ```py theme={null} def notify_of_things_that_happened(state): state.add_notification("error", "An Error", "Something bad happened.") state.add_notification("warning", "A Warning", "Be aware that something happened.") state.add_notification("info", "Some Info", "Something happened.") state.add_notification("success", "A Success", "Something good happened.") ``` ## Opening a URL Open a URL in a new tab using the `open_url` method, which takes the `url` argument. ```py theme={null} def handle_open_website(state): state.open_url("https://writer.com") ``` The URL will be safely opened with `noopener` and `noreferrer` options. > [!WARNING] > > Popup blockers: Given that the URL is opened asynchronously, popup blockers will likely block the new window —unless the user has opted in. ## Changing the active page The active page and route parameters can be changed using the methods `set_page` and `set_route_vars`. This is explained in more detail in [Page Routes](/framework/page-routes). # Builder basics Source: https://dev.writer.com/framework/builder-basics Writer Framework Builder’s interface is an overlay on top of the running app, which allows you to edit your app while it’s running. This approach gives you an accurate representation of how the app will look and behave without the need to constantly preview it. ## Writer Framework Builder’s modes Writer Framework Builder has two modes: 1. **UI mode:** This is the default mode, which provides an overlay of tools for building and editing the user interface. The app still runs in UI mode, allowing to you test its functionality while you’re building it. You can also edit the app’s code and view its log. ![Writer Framework Builder in UI mode](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.ui-mode.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=8a94e3f7fd39ec70fae21dc2e1b03b90) 2. **Preview mode:** This mode lets you preview the application, experiencing it almost as your end users would. The tool overlay is hidden, but you can still edit the app’s code and view its log in this mode. ![Writer Framework Builder in Preview mode](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.preview-mode.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=74614f25146ef300768f159cd2c1bed8) You can switch between UI mode and Preview mode by using the **UI**/**Preview** selector near the upper left corner of the page. ![Writer Framework Builder’s UI/Preview selector](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.ui-preview-selector.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=dde73bd2ff445c46b590423b99c6c476) ## Building your app in UI mode ### The different areas of UI mode In UI mode, Writer Framework Builder’s page is divided into these areas: ![Writer Framework Builder in UI mode, with indivdual areas labeled](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.ui-mode-with-labels.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=91038caeaa6ed955729dd980bf85bc73) 1. **Canvas:** This is where you lay out components to build your app’s user interface. It displays the UI as your users will see it. 2. **Core toolkit:** A “palette” of UI components that can be added to your app’s user interface. To add a component to your app’s UI, drag it onto the Canvas or into the Component tree. 3. **Component tree:** This provides an alternative way to view your app’s user interface: as a hierarchical tree structure. It’s useful for ensuring that UI components are located in the right place or in the correct container object, and is handy for selecting UI components in complex layouts. 4. **Component settings:** This panel lets you view and edit the settings for the currently selected UI component. You can hide the Component settings panel if you need more screen space to work on the Canvas. 5. **Top bar:** Contains the “high level” editing controls: switching between UI and Preview mode, undoing and redoing the most recent change to the UI, and viewing the application’s state. 6. **Bottom bar:** Contains the “low level” editing controls, which toggle the Code and Log panels. ### Defining your app’s user interface Writer Framework Builder provides a selection of over 50 UI components that you can use to build your app’s user interface: ![Visual catalog of all the components in the Core toolkit](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.components.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=5e4532b6ad203b6e794f83861715c232) You define your app’s user interface by dragging components from the Core toolkit and dropping them either onto the Canvas or into the Component tree (remember, the Canvas and Component tree provide different ways to look at your app’s user interface). If you simply drag and drop a UI component onto an empty spot on the Canvas, it will be placed at the “end,” below all other UI components in the user interface. To place a UI component at a specific location, drag them over the desired location or parent component until you see the insertion lines. ![Writer Framework Builder with diagram showing how to drag and drop components from Core toolkit](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.drag-drop-components.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=4b5ba0fe00764a2a716124378509aadc) It can sometimes be difficult to find the component you’re looking for, so the Core toolkit has a search field. You can use it to find the narrow down the list of components or find a specific one. ![Close-up of Core toolkit with instructions for using its Search text field](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.component-search.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=10078ffb156187bdaa6af8fefc0ca6af) Some UI components, such as Section, can act as “parents,” which are UI components that can contain other UI components. Others, such as Text, cannot. Additionally, certain components have placement restrictions — for instance, a Column must be added to a Column Container, and a Sidebar can only be added to a Page. ![Writer Framework builder, showing parent-child relationship between a Section and the Text Input and Button components it contains](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.parent-components.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=89df0ad6e44d0de0e72b77290c7130bd) The Component tree provides a hierarchical view of your app’s user interface. It shows the top-down layout of UI components in your app, as well as the parent-child relationships between components, making it easier to understand your app’s structure and ensure that components are correctly nested. You will find the Component tree useful when trying to reorganize the order of components in the UI, especially those located inside a parent UI component. For more flexibility and finer control, you can use the Component tree as a source or a destination for your drag and drop actions. ### Discovering components The Builder is designed to allow easy discoverability of components. Rather than scouring specifications every time you need to use a component, you can rely on the visual editor to guide you. 1. **Short description:** You can hover on the component type to get a tooltip with a short description. 2. **Available properties and events:** Looking at *Settings* will allow you to see which of its properties are configurable. 3. **Built-in docs:** Components have short docs built into them. You can expand it by clicking the help icon in Settings. 4. **Event handler stub code:** Different events need to be handled differently. The built-in stub handlers, which can be found next to each event, can help you get started when writing event handlers. ### Selecting and editing components To move or edit a component in your UI, you need to select it first. You can do this by clicking on the component either in the Canvas or in the Component tree. The selected component will be highlighted in both the Canvas and Component tree. ![Writer Framework Builder, with instructions to select a component by clicking on it either on the Canvas or in the Component tree](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.select-components.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=0adc6378dc0fe65bba609ffb3629a9fe) Selecting a UI component will allow you to view and edit its settings in the Component settings panel on the right side of the page. ![Writer Framework Builder, with Component settings panel on display, and instructions to hide the panel](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.component-settings.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=9e1be3f0482efb2ed2b04a1856696591) To hide the Component settings panel to get a better view of the Canvas, click on **»** in the button bar. To show the panel, click on **⚙** in the button bar. ![Writer Framework Builder, with Component settings panel hidden, and instructions to show the panel](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.component-settings-show.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=6b2dc8293ac3ac09f0d071892bf50e08) The settings in the Component settings panel are divided into the following sections: > [accordion] Basic settings > > ![Component settings panel, with basic settings highlighted](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.basic-settings.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=d1b63c133e4c8356247559bb423b1c37) > > These settings are divided into two categores: > > 1. **General**, which specifies the component’s content > 2. **Style**, which defines the component’s appearance. > > Values for these settings can include: > > 1. Literals, e.g. `monkey` > 2. References to application state using the template syntax `@{}`, e.g. `@{my_favourite_animal}`. > 3. A combination of both, e.g. `My favourite animal is @{my_favourite_animal}`. > 4. Nested states can be accessed with `.` (dot), e.g. `@{building.height}`. > 5. Nested elements can be dynamically accessed with `[]`, e.g. `@{building[dynamic_prop]}` will be equivalent to `@{building.height}` when `dynamic_prop` equals `height`. > > The values for these settings can be of different types, such as *Text*, *Color* and *Number*. The values are stored as text and are cast to the correct type when evaluated. > [accordion] Binding > > ![Component settings panel, with Binding settings highlighted](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.binding.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=f629f67f8ac7026aa8de68a24b97d8d2) > > Only input components have a **Binding** section, whose settings are used to bind the component to a variable in the application’s state. The binding is two-way; if the user changes the component’s value, the state variable will change to match, and any change the code makes to the bound state variable will also change the component’s value. > > For example, a *Slider Input* component can be bound to a state variable `my_var`. If the value of the slider changes, so does the value of `my_var`. Similarly, if the value of `my_var` changes, the slider is moved automatically to reflect the change. > > To bind an input component, specify the state element. For example, `my_var` or `building.height`. Note that this field should not contain the template syntax, e.g. `my_var` and not `@{my_var}`. > [accordion] Events > > ![Component settings panel, with Events settings highlighted](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.events.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=070332bffa0c38b0bcce28f43d943364) > > The **Events** section lists all the events generated by the selected component, with the option of setting event handlers for them. For example, one of the events that the Text Input component generates is the `wf-change` event, which occurs whenever the user changes the contents of the component. > > For more about event handlers, consult the [*Event handlers*](/framework/event-handlers) section of the Writer Framework documentation. > [accordion] Visibility > > ![Component settings panel, with Visibility settings highlighted](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.visibility.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=9bb148a61970832ad270176472288b7f) > > The **Visibility** settings control Whether the component should be displayed. There are three visibility options: > > 1. **Yes**: The component is displayed. > 2. **No**: The component is *not* displayed. Note that hidden components are still part of the HTML code but aren't shown. > 3. **Custom**: The component’s visibility depends on the value of a given state or context element. For example, if set to `my_var`, visibility will depend on the value of the `my_var` state element. Note that this field, similarly to Binding, should only contain the state element, e.g. `my_var` and not `@{my_var}`. ### Component shortcuts The Component shortcuts bar contains a set of options to perform various operations that are often performed on components. ![Component settings panel, with Component shortcuts bar highlighted](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.component-shortcuts.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=787dc69289144b36d75082d070cb92c9) Options will be grayed out when they're not applicable to the relevant component. Most shortcuts can also be activated using the keyboard; hover the cursor over a shortcut to see its keyboard shortcut. The shortcuts are: ![The Component shortcuts bar, with labels](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.component-shortcuts-guide.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=60d9ef66da680575e6aff41dc2a61afc) * **Add**: Adds a child of a specified type to the selected component. * **Move up**: Decrements the position index of the selected component, used to sort children within the parent container. * **Move down**: Increments the position index of the selected component. * **Cut**: Cuts the selected component and places it in the clipboard. * **Copy**: Copies the selected component to the clipboard. * **Paste**: Pastes the content of the internal clipboard using the selected component as a parent. * **Go to parent**: Selects the parent of the selected component. * **Delete**: Deletes the selected component. ### The Code editor and the Log Writer Framework Builder provides a built-in Code editor for the `main.py` file, which defines the behavior of the app. You can toggle the Code panel by clicking the **Code** control near the lower left corner of the page: ![Writer Framework Builder, with the Code editor displayed](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.code.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=469014b3b60a8ca53145e42f37ef1c88) Any changes made to the code do not take effect until you click the **Save and run** button, located at the upper right corner of the code editor. The log is a useful debugging tool that displays any messages sent to standard output via the `print()` function, as well as any error messages. You can toggle the Log panel by clicking the **Log** control near the lower right corner of the page: ![Writer Framework Builder, with the Log editor displayed](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.log.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=0e276770d1f08c2b6010f6ab30f2399c) Note that both the Code editor and Log panes can be displayed at the same time: ![Writer Framework Builder, with the Code editor and Log displayed at the same time](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.code-and-log.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=09b2359d8154446377d59b1daca3704d) ## Testing your app in Preview mode In Preview mode, the overlays that let you build the user interface — the Core toolkit, Component tree, and Component settings — are invisible and unavailable. You see the app *almost* as your users would see it; the Top bar and Bottom bar, which your users would not see, are still available to you in Preview mode. ![Writer Framework Builder in preview mode](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.preview.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=0e5e0750b740b6a7208aa13058d5aaba) You can still use the Code editor and Log in Preview mode: ![Writer Framework Builder in Preview mode, with the Code editor and Log displayed at the same time](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/builder-basics.preview-code-and-log.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=30b357f89696828a0c990aa476d8cb7d) # Chat assistant Source: https://dev.writer.com/framework/chat-assistant In this tutorial, you'll use the Writer Framework to create a simple yet powerful chat assistant that can engage in conversations on various topics, provide answers to your questions, and maybe even help you when you're experiencing writer's block! The process will take only minutes using a drag-and-drop visual editor to build the user interface and Python for the back-end code. Here's what the finished project will look like: ![Finished chat assistant project](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_1.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=0c3c814df95473821d822abc1c883f92) ## Prerequisites Before starting, ensure you have: * **A Writer account:** You don't need an account to use Writer Framework, but you'll need one to use the AI module. [Sign up for a free account here](https://app.writer.com/register). * **Python 3.9.2 or later**: Use the installer from [python.org](https://www.python.org/downloads/). * **pip:** This command-line application comes with Python and is used for installing Python packages, including those from Writer. * **A basic understanding of Python:** You should be familiar with the basics of the language. * **Your favorite code editor (optional):** There's a code editor built into Writer for editing back-end code, but you can also use Visual Studio Code, Notepad++, Vim, Emacs, or any text editor made for programming if you prefer. ## Setting up your project ### Create a Writer app and get its API key First, you'll need to create a new app within Writer. **1. Create the app in Writer** Log into Writer. From the Home screen, click on the **Build an app** button. ![Writer home screen](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=580c843c75a49b10e62d893751849a7e) The **Start building** menu will appear, presenting options for the types of apps you can create. Select **Framework**, located under **Developer tools**. This will create a brand new app based on Writer Framework. !["Start building" menu](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_3.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=43c43a9a53829617c068bf5d37e9c36d) **2. Copy your app's API key** On the next screen, titled **How to deploy an application**, you can get the API key for the app by clicking on the **Reveal key** button, located under the text **Authenticate with an API key**. Your complete API key will be displayed, and a "copy" button will appear. Click this button to copy the key; you'll use it in the next step. !["How to deploy an application" page](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2a.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=427ce6f509ecfa7fdbc8f44c8b0f7404) ### Set up your computer and create the app's project The next step is to set up the Writer Framework environment on your computer. You'll do this by creating a directory for the project, installing dependencies, and creating the project for the application using a template. **1. Open your terminal application** Open your terminal application. On macOS and Linux, this application goes by the name *Terminal*; on Windows, you can use either *Windows PowerShell* (which is preferred) or *Command Prompt*. **2. Install the dependencies** > [!NOTE] > > If you already have the `writer` and `python-dotenv` packages installed on your computer, you can skip this step. Install the `writer` and `python-dotenv` packages by entering the following commands in your terminal application: ``` pip install writer python-dotenv ``` This command tells `pip`, the Python package installer, to install two packages: * `writer`, which provides some command-line commands and enables Python code to interact with Writer and the Writer Framework. * `python-dotenv`, which makes it easy to manage environment variables by loading them from a `.env` file. This one is optional for this exercise, but you might find it useful when working on larger projects. **3. Set the API key environment variable** To pass your API key to the Writer Framework, you need to set an environment variable called `WRITER_API_KEY`. Select your operating system and terminal application below, then copy and paste the command into your terminal application, replacing `[your_api_key]` with the API key you copied earlier: ```sh macOS/Linux (Terminal) theme={null} export WRITER_API_KEY=[your_api_key] ``` ```sh On Windows (Windows PowerShell) theme={null} $env:WRITER_API_KEY=[your_api_key] ``` ```sh On Windows (Command Prompt) theme={null} set WRITER_API_KEY=[your_api_key] ``` The `WRITER_API_KEY` environment variable will remain defined as long your terminal session is open (that is, until you close your terminal application’s window). **4. Create the project** Create the project by entering this command into your terminal application: ``` writer create chat-assistant --template=ai-starter ``` This command sets up a new project called `chat-assistant` using a starter template called `ai-starter` so that you're not starting "from scratch." ## Build the UI Now that you've created the project, it's time to define the UI. The Writer Framework's drag-and-drop capabilities make it easy — even if you haven't done much UI work before! The project editor is a web application that runs on your computer and enables you to define and edit your app's user interface. Launch it by typing the following into your terminal application: ``` writer edit chat-assistant ``` You'll see a URL. Control-click it (command-click on macOS) to open it, or copy the URL and paste it into the address bar of a browser window. The browser window will contain the project editor, which will look like this: ![Project editor](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2b.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=75f2df9ca6f896d9461ed2604b58d398) You'll see the following: * The **canvas** is in the center. It displays the app's user interface. * The column on the left contains: * The **Core toolkit**, which contains all the UI components. You define the user interface by dragging components from the Toolkit and placing them on the canvas. * The **Component tree**, which shows the arrangement of the UI components on the canvas. It's also useful for selecting items on the canvas, especially when it has a lot of UI components. It's time to build the UI! **1. Examine the header** Select the **Header** component by clicking it — it's the component at the top, containing the title **AI STARTER** and a gray area labeled **Empty Header**. When you click it, you'll see the **properties** panel appear on the right side of the page. This lets you view and edit the properties of the selected component. ![The selected header and its properties panel](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2c.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=30ee76df7d06491491699e17d0c7e64b) The first property you'll see in the panel is the **Text** property, which defines the text that appears as the header's title. It should contain the value `@{my_app.title}`. The `@{` and `}` indicate that `my_app.title` is a variable and that its contents should be the text displayed instead of the literal text "my_app.title". You'll set the value of this variable soon. **2. Clear the Section's default title** Select the **Section** component by clicking it — it's just below the **Header** component and contains the title **Section Title** and a gray area labeled **Empty Section**. In the **properties** panel, clear out the value of the **Title** property. This will remove the **Section**'s default title. ![The selected section and its properties panel](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2d.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=188d524f61e214d47483571614ed6fd9) **3. Add a Text component to the Section** Drag a **Text** component from the **Core toolkit** panel on the left (it's under **Content**, and you may need to scroll down a little to find it) and into the *Section*. Sections can act as containers for other components. > [!NOTE] > > You can search for a specific component by using the search bar at the top of the **Core toolkit** panel. Select the **Text** component. In the **properties** panel, set the **Text** property to provide instructions or context for your chat assistant. Here's an example: `Welcome to the Chat Assistant. Ask me anything!` ![The text component and its properties panel](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2e.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=fc1c5e1409d44ea510ea6ef0af471d7a) **4. Add a Chatbot component to the Section** The heart of this app is the **Chatbot** component, a pre-built component that displays the conversation between the LLM and the user and provides a text field where the user can enter prompts. Drag a **Chatbot** component from the **Core toolkit** panel (it's under **Content**) into the *Section*, just below the Text box. ![The chatbot component](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2f.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=7bd7ea78e5115c2057646121dee641eb) ## Add the back-end code With the UI laid out, it's time to work on the logic behind it. The logic behind the user interface is defined in a file named `main.py`, which is in your project's directory. This file was automatically generated; you'll update the code in it to define the behavior of your app. The simplest way to edit `main.py` is within the project editor. Click on the "toggle code" button (beside the word **Code**) near the lower left corner of the project editor page. ![Project editor with arrow pointing to toggle code button](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2g.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=16baa189672daa68f3d956dc3053a348) A pane with the name **Code** will appear at the bottom half of the screen, displaying an editor for the the contents of `main.py`. ![Project editor with the code editor displayed](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2h.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=e82dd26da8afd23ea8f48ee8f949f105) > [!NOTE] > > If you'd rather use a code editor instead of coding in the browser, use it to open the `main.py` file in your project's directory. Now follow these steps: **1. Import libraries and load the Writer Framework API key** You should see the following at the start of the file: ```python theme={null} import writer as wf import writer.ai ``` Replace that code with the following: ```python theme={null} import os import writer as wf import writer.ai # Set the API key wf.api_key = os.getenv("WRITER_API_KEY") ``` This code imports the libraries that the application will need and then reads your Writer Framework API key in the `WRITER_API_KEY` environment variable. **2. Create a handler to respond to the user's input** The application needs a function to handle incoming chat messages. Find these comments in the code... ```python theme={null} # Welcome to Writer Framework! # This template is a starting point for your AI apps. # More documentation is available at https://dev.writer.com/framework ``` ...and replace them with the following function: ```python theme={null} def generate_completion(state, payload): print(f"Here's what the user entered: {payload['content']}") state["conversation"] += payload print(f"Conversation: {state['conversation'].messages}") try: for index, chunk in enumerate(state["conversation"].stream_complete()): print(f"Chunk {index}: {chunk}") if not chunk.get("content"): chunk["content"] = "" state["conversation"] += chunk print(f"state['conversation']:\n{state['conversation'].messages}") except Exception as e: print(f"Error during stream_complete: {e}") ``` The `generate_completion()` function will be called when the user enters a prompt, which is contained in the `payload` object. The `payload` object is added to the `conversation` object contained in the application's `state`, which adds the user's prompt to the record of the conversation between the user and the LLM. After adding the user's prompt to the conversational record, `generate_completion()` calls the `conversation` object's `stream_complete()` method, which generates an LLM completion based on the conversation so far. As its name implies, `stream_complete()` returns the completion as a stream of text chunks, which are captured and added to the `conversation` object. > [!NOTE] > > The `conversation` object in the code above is an instance of Writer’s `Conversation` class. You can find out more about this class on our [*Writer AI module*](https://dev.writer.com/framework/ai-module) page. Note that `generate_completion()` completion uses a lot of `print()` functions for debugging purposes, and you can use them to get a better idea of what's happening in the function. You'll see their output in both your terminal application and in the project editor's 'log' pane (which will be covered shortly) as you use the chat assistant. This output will include: * The prompt the user entered * The chunks of data that make up the LLM's response as they are generated * The record of the conversation between the user and the LLM. The `print()` functions don't affect the operation of the chat assistant in any way, and you can remove them if you wish. **3. Initialize the application** The final step is to set the application's initial state. Find this code, which should be just after the `generate_completion()` function... ```python theme={null} # Initialise the state wf.init_state({ "my_app": { "title": "AI STARTER" }, }) ``` ...and replace it with this: ```python theme={null} # Initialize the state wf.init_state({ "conversation": writer.ai.Conversation(), "my_app": { "title": "CHAT ASSISTANT" }, }) ``` The Writer Framework's `init_state()` method sets the initial value of `state`, a dictionary containing values that define the state of the application. The key-value pairs in `state` are how you store values used by your app and how you pass data between the back-end code and the UI. The code above sets the initial value of `state` so that it has two key-value pairs: * `conversation`: An object that keeps a record of the conversation that the user is having with the LLM. You'll bind its value to the **Chatbot** component soon. * `my_app`: A dictionary containing values that define the application's appearance. This dictionary has a single key-value pair, `title`, which defines the text that appears as the application's title in the **Header**. > [!NOTE] > > For more details about the `state` variable, see our [*Application state*](https://dev.writer.com/framework/application-state#application-state) page. **4. Save the updated code and hide the code editor** That’s all the code. If you edited the code in the browser, save it by clicking the “save” button near the top right corner of the code editor. ![Project editor and code editor, with arrow pointing to save button](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2i.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=0a10aed680c79ebfcb54b5d679d16d84) Click the "toggle code" button to hide the code editor. ## Bind the UI to the back-end code You've built the UI and written the code behind it. Let's connect the two! Go back to the browser window with the project editor and do the following: **1. Observe that the heading at the top of the app is now 'CHATBOT ASSISTANT'** Earlier, you saw that the **Header** component's **Text** property was set to `@{my_app.title}`, a value in the app's `state` variable. You changed this value when you update the call to the Writer Framework's `init_state()` method. **2. Bind the Chatbot component to the 'state' variable's 'conversation' key** Recall that the `conversation` object contained within the `state` variable contains the record of the conversation that the user is having with the LLM. Binding the **Chatbot** component to this object allows it to display the conversation to the user. Select the **Chatbot** component. In the **properties** panel, find the **Conversation** property and set its value to `@{conversation}`. ![Updating the Chatbot's conversation property](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2j.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=03d1547aad9b8898fc274a285434bb26) The value `@{conversation}` specifies that the **Chatbot** component should get its information from the value corresponding to the `conversation` key in the application's `state` variable. **3. Specify the Chatbot component's event handler** You need to specify that the **Chatbot** component should call the `generate_completion()` function when the user enters a prompt. Do this by scrolling down the **properties** panel to the **Events** section until you see a property called **`wf_chatbot_message`**. Select **`generate_completion`** from its menu. ![Updating the Chatbot's wf_chatbot_message property](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2k.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=5a9ddfbaa789a46bf3dd26c889038588) ## Test the application You've completed all the steps to make a working chat assistant, and you can try using it right now, even while editing the user interface! Try entering some prompts into the text entry at the bottom of the **Chatbot** component. The LLM should respond accordingly: ![The chat assistant, with the project editor in "UI" mode](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2l.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=3fde15b8d95e47d25d9200b33becdb91) To get a better sense of what the experience will be like for the user, switch to the preview by changing the edit mode (located near the upper left corner of the page) from *UI* mode to *Preview* mode by selecting the **Preview** option: ![The project editor with an arrow pointing to the Preview button](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2m.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=7634299b9d42ca51e53b36aa8ff6a172) Here’s what the app looks like in *Preview* mode: ![The chat assistant, with the project editor in "Preview" mode](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2n.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=695a087df7fdfec75e0c3c6a2d56d77a) You can see the output of any `print()` functions and error messages by clicking on the **Log** button located near the upper right corner of the page: ![The chat assistant with an arrow pointing to the Log button](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2o.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=abccbdbea8cff7ecc7e28b71cc2f11c8) Here’s what the app looks like when displaying the log: ![The working chat assistant, with the log pane displayed](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_2p.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=7aca8100f0079306e2a7ec9e52bff79c) It's very helpful to be able to test the application while editing it. As you continue to work with Writer Framework, you'll find yourself alternating between making changes to your application and testing those changes without having to leave the project editor. ## Run the application locally Once you've tested the application, it's time to run it locally. Switch back to your terminal application. Stop the project editor with ctrl-c, then run the application by entering the following command: ``` writer run chat-assistant ``` Note that the command starts with `writer run` as opposed to `writer edit`. This launches the application as your users will see it, without any of the editing tools. Even though you can preview your applications in the project editor, it's still a good idea to test it by running it on your computer, outside the project editor, before deploying it. You'll be able to access the application with your browser at the URL that appears on the command line. It should look like this: ![Finished chat assistant project](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/chat/chat_assistant_1.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=0c3c814df95473821d822abc1c883f92) > [!NOTE] > > The Writer editor, which you launched with `writer edit chat-assistant`, and your application, which you launched with `writer run chat-assistant`, run on the same URL, but on different *ports* (specified by the number after the `:` character at the end of the URL). ## Conclusion That's it — you've built a functional chat assistant using the Writer Framework! Feel free to modify this project! The Writer platform is flexible enough for you to customize, extend, and evolve your application into something completely different! To find out what else you can do, check out the documentation for [Writer Framework](https://dev.writer.com/framework/introduction) and the [Writer API](https://dev.writer.com/introduction). # Deploy to Writer Cloud Source: https://dev.writer.com/framework/cloud-deploy ## Basic usage The `writer cloud` command group includes the following commands: * `deploy` * `undeploy` * `logs` ## Common options These options are common across multiple commands: * `--api-key`: The Writer API key used for authentication. If not provided, you will be prompted to enter it. * `--verbose, -v`: Enable verbose output. ## Commands > [accordion] writer cloud deploy > > Deploys an app from the specified path to the Writer cloud. > > **Usage:** > > ``` > writer cloud deploy [OPTIONS] PATH > ``` > > **Arguments:** > > * `PATH`: The path to the folder containing the app to deploy. > > **Options:** > > * `--api-key`: Writer API key for authentication. If not provided, you will be prompted to enter it. > * `--env, -e`: Environment variables to set in the deployed app. Use the format `VAR=value`. Multiple environment variables can be specified by repeating the `--env` option. > * `--verbose, -v`: Enable verbose output. > > **Example:** > > ``` > writer cloud deploy hello --env VAR1=value1 --env VAR2=value2 > ``` > > **Description:** > > * Deploys the app located in the `PATH` folder. > * Creates a deployment package, ignoring `.git` directories, `Dockerfile`s and all files specified in `.gitignore` file. > * Uploads the package to the deployment server. > * The deployed app will have access to specified environment variables. > * By default, the `WRITER_API_KEY` environment variable will be added to enable AI features. > > **Output Example** > > ``` > Creating deployment package from path: /path/to/your/app > [WARNING] Dockerfile found in project root. This will be ignored in the deployment package. > Packing file: pyproject.toml > Packing file: README.md > ... > Uploading package to deployment server > Package uploaded. Building... > ... > Deployment successful > URL: https://your_app_url > ``` > [accordion] writer cloud undeploy > > Stops the deployed app and makes it unavailable. > > **Usage:** > > ``` > writer cloud undeploy [OPTIONS] > ``` > > **Options:** > > * `--api-key`: Writer API key for authentication. If not provided, you will be prompted to enter it. > * `--verbose, -v`: Enable verbose output. > > **Example:** > > ``` > writer cloud undeploy > ``` > > **Description:** > > * Stops and removes the deployed app from the Writer cloud. > [accordion] writer cloud logs > > Fetches logs from the deployed app. > > **Usage:** > > ``` > writer cloud logs [OPTIONS] > ``` > > **Options:** > > * `--api-key`: Writer API key for authentication. If not provided, you will be prompted to enter it. > * `--verbose, -v`: Enable verbose output. > > **Example:** > > ``` > writer cloud logs > ``` > > **Description:** > > * Continuously fetches and displays logs from the deployed app. > * Logs are ordered by date and time. > > **Output Example** > > ``` > 2024-06-11 09:27:02.190646+00:00 [INFO] Starting container entrypoint... > 2024-06-11 09:27:03.798148+00:00 [INFO] BuildService - Downloading build files... > ... > ``` ## Environment variables When deploying an app, you can specify environment variables that will be available to the app during runtime. Use the `--env` option to pass these variables. ``` writer cloud deploy hello --env DB_HOST=db.example.com --env DB_PORT=5432 ``` In this example, `DB_HOST` and `DB_PORT` will be available to the app as environment variables. ## API key The `WRITER_API_KEY` is crucial for deploying and managing apps. It is used for authenticating requests to the Writer cloud. If not provided as an option, the CLI will prompt you to enter it. The `WRITER_API_KEY` will also be added to the deployed app's environment to enable AI features of the Writer framework. ## Deployment process **1. Package Creation** The CLI packages the app, excluding certain files (e.g., Dockerfile, `service_entrypoint.py`). **2. Upload Package** The package is uploaded to the Writer deployment server. **3. Build and Deploy** The server builds and deploys the app, making it accessible via a URL. **4. Environment Variables** Specified environment variables are set, and `WRITER_API_KEY` is added by default. ## Example workflow **1. Deploying an App** ```bash theme={null} writer cloud deploy /path/to/app --env DB_HOST=db.example.com --env DB_PORT=5432 ``` **2. Fetching Logs** ```bash theme={null} writer cloud logs ``` **3. Undeploying an App** ```bash theme={null} writer cloud undeploy ``` By following this documentation, you should be able to effectively deploy and manage your Writer apps using the Writer Framework CLI. # Components Source: https://dev.writer.com/framework/component-list-link # Custom components Source: https://dev.writer.com/framework/custom-components It's possible to extend Framework with custom component templates. They're developed using Vue 3 and TypeScript. Once transpiled, they can be used by copying them to the `extensions/` folder of any project. > [!NOTE] > > Custom components behave exactly like built-in ones. They are just as > performant, can contain other components, and offer the same the Builder > experience. They only differ from built-in components in the way that they're > bundled and imported. ## Architecture Framework front-end compiles to a collection of static assets that is distributed in the Python package. These static assets are then served via FastAPI. During initialisation time, the server scans the `extensions/` folder in the project folder and looks for `.css` and `.js` files. This folder is also served, similarly to `static/`. If it finds any valid files in `extensions/`, it shares the list with clients and tells them to dynamically import these files during runtime. Extensions and custom templates are currently synonyms, but this might change in order to accommodate other extension capabilities. ![Custom Components - Architecture](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/custom-components.architecture.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=0bf436f6f05141b9c10203b73303db10) Dependencies are [provided](https://vuejs.org/api/composition-api-dependency-injection.html) using injection symbols and can be *injected* to be used by the component template. These include `evaluatedFields`, which contain the current values of the editable fields. Injected dependencies are fully typed, making development easier. [Rollup's external feature](https://rollupjs.org/configuration-options/#external), invoked via Vite, allows for extensions to be compiled without dependencies and link those during runtime. Therefore, extensions aren't bundled to be standalone, but rather to work as a piece of a puzzle. ![Custom Components - External](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/custom-components.external.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=c79c2bffa0ff892d4b29585339ade35c) ## Anatomy of a template A template defines how a certain component is rendered. For example, `corebutton` defines how *Button* components are rendered. Framework component templates are purely front-end. They are Vue 3 templates that extend the Vue specification via a [custom option](https://vuejs.org/api/utility-types.html#componentcustomoptions), `writer`. This custom option defines all the Framework-specific behaviour of the component. For example, its `fields` property establishes which fields will be editable via the Builder. ### Simple example This example shows a template for *Bubble Message*, a simple demo component with one editable field, `text`. ```js theme={null} ``` The code above will make Bubble Message available in the Builder. ![Custom Components - Bubble Message](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/custom-components.bubble-message.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=5ea7079317c2b87385b7db8000124156) ## Developing templates ### Run a local server **1. Clone the Framework Repository** To get started, clone the [Framework repository](https://github.com/writer/writer-framework) from GitHub. **2. Set Up the Development Environment** To develop custom templates in a developer-friendly way, ensure you have a front-end development server with instant reload capabilities. The front-end code for Framework is located in the `ui` folder. With Node and npm installed on your system, run `npm install` to install dependencies. Then, start the server with support for custom component templates using `npm run custom.dev`. ```sh cd ui npm install # "custom.dev" links templates in theme={null} "custom_components/" # "dev" runs the server without them npm run custom.dev ``` **3. Start the Back-End Server** The command `npm run custom.dev` starts a front-end server, which requires a back-end to function fully. Start Framework via command line, specifying the option `--port 5000`, to provide a back-end on that port. It's recommended to create a new app for testing the template you're developing. `sh writer create customtester writer edit customtester --port 5000 ` **4. Access Framework and Test Custom Component** You should now be able to access Framework via the URL provided by Vite, e.g. `http://localhost:5174`. In the Builder's *Toolkit*, you should see the sample component, *Balloon Message*. Add it to your tester application. ### Create a new component > [!TIP] > > You can also have a look at the built-in component templates, since their > syntax is equivalent. They can be found in the `ui/src/components/core` folder. Go to `ui/src/components/custom` and open the Vue single-file components, i.e. the `.vue` files. These files contain comments that will help you get started. Try editing the provided templates, you should see changes reflected. You can get started by duplicating one of these examples. Make sure you add the new template to the entrypoint, as discussed below. ### Define entrypoint For custom component templates to be taken into account, they need to be accessible from the entrypoint. Edit `ui/src/components/custom/index.ts` to define which templates you wish to export and under which identifiers. ```ts theme={null} // Import the templates import BubbleMessage from "./BubbleMessage.vue"; import BubbleMessageAdvanced from "./BubbleMessageAdvanced.vue"; // Export an object with the ids and the templates as default export default { bubblemessage: BubbleMessage, bubblemessageadvanced: BubbleMessageAdvanced, }; ``` A single or multiple templates can be specified. Take into account that they will all be exported, and later imported, together. ## Bundling templates Execute `npm run custom.build` into `src/ui`, this will generate the output `.js` and `.css` files into `./custom_components_dist`. ```sh theme={null} # "build" builds the entire front-end # "custom.build" only builds the custom templates npm run custom.check # Optional: checks certain issues on custom components npm run custom.build ``` Collect the files from `./custom_components_dist` and pack them in a folder such as `my_custom_bubbles`. The folder containing the generated files, e.g. `my_custom_bubbles`, can now be placed in the `extensions/` folder of any Framework project. It'll be automatically detected during server startup. > [!TIP] > > The `custom.check` command is optional, but it's recommended to run it before building the custom components. It checks for common issues in the custom components, such as invalid key declaration, ... # Custom server Source: https://dev.writer.com/framework/custom-server Framework uses Uvicorn and serves the app in the root path i.e. `/`. If you need to use another ASGI-compatible server or fine-tune Uvicorn, you can easily do so. ## Configure webserver You can tune your server by adding a `server_setup.py` file to the root of your application, next to the `main.py` files. This file is executed before starting writer. It allows you to configure [authentication](./authentication.md), add your own routes and middlewares on FastAPI. ```python theme={null} # server_setup.py import typing import writer.serve if typing.TYPE_CHECKING: from fastapi import FastAPI # Returns the FastAPI application associated with the writer server. asgi_app: FastAPI = writer.serve.app @asgi_app.get("/probes/healthcheck") def hello(): return "1" ``` > [!WARNING] > > `server_setup.py` is disabled by default on edit mode. If you want to use in `edit` mode, you can launch `writer edit --enable-server-setup `. ## Implement custom server You can import `writer.serve` and use the function `get_asgi_app`. This returns an ASGI app created by FastAPI, which you can choose how to serve. The following code can serve as a starting point. You can save this code as `serve.py` and run it with `python serve.py`. ```py theme={null} import uvicorn import writer.serve app_path = "." # . for current working directory mode = "run" # run or edit asgi_app = writer.serve.get_asgi_app(app_path, mode) uvicorn.run(asgi_app, host="0.0.0.0", port=5328, log_level="warning", ws_max_size=writer.serve.MAX_WEBSOCKET_MESSAGE_SIZE) ``` Note the inclusion of the imported `ws_max_size` setting. This is important for normal functioning of the framework when dealing with bigger files. Fine-tuning Uvicorn allows you to set up SSL, configure proxy headers, etc, which can prove vital in complex deployments. If you want to disable server setup hook, you should use `enable_server_setup`: ```python theme={null} asgi_app = writer.serve.get_asgi_app(app_path, mode, enable_server_setup=False) ``` ## Multiple apps at once Framework is built using relative paths, so it can be served from any path. This allows multiple apps to be simultaneously served on different paths. The example below uses the `get_asgi_app` function to obtain two separate Framework apps, which are then mounted on different paths, `/app1` and `/app2`, of a FastAPI app. ```py theme={null} import uvicorn import writer.serve from fastapi import FastAPI, Response root_asgi_app = FastAPI(lifespan=writer.serve.lifespan) sub_asgi_app_1 = writer.serve.get_asgi_app("../app1", "run") sub_asgi_app_2 = writer.serve.get_asgi_app("../app2", "run") root_asgi_app.mount("/app1", sub_asgi_app_1) root_asgi_app.mount("/app2", sub_asgi_app_2) @root_asgi_app.get("/") async def init(): return Response("""

Welcome to the App Hub

""") uvicorn.run(root_asgi_app, host="0.0.0.0", port=5328, log_level="warning", ws_max_size=writer.serve.MAX_WEBSOCKET_MESSAGE_SIZE) ``` # Dataframe Source: https://dev.writer.com/framework/dataframe ## DataFrames If your application needs to present data as a table, it should use a **DataFrame**. DataFrames provide a simple way to present data in a grid format, require only a couple of lines of code to set up, and provide an interface that users expect from modern data applications. ![DataFrame showing a table of popular ice cream flavors](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/dataframe.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=6a47c39e70ee2ba1d70724612aeab66e) DataFrames built-in features that users expect, such as headers that can be clicked to change the sort order and resizable columns... ![DataFrame with arrows pointing to the re-sort and resizing features](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/dataframe_resort_resize.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=bb01cf0a041d758aec465676b5373e8b) ...and with the simple change of a parameter, you can enable features such as the Search field, which lets the user find the data they’re looking for (or filter out unwanted data), and the Download button, which downloads the data currently being displayed as a .csv file: ![DataFrame with arrows pointing to the Search field and Download button](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/dataframe_search_download.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=dcc25452bf0f4460182e4092119f1894) You can find the full list of DataFrame properties and fields on the [*DataFrame* component page](/components/dataframe). ### “DataFrame” has multiple meanings **Writer Framework has two objects with the name *DataFrame*:** 1. **UI DataFrame:** In Writer Framework's UI, "DataFrame" refers to a **_user interface component_** that displays data in rows and columns in a way similar to a spreadsheet or SQL table. 2. **Code Dataframe:** In code that you write for a Writer Framework application, `DataFrame` refers to a **_data structure_** that stores data in rows and columns in a way similar to a spreadsheet or SQL table. To present a data table in Writer Framework, you create a `DataFrame` data structure in your code and then bind it to a UI Dataframe. ## Displaying a static DataFrame A static DataFrame is one whose content does not change. The user can change its sort order, but the data within the DataFrame remains constant. **1. Create a DataFrame data structure** Writer Framework supports both [pandas](https://pandas.pydata.org/) and [Polars](https://pola.rs/) `DataFrame` data structures. Create a `DataFrame`, assign its value to a variable, then assign make that variable a value in the `state` dictionary: ```python pandas theme={null} import writer as wf import pandas as pd data = [ {"rank": 1, "flavor": "Vanilla", "favorite": 0.11}, {"rank": 2, "flavor": "Chocolate", "favorite": 0.1}, {"rank": 3, "flavor": "Cookies and cream", "favorite": 0.07}, {"rank": 4, "flavor": "Strawberry", "favorite": 0.06}, {"rank": 5, "flavor": "Chocolate chip", "favorite": 0.02}, ] df = pd.DataFrame(data) wf.init_state({ "mydf": df }) ``` ```python Polars theme={null} import writer as wf import polars as pl data = [ {"rank": 1, "flavor": "Vanilla", "favorite": 0.11}, {"rank": 2, "flavor": "Chocolate", "favorite": 0.1}, {"rank": 3, "flavor": "Cookies and cream", "favorite": 0.07}, {"rank": 4, "flavor": "Strawberry", "favorite": 0.06}, {"rank": 5, "flavor": "Chocolate chip", "favorite": 0.02}, ] df = pl.DataFrame(data) wf.init_state({ "mydf": df }) ``` The call to `wf.init_state()` adds the `DataFrame` to the application's `state` variable as the value of the `mydf` key. **2. Add a DataFrame component to the UI and bind it to the DataFrame data structure** Add a DataFrame UI component to the user interface, then set its **Data** property to `@{`*dataframe_key*`}`, where *dataframe_key* is the `state` variable key whose value refers to the `DataFrame` data structure. In the case of this example, `mydf` is the `state` variable key referring to the `DataFrame`, so set the **Data** property to `@{mydf}`. ![DataFrame for static table example with properties panel open](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/dataframe_static_table_1.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=a555186139ccc7397085b797044fafea) ## Displaying an editable DataFrame A editable DataFrame is one whose content can change. Like static DataFrames, editable DataFrames use the **DataFrame** UI component. Unlike static tables, the DataFrame UI component is bound to an instance of `EditableDataFrame`, a class provided by the Writer library. Changes to a `EditableDataFrame` object will be immediately reflected in the DataFrame UI component that it is bound to. **1. Create an EditableDataFrame data structure** An `EditableDataFrame` object can be instantiated from any of the following: 1. A pandas `DataFrame` 2. A Polars `DataFrame` 3. A list of dictionaries ```python pandas theme={null} import writer as wf import pandas as pd data = [ {"rank": 1, "flavor": "Vanilla", "favorite": 0.11}, {"rank": 2, "flavor": "Chocolate", "favorite": 0.1}, {"rank": 3, "flavor": "Cookies and cream", "favorite": 0.07}, {"rank": 4, "flavor": "Strawberry", "favorite": 0.06}, {"rank": 5, "flavor": "Chocolate chip", "favorite": 0.02}, ] df = pd.DataFrame(data) wf.init_state({ "mydf": wf.EditableDataFrame(df) }) ``` ```python Polars theme={null} import writer as wf import polars as pl data = [ {"rank": 1, "flavor": "Vanilla", "favorite": 0.11}, {"rank": 2, "flavor": "Chocolate", "favorite": 0.1}, {"rank": 3, "flavor": "Cookies and cream", "favorite": 0.07}, {"rank": 4, "flavor": "Strawberry", "favorite": 0.06}, {"rank": 5, "flavor": "Chocolate chip", "favorite": 0.02}, ] df = pl.DataFrame(data) wf.init_state({ "mydf": wf.EditableDataFrame(df) }) ``` ```python List of dictionaries theme={null} import writer as wf data = [ {"rank": 1, "flavor": "Vanilla", "favorite": 0.11}, {"rank": 2, "flavor": "Chocolate", "favorite": 0.1}, {"rank": 3, "flavor": "Cookies and cream", "favorite": 0.07}, {"rank": 4, "flavor": "Strawberry", "favorite": 0.06}, {"rank": 5, "flavor": "Chocolate chip", "favorite": 0.02}, ] wf.init_state({ "mydf": wf.EditableDataFrame(data) }) ``` The call to `wf.init_state()` adds the `DataFrame` to the application's `state` variable as the value of the `mydf` key. **2. Add a DataFrame component to the UI and bind it to the DataFrame data structure** Add a **DataFrame** component to the user interface, then set its **Data** property to `@{`*dataframe_key*`}`, where *dataframe_key* is the `state` variable key whose value refers to the `DataFrame` data structure. In the case of this example, `mydf` is the `state` variable key referring to the `DataFrame`, so set the **Data** property to `@{mydf}`. ![DataFrame for dynamic table example with properties panel open](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/dataframe_dynamic_table_1.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=de4fbba831aa1f320efe18b4d275f540) ## Updating an editable DataFrame Editable DataFrames are updated by updating the `EditableDataFrame` object they are bound to, which is done using `EditableDataFrame`'s methods. ### `record_add`: Add a new row `record_add()` adds a new row to an `EditableDataFrame`. It takes a dictionary with the following structure... ```python theme={null} {"record": new_row} ``` ...where `new_row` is a dictionary containing the data for the row to be added. In the code example above, you would add a new row to the DataFrame with the following code: ```python theme={null} state["mydf"].record_add({"record": {"rank": 6, "flavor": "Birthday cake", "favorite": 0.01}}) ``` ### `record`: Read the contents of a row `record()` returns a row in an `EditableDataFrame`. It takes an integer specifying the index of the row. In the code example above, you would retrieve the record at row 1 with the following code: ```python theme={null} record = state["mydf"].record(1) ``` ### `record_update`: Change an existing row `record_update()` replaces an existing row in an `EditableDataFrame` with a new one. It takes a dictionary with the following structure... ```python theme={null} { "record_index": index, "record": row_to_update } ``` ...where `index` is an integer specifying which row should be updated and `row_to_update` is a dictionary containing the updated row data. In the code example above, you would update the row at index 0 with the following code: ```python theme={null} state["mydf"].record_update({ "record_index": 0, "record": {"rank": 6, "flavor": "Bubble gum", "favorite": 0.08} }) ``` ### `record_remove`: Delete an existing row `record_remove()` removes an existing row from an `EditableDataFrame`. It takes a dictionary with the following structure... ```python theme={null} {"record_index": index} ``` ...where `index` is an integer specifying which row should be deleted. In the code example above, you would delete the row at index 2 with the following code: ```python theme={null} state["mydf"].record_remove({"record_index": 2}) ``` ## Enabling additional features The DataFrame component has these “always-on” features: 1. **Sorting:** Clicking a column header sorts the entire DataFrame based on that column's values. The first click sorts that DataFrame in ascending order, a second click changes it to descending order, and a third click restores the DataFrame to its original sort order. 2. **Column resizing:** Click and drag the dividing line on the right edge of a column header to adjust its width. DataFrames have other features that you need to activate, which are listed below. ### Search field To enable the Search field, select the DataFrame, open the Component settings panel, and set **Enable search** to **yes**. ![Enabling the Search field in a DataFrame](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/dataframe_enable_search.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=2421dd2b6c6367ee67a2f6ea3f723883) ### Download button To enable the Download button, select the DataFrame, open the Component settings panel, and set **Enable download** to **yes**. ![Enabling the Download button in a DataFrame](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/dataframe_enable_download.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=0ba0cae4796c848d91e54f366c189b32) # Deploy with Docker Source: https://dev.writer.com/framework/deploy-with-docker > [!TIP] > > To deploy on the Writer cloud see instructions [here](/framework/quickstart#deploying-on-writer-cloud). You can use Docker to deploy Framework anywhere. If you're an experienced Docker user, you may want to go straight to the provided Dockerfile. ## Creating a Docker image **1. Verify docker installation** Make sure you have Docker installed on your system. **2. Navigate to your app's folder** Open a terminal and navigate to your app’s folder. **3. Set up Python environment** Create a `pyproject.toml` file using `poetry init` and install `writer` using `poetry add writer`. A Dockerfile is a file with instructions that tell Docker how to build your image. It must be named `Dockerfile`. You can use the following as-is, or as a starting point. It should be saved in your app's folder, together with `main.py` and `.wf/`. ```docker theme={null} FROM python:3.10-bullseye RUN apt-get update -y && mkdir /app RUN apt-get install build-essential cmake python3-dev -y COPY . /app WORKDIR /app RUN pip3 install poetry RUN poetry config virtualenvs.create false RUN poetry install --only main ENTRYPOINT [ "writer", "run" ] EXPOSE 8080 CMD [ ".", "--port", "8080", "--host", "0.0.0.0" ] ``` > [!NOTE] > > This Dockerfile is just a guideline. > It uses an official Python slim base image with a multistage build to reduce the size of the built image. > If you're a Docker expert, feel free to work on your own `Dockerfile`. Framework is, after all, a standard Python package. To build the image, use `docker build . -t ` followed by an image tag, which you're free to choose and will locally identify your image. ```sh theme={null} docker build . -t my_framework_app ``` > [!WARNING] > > By default, Docker builds images in the architecture it's being run on. If you're working with an ARM computer, such as a Mac M2 or a Raspberry Pi, Docker will build an ARM image. Most cloud services will only accept x86 images. You can use another computer (or virtual machine) to build the image, or you can use [Docker buildx](https://docs.docker.com/build/building/multi-platform/). ## Publishing your Docker image Once your Docker image has been built, you can publish it to a registry. This is a place where Docker images are stored and made available to other services. We recommend using Docker Hub; it has a generous free tier, it's very easy to set up and it's widely supported. However, you can choose to use another service such as Azure Container Registry. To use Docker Hub, you'll need to sign up for an account. You can push your image using the following commands. ```sh theme={null} # Login to Docker Hub docker login # Push the image # Replace "my_writer_app" for the tag you've previously chosen # Replace "my_user" for your user on Docker Hub docker tag my_writer_app:latest my_user/my_writer_app:latest docker push my_user/my_writer_app:latest ``` If your image is public, anyone can now run the following command and start the app. It's important to bind the port to a port in the host machine. The command below binds port 8080 in the Docker image to port 8080 in the host. ```sh theme={null} docker run -p 8080:8080 my_user/my_framework_app ``` Go on your browser to [http://localhost:8080](http://localhost:8080) to check everything is working as expected. ## Deploying your Docker image As mentioned earlier, once the image is a registry, it can be spun up by others. After trying a few options, we recommend using Google Cloud Run. Its free tier is generous and SSL works out of the box. ![Run and Share - Google Cloud Run](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/deploy-with-docker.google-cloud-run.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=af8ba51ab1ea3dbdaf59274e7e6b2274) Cloud Run can be configured in just one page. It takes the image from a registry and makes it available via a URL, with SSL enabled by default. We recommend the following settings: > [accordion] Instance specifications > > Minimum 0 instances, maximum 4 instances. This range is suitable unless your app needs to serve several thousands of users. > [accordion] Connection settings > > Set the request timeout to the maximum allowed and enable Session Affinity. This ensures that WebSocket connections are not unnecessarily dropped. > [accordion] Resource allocation > > Allocate 2GB of memory and 2 vCPUs. This configuration will likely be enough to comfortably run a simple app. However, you can probably manage with much less—512MB of memory and 1 vCPU—if your app isn’t too demanding and you don’t expect much traffic. # Event handlers Source: https://dev.writer.com/framework/event-handlers Events originate in the front-end, for example, when a user clicks a *Button* component. Using the Builder, these events can be linked to event handlers. ## Plain Python functions Event handlers are Python functions accessible from `main.py`. They can be defined in that same file or imported. No decorators or special syntax are required. ```py theme={null} # This event handler will add an entry to the log def handle_click() print("Hello") ``` To specify that a function isn't an event handler and should remain hidden to the front-end, prefix it with a `_` (underscore). ```py theme={null} # This function won't be visible in the front-end # because its name starts with an underscore def _reticulate(splines): r_splines = np.random.normal(size=(splines,100)) return r_splines ``` ### External handlers If your `main.py` file has become cluttered with too many handler functions, you can organize them more effectively using the `init_handlers` method. This method allows you to register handler functions from other modules. You can pass a single imported module or a list of modules to the init_handlers method to register multiple handlers simultaneously: ```py one_handler theme={null} # my_app/my_handlers_module.py def increment(state): state["counter"] += 1 ``` ```py init_handlers one module theme={null} # my_app/main.py import writer as wf import my_handlers_module wf.init_handlers(my_handlers_module) # Register all functions from the module as handlers; # this makes `increment` handler accessible on front-end ``` ```py init_handlers many modules theme={null} # my_app/main.py import writer as wf import handler_module_one import handler_module_two wf.init_handlers([handler_module_one, handler_module_two]) ``` > [!WARNING] > > Each function inside a module is attempted to be registered as a handler. Make sure to use `_` prefix as described [before](#plain-python-functions) to prevent exposing unwanted functions to front-end. You can also call `init_handlers` within other modules, which allows for a sequence of registrations: ```py another_handlers_module theme={null} # my_app/another_handlers_module.py def decrement(state): state["counter"] -= 1 ``` ```py register_additional_handlers theme={null} # my_app/my_handlers_module.py import writer as wf import another_handlers_module wf.init_handlers(another_handlers_module) # Makes `decrement` handler accessible on front-end ... ``` ```py my_handlers_module theme={null} # my_app/main.py import writer as wf import my_handlers_module ... ``` Note that for this "chain" to work, you need to import the final module in the sequence into `main.py`. ## Mutating state In most cases, event handlers will modify the application state. State can be accessed by including the `state` argument in the handler, which will provide you with a `WriterState` object for the session that invoked the handler. Elements of state can be reached using the square brackets syntax `state["my_element"]`. Accessing keys that don't exist will return `None`. ```py theme={null} def handle_click(state): state["counter"] += 1 ``` The handler above receives the application state for the relevant session and mutates it. For example, if Bob's counter was 4, and he clicks on a *Button* linked to `handle_click`, his new counter value will be 5. Other sessions remain unaffected. ## Mutation detection > [!WARNING] > > Mutations are detected via assignment. > Make sure you perform an assignment on the state element you're mutating, for the mutation to be detected. When communicating with the front-end, Framework only sends state elements that have mutated. To detect which elements have mutated, it relies on assignment (via operators such as `=`, `+=`, etc). This is because Python doesn't offer a performant, reliable mechanism to detect mutations. See the two examples below. ```python hande_click theme={null} def handle_click(state): state["my_df"].sample(frac=1, random_state=random.seed()) # The self-assignment is necessary when mutating # an existing object directly on state state["my_df"] = state["my_df"] ``` ```python hande_click_cleaner theme={null} # The following cleaner code also works as it relies on assignment def hande_click_cleaner(state): my_df = state["my_df"] my_df.sample(frac=1, random_state=random.seed()) state["my_df"] = my_df # State assignmnet ``` ## Mutation event You can subscribe to mutations on a specific key in the state. This is useful when you want to trigger a function every time a specific key is mutated. ```python simple subscription theme={null} import writer as wf def _increment_counter(state): state['my_counter'] += 1 state = wf.init_state({"a": 1, "my_counter": 0}) state.subscribe_mutation('a', _increment_counter) state['a'] = 2 # trigger _increment_counter mutation ``` ```python multiple subscriptions theme={null} import writer as wf def _increment_counter(state): state['my_counter'] += 1 state = wf.init_state({ 'title': 'Hello', 'app': {'title', 'Writer Framework'}, 'my_counter': 0} ) state.subscribe_mutation(['title', 'app.title'], _increment_counter) # subscribe to multiple keys state['title'] = "Hello Pigeon" # trigger _increment_counter mutation ``` ```python trigger event handler theme={null} import writer as wf def _increment_counter(state, context: dict, payload: dict, session: dict, ui: WriterUIManager): if context['event'] == 'mutation' and context['mutation'] == 'a': if payload['previous_value'] > payload['new_value']: state['my_counter'] += 1 state = wf.init_state({"a": 1, "my_counter": 0}) state.subscribe_mutation('a', _increment_counter) state['a'] = 2 # increment my_counter state['a'] = 3 # increment my_counter state['a'] = 2 # do nothing ``` > [!TIP] > > `subscribe_mutation` is compatible with event handler signature. It will accept all the arguments > of the event handler (`context`, `payload`, ...). ## Receiving a payload Several events include additional data, known as the event's payload. The event handler can receive that data using the `payload` argument. For example, the `wf-change` event in a *Text Input* component is triggered every time the value changes. As a payload, it includes the new value. ```py theme={null} def handle_input_change(state, payload): state["value"] = payload ``` The content of the payload will vary depending on the event. For example, when a user takes a photo with a *Webcam Capture*, the picture they took is sent across as a PNG image. ```py theme={null} def handle_webcam_capture(payload): image_file = payload with open(f"picture.png", "wb") as file_handle: file_handle.write(image_file) ``` Handling different payloads across events can be challenging, especially since the shape of the payload may vary. To simplify this process, the Builder provides stub code that can help you get started with writing an event handler. You can access it by clicking the icon located next to the event when configuring the component's settings. This feature can help you quickly understand the structure of the payload and start writing the appropriate code to handle it. ## Globals You can use globals and module attributes, just as you would in a standard Python script. This is very convenient for storing a single copy of resource-intensive object. ```py theme={null} my_ai = CatIdentifierAI() def evaluate(state, payload): result = my_ai.process(payload) state["is_a_cat"] = result ``` Take into account that globals apply to all users. If you need to store data that's only relevant to a particular user, use application state. ## Middlewares Middlewares are functions that run before and after every event handler. They can be used to perform tasks such as logging, error handling, session management, or modifying the state. ```py theme={null} import writer as wf @wf.middleware() def middleware_before(state, payload, context): print("Middleware before event handler") state['running'] += 1 yield print("Middleware after event handler") state['running'] -= 1 ``` A middleware receives the same parameters as an event handler. A middleware can be used to handle exceptions that happens in event handlers. ```py theme={null} import writer as wf @wf.middleware() def middleware_before(state): try: yield except Exception as e: state['error_counter'] += 1 state['last_error'] = str() finally: pass ``` ## Standard output The standard output of an app is captured and shown in the code editor's log. You can use the standard `print` function to output results. ```py theme={null} # Shown every time the app starts print("Hello world") def payload_inspector(state, payload): # Shown every time the event handler is executed print("Payload: " + repr(payload)) ``` ## Execution flow Event handlers run in a thread pool and are non-blocking. Each event is processed independently from each other. State mutations are sent to the front-end after the function has finished executing. The code in `handle_fast` will accumulate all mutations and send to the front-end after the function returns. For long-running tasks, Framework will periodically check state and provide partial updates to the user. ```py handle_fast theme={null} def handle_fast(state): state["text"] = "Hello" state["x"] += 3 state["y"] += 2 ``` ```py handle slowly theme={null} # The code below will set `message` to "Loading...", then to "Completed". def handle_slowly(state): state["message"] = "Loading..." import time time.sleep(5) state["message"] = "Completed" ``` ## Asynchronous event handlers Framework supports asynchronous event handlers, allowing for non-blocking I/O operations directly within event handlers. This is particularly useful for tasks such as fetching data from a database, making HTTP requests, or performing any other I/O bound operation that can benefit from asynchronous execution. ### Defining an asynchronous handler An asynchronous event handler is defined with the standard `async` keyword syntax. ```py theme={null} # An asynchronous event handler for performing an I/O bound operation async def handle_async_click(state): data = await fetch_data() state["data"] = data ``` In the example above, `fetch_data()` is an asynchronous function that retrieves data, potentially from a remote source. The `await` keyword is used to wait for the operation to complete without blocking the main thread, allowing other tasks to run concurrently. ### Awaitable objects You can use any awaitable object within an async event handler. This includes the output of any function defined with `async def`, or objects with an `__await__` method. This makes it easy to integrate with asynchronous libraries and frameworks. ## Context The `context` argument provides additional information about the event. The context provide the id of component that trigger the event in `target` field. ```py theme={null} def handle_click(state, context: dict): last_source_of_click = context['target'] state["last_source_of_click"] = last_source_of_click ``` The context provides the event triggered in the `event` field. ```py theme={null} def handle_click(state, context: dict): event_type = context['event'] if event_type == 'click': state["last_event"] = 'Click' ``` The repeater components have additional fields in the context, such as defined in `keyVariable` and `valueVariable`. ```py theme={null} def handle_repeater_click(state, context: dict): key = context['keyVariable'] state['repeater_content'][key]['last_action'] = 'Clicked' ``` More information in [Repeater chapter](/framework/repeater) # Frontend scripts Source: https://dev.writer.com/framework/frontend-scripts Framework can import custom JavaScript/ES6 modules from the front-end. Module functions can be triggered from the back-end. ## Importing an ES6 module Similarly to [stylesheets](/framework/stylesheets), front-end scripts are imported via Framework's `mail` capability. This allows you to trigger an import for all or specific sessions at any time during runtime. When the `import_frontend_module` method is called, this triggers a dynamic [import()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) call in the front-end. The `import_frontend_module` method takes the `module_key` and `specifier` arguments. The `module_key` is an identifier used to store the reference to the module, which will be used later to call the module's functions. The `specifier` is the path to the module, such as `/static/mymodule.js`. It needs to be available to the front-end, so storing in the `/static/` folder is recommended. The following code imports a module during event handling. ```py theme={null} def handle_click(state): state.import_frontend_module("my_script", "/static/mymodule.js") ``` If you want the module to be imported during initialisation, use the initial state. ```py theme={null} initial_state = wf.init_state({ "counter": 1 }) initial_state.import_frontend_module("my_script", "/static/mymodule.js") ``` > [!NOTE] > > Use versions to avoid caching. Similarly to stylesheets, your browser may cache modules, preventing updates from being reflected. Append a querystring to invalidate the cache, e.g. use `/static/script.js?3`. ## Writing a module The module should be a standard ES6 module and export at least one function, enabling it to be triggered from the back-end. As per JavaScript development best practices, modules should have no side effects. An example of a module is shown below. ```js theme={null} let i = 0; export function sendAlert(personName) { i++; alert(`${personName}, you've been alerted. This is alert ${i}.`); } ``` ## Calling a function Once the module is imported, functions can be called from the back-end using the `call_frontend_function` method of state. This function takes three arguments. The first, `module_key` is the identifier used to import the module. The second, `function_name` is the name of the exported front-end function. The third, `args` is a `List` containing the arguments for the call. The following event handler triggers the front-end function defined in the section above. ```py theme={null} def handle_click(state): state.call_frontend_function("mymodule", "sendAlert", ["Bob"]) ``` ## Import a JS script Framework can also import and run JavaScript scripts directly, for their side effects. These are imported via the report's `import_script` method. This method takes two arguments. The first, `script_key` is the identifier used to import the script. The second, `path` is the path to the file. The specified path must be available to the front-end, so storing it in your application's `./static` folder is recommended. ```py theme={null} initial_state = wf.init_state({ "counter": 1 }) initial_state.import_script("my_script", "/static/script.js") ``` > [!WARNING] > > Prefer ES6 modules: importing scripts is useful to import libraries that don't support ES6 modules. When possible, use ES6 modules. The `import_script` syntax is only used for side effects; you'll only be able to call functions from the back-end using modules that have been previously imported via `import_frontend_module`. ## Importing a script from a URL Framework can also import scripts and stylesheets from URLs. This is useful for importing libraries from CDNs. The `import_script` and `import_stylesheet` methods take a `url` argument, which is the URL to the script or stylesheet. ```python theme={null} initial_state = wf.init_state({ "my_app": { "title": "My App" }, }) initial_state.import_script("lodash", "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.js") ``` ## Frontend core > [!WARNING] > > Effectively using Framework's core can be challenging and will likely entail reading its [source code](https://github.com/writer/writer-framework/blob/master/src/ui/src/core/index.ts). Furthermore, it's considered an internal capability rather than a public API, so it may unexpectedly change between releases. You can access Framework's front-end core via `globalThis.core`, unlocking all sorts of functionality. Notably, you can use `getUserState()` to get values from state. ```js theme={null} export function alertHueRotationValue() { const state = globalThis.core.userState.value. console.log("State is", state); } ``` # Handling inputs Source: https://dev.writer.com/framework/handling-inputs There are two, complementary, ways to handle inputs in Framework: via event handlers and via binding. ## Event handlers Input components have *change* events that are dispatched when the value changes. The new value is provided as a payload in the event handler. Change events have slightly different names across components, reflecting the payloads they provide. For example, *Number Input* and *Slider Input* use the event `wf-number-change` while *Text Input* and *Text Area Input* use the generic `wf-change`. As discussed in the [Event handlers](/framework/event-handlers) section, the payload can be accessed via the `payload` argument in the event handler. ```py theme={null} # This event handler takes the payload and assigns it # to the state element "name" def handle_input_change(state, payload): state["name"] = payload ``` ## Two-way bindings Writing event handlers for every input component can be tedious. In most cases, you'll only need to update a single element of state when the value changes, akin to the example above. You can achieve this by binding a component to a state element. Bindings automatically handle the *change* event for the component and set the value of the state element to the payload. Furthermore, bindings are two-way. If the state element is updated from the back-end, the front-end component is updated to reflect the new value. As mentioned in the [Builder basics](/framework/builder-basics) section of the guide, bindings can be configured in the component settings. ![Repeater example](https://mintcdn.com/writer/eBiCs3I5_-mSTcT-/framework/images/handling-inputs.binding.png?fit=max\&auto=format\&n=eBiCs3I5_-mSTcT-\&q=85\&s=bcb3fe9fc8d61fe1f7302f98a35b4099) The binding above establishes a two-way link between the component and the state element `name`. If `name` changes in the back-end, the component changes. If the component changes, the value of `name` changes. ## Using events and bindings simultaneously Bindings can be used together with events. This is useful for triggering recalculations or applying dynamic filters. For example, you may want to have three *Number Input* components bound to `a`, `b` and `c` and display a value `n`. This easily done by binding the components and linking the same recalculation event handler to all three components. ```py theme={null} def recalculate(state): state["n"] = state["a"]*state["b"]*state["c"] ``` ## Handling inputs safely Framework automatically sanitises the payloads it provides for its built-in events, those that start with `wf-`. For example, if a *Dropdown Input* component lists options `high` and `low`, you're guaranteed you won't get a value like `"Robert'); DROP TABLE students;--"` when handling `wf-option-change`. You'll get `"high"`, `"low"` or `None`. > [!WARNING] > > Inputs are sanitised, but you should still be careful > > As with any application, it's important to be familiar with the risks associated with handling user input, especially SQL injections. If you're using any custom HTML and mixing it with user generated content, make sure you understand XSS. ## Creating forms Input components can be combined with *Message* and *Button* components to create forms with messages, indicating whether the submission was successful. ![Form example](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/handling-inputs.form.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=d60aee2c6edda91f55808ee2d678c288) # Writer Framework Source: https://dev.writer.com/framework/introduction The Writer Framework lets you build feature-rich apps by using a drag-and-drop visual editor called **the Builder** and writing the back-end code in Python. It's fast and flexible, with clean, easy-to-test syntax. It provides separation of concerns between UI and business logic, enabling more complex apps. ![Framework Builder screenshot](https://mintcdn.com/writer/mFPGVlLcGxKIh_Y1/framework/public/builder.png?fit=max\&auto=format\&n=mFPGVlLcGxKIh_Y1\&q=85\&s=9ad9be8f3da7b87fca947402b68986b7) Build AI apps with the Writer Framework when: 1. You need to incorporate external data sources, such as external APIs 2. You have complex user input that requires custom logic, such as conditions that trigger the use of different prompts 3. You want to quickly analyze and visualize data using an LLM The Writer Framework offers: > [accordion] Easily-testable Python functions > > Define event handlers as plain Python functions. > > ```python theme={null} > def handle_text_update(state): > state["text"] = "Updated text" > > writer.init_state({ > "text": "Initial text" > }) > ``` > [accordion] Visual editor > > Link the event handler and state to the UI seamlessly. > [accordion] Standard Python packages > > Install with a simple pip command. > [accordion] Version control > > Save user interfaces as JSON to be version controlled with the rest of the app. > [accordion] Flexible editing > > Use your local code editor with instant refreshes or the provided web-based editor. Edit the UI while your app is running without needing to click “Preview.” > [accordion] Minimal overhead > > Event handling adds only 1-2ms to your Python code. > [accordion] Real-time synchronization > > Use WebSockets to synchronize front-end and back-end states. > [accordion] Efficient execution > > Non-blocking by default, with asynchronous event handling in a dedicated thread pool. > [accordion] Customizable elements > > No CSS required for customization like shadows, button icons, and background colors. > [accordion] HTML integration > > Include HTML elements with custom CSS using the HTML Element component, which can serve as containers for built-in components. To get started, head to [Quickstart](/framework/quickstart) or our tutorials: > [card] [Social post generator](/framework/social-post-generator) > > Generate multiple social media posts in a click of button using our social media generator. > [card] [Chat assistant](/framework/chat-assistant) > > Using Knowledge Graph, our graph-based RAG solution, you can build chat assistants to quickly ask questions using your data sources. > [card] [Product description generator](/framework/product-description-generator) > > Build real-time digital shelves for hundreds of products that are automatically customized for different e-retailers. # Page routes Source: https://dev.writer.com/framework/page-routes Framework apps can have multiple pages, with parametrised routes. Pages can be switched from the front-end or the back-end. ## Basic navigation To enable navigation between *Page* components, they must have a key assigned. This can be set up from the component's settings. Once a key is set up, the page will be accessible at `/#my_page_key`. ### Frontend-triggered page changes For basic page changes, assign a "Go to page" action to an event handler. For example, if you want to change to page `my_page_key` when a *Button* is clicked, go to the button's settings and under the `click` event select `Go to page "my_page_key"`. ### Backend-triggered page changes Trigger a page change from the back-end using the `set_page` method of state. ```py theme={null} # This event handler sends the user to a different page # depending on time of the day def handle_click(state): from datetime import datetime now = datetime.now() if now.hour >= 18: state.set_page("fun_work_page") else: state.set_page("work_work_page") ``` ## Routes with parameters You may want to share a URL that links directly to a specific resource within your app. For example, to a specific location or product. You can do so by specifying parameters in the URL, known as route vars. Framework URLs contain the page key, followed by the route vars and their values. For example, `/#detailPage/product_id=32&country=AR`. ### Adding vars to the URL from the back-end You can set up variables that are displayed in the URL by passing a dictionary to the `set_route_vars` state method. Use `None` to clear specific keys. ```py theme={null} # The following code will set the value of product_id # to the value of the "product" state element def change_route_vars(state): state.set_route_vars({ "product_id": state["product"] }) ``` ### Retrieving the values Framework uses the hash portion of the URL to store page and variable data, so even when switching pages or changing variables, the page doesn't reload. To monitor changes to the active URL, set up an event handler for `wf-hashchange` in the *Root* component. ```py theme={null} # The following event handler reads the product_id route var, # then assigns its value to the "product" state element. def handle_hash_change(state, payload): route_vars = payload.get("route_vars") if not route_vars: return state["product"] = route_vars.get("product_id") ``` # Product description generator Source: https://dev.writer.com/framework/product-description-generator In this tutorial, you'll use the Writer Framework to build a Saturn Snacks product description generator for a variety of food outlets. After adding the initial functionality of the app, you'll also extend the app to include a chart of SEO keyword analysis and the ability for users to add their own food outlet. ![Finished application](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/product_desciption/pd_gen_1.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=7a650f72a50ecfe26f26954850752c7c) ## Setting up your project ### Creating a Writer app and getting your API key From the Home screen, click on **Build an app**. ![Writer home screen](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/product_desciption/pd_gen_2.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=8982373a5960f4538f99cee7560e3b65) Select Framework as the app type you’d like to create, enabling you to generate keys and build your app with the Writer Framework. ![App type selection](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/product_desciption/pd_gen_3.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=ca942a84ade3518427b5ccbc58a12f4f) On the next screen, you can edit your Writer application name in the upper left. Underneath “Authenticate with an API key,” click on “Reveal” to see and copy your API key. ### Creating the application Next, open your terminal and navigate to the directory where you want to create your application directory. **1. Set the API key environment variable** To pass your API key to the Writer Framework, you'll need to set an environment variable called `WRITER_API_KEY`. Here’s how you can set this variable in your terminal session: ```sh On macOS/Linux theme={null} export WRITER_API_KEY=[key] ``` ```sh On Windows theme={null} set WRITER_API_KEY=[key] ``` **2. Create the application** Run the following command to create your application. Replace `product-description-app` with your desired project name and `pdg-tutorial` with the template you wish to use: ``` writer create product-description-app --template=pdg-tutorial ``` This command sets up a new project called `product-description-app` in the specified directory using a template designed for this tutorial. **3. Edit your project** To edit your project, run the below commands. This will bring up the console, where Framework-wide messages and errors will appear, including logs from the API. By default, the Writer Framework Builder is accessible at `localhost:4005`. If that port is in use, you can specify a different port. Open this address in your browser to view your default application setup. ```bash Standard port theme={null} writer edit product-description-app ``` ```bash Custom port theme={null} writer edit product-description-app --port=3007 ``` ## Introduction to the application setup When you first start up the application, you're going to see two main layout items provided by the template: 1. A Header component with the name of the application 2. A Column container that'll house most of the UI of the app The left column includes a form that has three text inputs and a button. These three text inputs are bound to corresponding state elements. The right column contains a Message component for loading and status messages, as well as an empty Tab container which you'll use to display the product descriptions of the various outlets. ### Code overview Looking at the code in `main.py`, you'll see that the template already imported the Writer Framework, the AI module, and the product description prompts that you'll use throughout this tutorial. ```python theme={null} import writer as wf import writer.ai from prompts import base_prompts, user_prompt, seo_keywords ``` The prompts are stored in a separate file called `prompts.py`. You are welcome to open this project in the IDE of your choice and modify the prompts however you wish. However, you don't need to make any changes to this file to follow this tutorial. You'll also see the state initialization: ```python theme={null} wf.init_state({ "form": { "title": "", "description": "", "keywords": "" }, "message": "Fill in the inputs and click \"Generate\" to get started.", }) ``` The form elements and the message have been initialized as strings. You'll add to this state dictionary throughout the tutorial. ## Implementing the Product description generator Your first goal is to generate product descriptions for the various food outlets, with each outlet appearing as a tab to the right of the form. ![Finished product description tabs](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/product_desciption/pd_gen_4.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=fdcee7cedc90faff3147219526a74da7) ### Setting up the code First, integrate new functionality into your code for generating product descriptions. **1. Add a private helper method** Paste the following method on line 5 after all of the imports to create a helper function for generating product descriptions: ```python theme={null} def _generate_product_description(base_prompt, product_info): prompt = base_prompt.format(**product_info) description = writer.ai.complete(prompt) return description ``` This function, `_generate_product_description`, accepts a base prompt and the product information from a form on the page. The underscore at the beginning of its name indicates that it's a private method not exposed to the UI. **2. Initialize additional state elements** Update the `wf.init_state()` to include a `product_description` dictionary with visibility control and outlets for descriptions: ```python theme={null} wf.init_state({ "form": { "title": "", "description": "", "keywords": "" }, "message": "Fill in the inputs and click \"Generate\" to get started.", "product_descriptions": { "visible": False, "outlets": {} } }) ``` This setup includes a variable `visible` to control whether product description tabs are shown or hidden, and an empty dictionary `outlets` for storing descriptions. **3. Add a button click handler** Paste the following method beneath `_generate_product_description` to handle button clicks and generate descriptions: ```python theme={null} def handle_click(state): state["product_descriptions"]["visible"] = False # Loop through all the base prompts to generate versions tailored to each outlet for outlet, base_prompt in base_prompts.items(): state["message"] = f"% Generating product description for {outlet}..." product_description = _generate_product_description(base_prompt, state["form"].to_dict()) state["product_descriptions"]["outlets"][outlet] = product_description state["product_descriptions"]["visible"] = True state["message"] = "" ``` This handler will loop through each imported base prompt, format it with the form information, and pass it to the helper method. The handler also manages UI interactions, such as displaying and hiding product descriptions and managing loading messages. ### Setting up the user interface You can now set up the UI to iterate over the product descriptions dictionary and create tabs. Begin by opening the User Interface. **1. Add and configure the Repeater component** In the toolkit, drag a Repeater component from the Other section into the empty Tab Container. Click on the Repeater component to open its component settings. Under Properties, add `@{product_descriptions.outlets}` as the Repeater object to be used for repeating the child components. Replace the default “Key variable name” with `itemId`. You can leave “Value variable name” as `item`. ![Repeater settings](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/product_desciption/pd_gen_5.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=fc355793aa67411f6a538a293c43b411) **2. Add and configure the Tab component** From the Layout section of the toolkit, drag a Tab component into the Repeater. Click on the Tab to bring up the component settings and add `@{itemId}` to the Name property to display the outlet name on the tab. ![Tab settings](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/product_desciption/pd_gen_6.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=b52573eaafb4307107563db4eaf73128) **3. Add and configure the Text component** Drag a Text component from the Content section of the Toolkit into the Tab. Click on the Text component to open the Component settings and set the Text property to `@{item}`. You may also choose to set “Use Markdown” to “yes.” ![Text settings](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/product_desciption/pd_gen_7.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=51935abb3a9f642cfd11e0966936c602) **4. Control the visibility of the Tab container** Click on the Tab container to bring up its Component settings. Scroll to the bottom and, under Visibility, click “Custom” and add `product_descriptions.visible` to the Visibility value input. ![Tab container visibility settings](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/product_desciption/pd_gen_8.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=07d61f8ca1ac93e21cf12561cfb07481) **5. Wire up the form with the Generate button** Click on the Generate button inside the form to bring up its Component settings. In the Events section, select `handle_click` for the `wf-click` event. ![Button settings](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/product_desciption/pd_gen_9.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=2732d5fb788b351d640f6f34676e76f3) **6. Preview and test the application** Click **Preview** in the top toolbar, enter some test data, and click the **Generate** button. You should see a loading message, as well as three example food outlets displayed in the tabs. The loading message should disappear when everything is loaded, and the tab should remain visible once the data has loaded. Great work! ## Expanding the application: SEO keyword analysis You can expand on this application by adding a chart that displays the top ten SEO keywords present in the product descriptions. ### Updating the code To do this, back in the code, first add the following helper function underneath your ` _generate_product_description` helper method: ```python theme={null} def _generate_seo_keywords(outlets): combined_descriptions = "\n".join(f"{key}: {value}" for key, value in outlets.items()) # Generate the prompt with the provided descriptions prompt = seo_keywords.format(descriptions=combined_descriptions) # Strip out whitespace and backticks from the response return writer.ai.complete(prompt).strip(" `\n") ``` This method concatenates all of the product descriptions and incorporates them into a prompt in `prompts.py`. It then sends the formatted prompt to the Palmyra LLM using the `complete` method. The prompt not only analyzes the descriptions for SEO keywords, but also outputs a [Plotly.js](/components/plotlygraph) schema object that you can use directly with a Plotly graph component. With the helper method in place, you can now update the click handler for the button. On line 27, add the following code before the product description visibility is set: ```python theme={null} # Create the SEO analysis state["message"] = "Analyzing SEO keywords..." outlets = state["product_descriptions"]["outlets"] state["seo_analysis"] = _generate_seo_keywords(outlets) ``` This code sets the loading message and passes all of the product descriptions to the SEO keyword helper method. ### Adding SEO analysis to the UI To update the UI to display this chart, first drag a new tab from the Layout section of the toolkit into the Tab container. This tab should not be inside of the Repeater, but can be either before or after it. Click on the tab to open the component settings, and change the name to “SEO Analysis.” If you'd like, you can also set the Visibility to “Custom” and set `seo_analysis` as the visibility value. ![SEO Tab](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/product_desciption/pd_gen_10.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=67e6e702fc5c59121a6a5b32deb02bad) To display the chart, drag a Plotly graph component from the Content section of the toolkit into your new tab. Click on the component to bring up the component settings. The Plotly graph component accepts a graph specification. Add `@{seo_analysis}` to pass the LLM-generated graph specification to the component. Click preview, add some data to the form, and click generate. You should see a new SEO analysis tab appear with a nicely formatted and labeled chart. ![SEO analysis tab and chart](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/product_desciption/pd_gen_11.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=46c9e35d8235fa33e8a5637175275b67) ## Extending the application: user-added outlet Finally, you can extend this application even further by allowing users to add their own custom food outlet and derive a new description from a custom prompt. ### Adding the new form Start by building the UI for this new form. From the Layout section of the Toolkit, drag a new Section component into the column where the current form is and drop it above or below it. Click on the Section and change the Name to “Add an outlet.” To create the inputs for the form, drag a Text Input and a Number Input from the Input section of the Toolkit into the newly created section. Click on the Text Input component to change the Label to “Outlet name.” Click on the Number Input and change the label to “Character max.” Finally, add a Button from the Other section of the toolkit to the bottom of the new section. Click on the button and change the text to “Add and Generate.” You can also add `laps` or another [Material Symbols](https://fonts.google.com/icons) ID to the Icon input if you wish. ![Add outlet form](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/product_desciption/pd_gen_12.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=239f082ca68d09a76779f48ccd55e783) ### Updating the code In the code, you next need to add corresponding state elements for the new form components to `wf.init_state()`. Add the following to the state dictionary: ```python theme={null} "outlet_form": { "name": "", "character_max": "", }, ``` Don't forget to check your commas when adding to the state dictionary. Your completed state should look like this: ```python theme={null} wf.init_state({ "form": { "title": "", "description": "", "keywords": "" }, "outlet_form": { "name": "", "character_max": "", }, "message": "Fill in the inputs and click \"Generate\" to get started.", "product_descriptions": { "visible": False, "outlets": {} } }) ``` The `outlet_form` state elements will bind to the form elements. Next, add the click handler for the new button. Copy and paste this `handle_add_outlet` method into the code under the `handle_click` method: ```python theme={null} def handle_add_outlet(state): # Create a new base prompt for the new outlet new_outlet_name = state["outlet_form"]["name"] product_info = {**state["outlet_form"].to_dict(), **state["form"].to_dict()} base_prompt = user_prompt.format(**product_info) # Add the new base prompt to the base_prompts dictionary base_prompts[new_outlet_name] = base_prompt # Generate the product description for the new outlet state["message"] = f"% Generating product description for {new_outlet_name}..." product_description = _generate_product_description(base_prompt, state["form"].to_dict()) state["product_descriptions"]["outlets"][new_outlet_name] = product_description # Update the SEO analysis state["message"] = "Updating SEO analysis..." outlets = state["product_descriptions"]["outlets"] state["seo_analysis"] = _generate_seo_keywords(outlets) state["message"] = "" ``` This method formats the input from both forms into the imported `user_prompt` and adds the formatted prompt to the `base_prompts` dictionary. It then generates the product description for the new food outlet, updates the SEO analysis, and clears the status message. ### Binding the elements and handler to the UI Finalize your setup by binding the state elements and configuring the click handler to the UI components. **1. Bind text inputs to state elements** * **Outlet Name**: Click on the “Outlet name” Text Input component. In the Binding section of the component settings, set the state element to `outlet_form.name`. * **Character Max**: Move to the “Character max” Text Input. Update its state element binding to `outlet_form.character_max`. **2. Assign click handler to button** Click on the **Add and Generate** Button. In the Events section of the component settings, select `handle_add_outlet` for the `wf-click` event. **3. Configure form visibility** To conditionally display the form based on whether descriptions have been generated, click on the Section containing the form. In the Visibility section, choose “Custom” and set `product_descriptions.visible` as the “Visibility value.” ### Testing the finished product To see the result of your hard work, click **Preview** in the top toolbar, enter some information into the original product description form, and click **Generate**. The “Add an outlet” form should appear once the product descriptions have been generated. Add a new example outlet name and a character max and click “Add and Generate.” You should see a new tab appear with your new outlet, as well as an updated SEO analysis chart. ![Finished application](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/tutorial/product_desciption/pd_gen_13.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=59ef5c5e0698b04cf625075ace0b9338) You can add whatever additional form inputs you wish to the outlet form, but be sure to update `user_prompt` in the `prompts.py` file using your favorite editor. ## Conclusion You’ve now built a full application with the Writer Framework and the Writer AI module. Congratulations! This application not only demonstrates the platform's capabilities but also provides a foundation on which you can build more complex applications. To learn more, explore the rest of the Writer Framework documentation and the API documentation. # Quickstart Source: https://dev.writer.com/framework/quickstart ## Overview In this guide, you'll learn how to get started with the Writer Framework by building a simple "Hello, World" application. This beginner-friendly guide will help you install the necessary tools, set up an app, and deploy it to the Writer Cloud. ## Step 1: Install Writer Framework and run the demo app > [!TIP] > > Writer Framework works on Linux, Mac, and Windows. It supports Python versions 3.9.2 through 3.12. We recommend using a virtual environment. > [!WARNING] > > Python 3.13 is not yet supported. **1. Install Writer Framework** Use the following command to install the Writer Framework using `pip`. Open your command line interface and type: ```bash theme={null} pip install writer ``` This will download and install the Writer Framework and all its required dependencies. **2. Test installation with demo application** Once the installation is complete, you can verify that everything is set up correctly by running the built-in demo application. Navigate to your desired directory and type: ```bash theme={null} writer hello ``` This command creates a subfolder named **hello** and launches the Writer Framework, opening a visual editor accessible through a local URL displayed in your command line. This demo app illustrates the different components available in Writer Framework, helping you get familiar with the setup. ## Step 2: Create a new framework app Now that we've tested the setup, let's create our first "Hello, World" app using the `ai-starter` template. This template showcases how quickly you can build AI-powered applications with the Writer Framework. Use the following command to generate the app structure: ```sh theme={null} writer create hello-world --template=ai-starter ``` This will create a new app folder, **hello-world**, with the following structure: 1. `main.py` - The entry point for the app. You can import anything you need from here. 2. `.wf/` - This folder contains the UI component declarations. Maintained by the Writer Framework's visual editor. 3. `static/` - This folder contains front-end static files which you might want to distribute with your app, such as images and stylesheets. ## Step 3: Start the visual editor To start building and customizing your app visually, use the Writer Framework’s editor. This browser-based interface allows you to drag components, arrange layouts, and modify settings in real-time. ```sh theme={null} writer edit hello-world ``` After running this command, you'll see a local URL displayed in your command line. Open this URL in a web browser to access the editor. ![](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/quickstart/hello-world-editor.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=2be4a0fe511cc3244386d117f8139925) Writer Framework editor opens at [https://localhost:4005](https://localhost:4005) **1. Launch the Editor** In your terminal, enter the following command to open the editor: ```sh theme={null} writer edit hello-world ``` This command opens the Writer Framework editor in your browser, where you’ll see a live preview of your app. The editor interface includes a **component library** on the left, a **canvas** in the center for building layouts, and a **settings panel** on the right for customizing selected components. > [!NOTE] > > The editor starts by default on port 4005. If you launch multiple editors in parallel and do not specify a port, Writer Framework will automatically assign the next port until reaching the limit of 4099. > [!WARNING] > > It's not recommended to expose the Framework to the Internet. If you need to access the editor remotely, we recommend setting up an SSH tunnel. By default, requests from non-local origins are rejected as a security measure to protect against drive-by attacks. > > If you need to disable this protection, use the flag `--enable-remote-edit`. **2. Add Components to Your Canvas** On the left sidebar, browse through the **Component Library** and try dragging a few components onto the **Canvas**. For example, you can add a **Text** component to display "Hello, World!" or try other components to see how they work together. Experiment with arranging these components on the canvas to create a simple layout. ![](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/quickstart/hello-world-preview.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=efd8538a582610e7e070c65c9ea716cf) Writer Framework launches the app at [https://localhost:3005](https://localhost:3005) **3. Customize Component Settings** With a component selected, look at the **Settings Panel** on the right side. Here, you can edit properties like text content, colors, and alignment to see how it changes the appearance and behavior of the component on the canvas. This panel allows you to customize components without writing any code, giving you a quick and visual way to build a frontend. **4. Change the App Name in main.py** To personalize your app further, open `main.py` in the root of your project folder. Locate the following line: ```python theme={null} wf.init_state({ "my_app": { "title": "AI STARTER" }, }) ``` Change `"AI STARTER"` to something unique, like `"My First Writer App"`. Save the file, and you’ll see the updated name reflected immediately in the editor. ![](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/quickstart/hello-world-app-name.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=d013c1f5ead0a788818488b27ae7ca5e) App name updated in the Writer Framework editor For now, this simple exploration gives you an idea of how the framework enables rapid frontend building without code. In later tutorials, like creating a [Chat assistant](/framework/chat-assistant) or a [Social post generator](/framework/social-post-generator), you’ll explore more advanced components and layouts using this visual editor. ## Step 4: Run the app locally When your app is ready, execute the `run` command, which will allow others to run, but not edit, your Framework app. ```sh theme={null} writer run hello-world ``` > [!NOTE] > > Your app starts by default on port 3005. If you launch multiple apps in parallel and do not specify a port, Writer Framework will automatically assign the next port until reaching the limit of 3099. You can specify a port and host. Specifying `--host 0.0.0.0` enables you to share your application in your local network. ```sh theme={null} writer run hello-world --port 5000 --host 0.0.0.0 ``` ## Conclusion Congratulations! You’ve set up and configured your first app with the Writer Framework. Now, try building a [Chat assistant](/framework/chat-assistant) or a [Social post generator](/framework/social-post-generator) to put these skills into action. # Quickstart tutorial Source: https://dev.writer.com/framework/quickstart-tutorial In this tutorial, we'll guide you through creating a logistic regression visualisation tool using Framework. Logistic regression is a fundamental technique in machine learning for binary classification tasks, and visualising its decision boundary can provide valuable insights into the model's behaviour. First, make sure you have Framework installed. You can install it via pip: ```bash theme={null} pip install "writer" ``` Now, let's get started with creating our logistic regression visualisation tool. We'll break down the process into the following steps: 1. Setup Project 2. UI Creation 3. App state and bindings 4. Python implementation 5. Troubleshooting So, without further ado, let's jump into it. ## Project Setup To create our project, we will use the following commands: ```bash theme={null} writer create logistic_regression cd logistic_regression ``` Commands will create basic template of app project with initial file structure. In this project, we will be using the scikit-learn package for logistic regression, so let's install it before we start. Create a file `requirements.txt` and add the following line: ``` scikit-learn==1.4.0 ``` After that, we can install our requirements. ```bash theme={null} pip install -r requirements.txt ``` Once this is done, we can finally run the Framework editor using the command: ```bash theme={null} writer edit . ``` This will run our Framework instance. Runtime logs can be observed in the terminal, and the app is available at [http://localhost:4005](http://localhost:4005). ![newly created application](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/quickstart/new_app.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=90a1829bddec02dbcbe2aef578e0369d) ## UI Creation By default, Framework creates a simple application with a counter. To keep things easy, let's remove the contents from columns to make space for our new application. If you're unsure where to click to select a specific component on the screen, you can always use the `Component Tree` on the bottom left of the screen. The app should look something like this when you finish. ![empty app](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/quickstart/empty_app.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=0120edcb6cc46ea3ccf4e95dbf535653) This app will be made up of 2 columns, one with controls for our plot and the second with the plot itself. Half of the screen is way too much for controls, and the plot will be really small this way. To change the proportions of the columns, change the value of `Width (factor)` in the left column to `0.5`. ![width controls](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/quickstart/column_width.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=b595f5e72b470574cd38b3daf1e33530) This way, it will take just `1/3` of the screen. Proportions are calculated relative to each other. Each *Column*, by default, has the value of this factor set to 1. So, when we set the left column to 0.5 and the right to 1, we will get a relation between column sizes of 1:2. ![placing elements](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/quickstart/placing_elements.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=17eb9b9c28ffd6950384acd586f42ebb) Now let's add the rest of the components: * To the right column, add a *Plotly Graph*. * To the left: * 3 x *Slider Input* * *Dropdown Input* * *Button*. * To the free space in the header, let's place a *Message* component. ![ui boilerplate](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/quickstart/ui_boilerplate.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=d34c152cdbe1dba20fa9817894d777da) Now we can configure components with some static settings. You can find all the configuration options in right sidebar. Sidebar will apear after selecting the component using mouse click. Starting with slider inputs, let's set all 3 sliders configuration values to the following values: | Property | Value (Slider 1) | Value (Slider 2) | Value (Slider 3) | | :-: | :- | :- | :- | | Label | Number of groups | Number of points | Cluster deviation | | Minimum value | 2 | 50 | 0 | | Maximum value | 10 | 1000 | 10 | | Step size | 1 | 1 | 0.1 | Then for the dropdown, we will set: | Property | Value | | :-: | :- | | Label | Type | | Options | set `JSON` and paste: | | | `{"ovr": "One vs Rest", "multinomial": "Multinomial"}` | And in the end lets rename the button. | Property | Value | | :-: | :- | | Text | Regenerate | ## App State and Bindings It is time to create the application's initial state. Let's open the code editor. In this tutorial, we will be using the built-in code editor, which can be found by clicking on the 'Code' button at the top of the screen. However, if you prefer using your favourite editor, you can simply edit the `main.py` file, and the app will auto-refresh every time the file is changed. ![code editor](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/quickstart/code_editor.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=6400799d646b9e75f11e730f61e759e3) Let's remove all code from there and start with: ```python theme={null} import writer as wf import plotly.graph_objects as go from sklearn.linear_model import LogisticRegression from sklearn.datasets import make_blobs initial_state = wf.init_state({ "my_app": { "title": "Logistic Regression Visualiser" }, "message": None, "figure": None, "multi_class": "ovr", "number_of_groups": 2, "number_of_points": 50, "cluster_std": 2, }) ``` For now, only the Framework import is needed, but the rest will be used later on. Notice that after pasting this code into the editor, when we click on `Save and run`, the header of our application will immediately change to "Logistic regression visualiser". This is because the Header has in its text property the value `@{my_app.title}`, which is a template syntax that uses a value from the state. The rest of the keys and values from the `initial_state` are names and initial values for components that will be used for communication between the app UI and the back-end. Assigning those keys to components is called binding, and it is done by clicking on each component and filling property "State element" in the "Binding" menu. Let's use these bindings for our 3 *Slider Input* components: | Property | Value (Slider 1) | Value (Slider 2) | Value (Slider 3) | | :-: | :- | :- | :- | | State element | `number_of_groups` | `number_of_points` | `cluster_std` | For the *Dropdown Input*: | Property | Value | | :-: | :- | | State element | `multi_class` | If you closely follow my steps, the massage component can be hidden behind the right bar. Use the `Component Tree` to click the element and open the `Properties` menu. *Message* component doesen't have bindings but we still can use template syntax to use data from the state inside of a `Message`. Additionaly we are able to use this data to control the visibility of the component. | Property | Value | | :-: | :- | | Message | `@{message}` | | Visibility | `custom` | | Visibility value | `message` | This way, the *Message* component will show only if there is a message to display. For *Plotly Graph* we use template syntax again: | Property | Value | | :-: | :- | | Graph specification | `@{figure}` | Congratulations! You have just connected all components to the application state. Nothing is happening yet. Now, we are ready to make it alive. It's time for python! ## Python implementation Let's create a function that will update our application based on inputs and call it immediately. ```python theme={null} def update(state): state["message"] = "Hello, world!" update(initial_state) ``` Notice that *Message* showed up, and it is now displaying the message "Hello, World!". To have better access to state parameters and to make it clear on which parameters our function depends, we define them at the top of the function. Notice that some of them need to be mapped to appropriate types. The *Slider Input* returns float values by default, so here, as we will need integers, we cast values to int. ```python theme={null} def update(state): cluster_std = state['cluster_std'] multi_class = state['multi_class'] number_of_points = int(state['number_of_points']) number_of_groups = int(state['number_of_groups']) ``` In this example, we create a logistic regression visualisation, but the algorithm itself is not in the scope of this tutorial. So we will just use the basic function from the `scikit-learn` library. ```python theme={null} X, y = make_blobs( n_samples=number_of_points, n_features=2, cluster_std=cluster_std, centers=groups ) clf = LogisticRegression( solver="sag", max_iter=1000, random_state=42, multi_class=multi_class ).fit(X, y) coef = clf.coef_ intercept = clf.intercept_ score = clf.score(X, y) ``` `make_blobs` will generate `number_of_points` points on a 2D space that have a cluster deviation set to `cluster_std` and the number of groups defined by `number_of_groups`. After that, we generate a LogisticRegression, and we take parameters we need. For better knowledge about the process, let's display the training score as a message. ```python theme={null} state["message"] = "training score : %.3f (%s)" % (score, multi_class) ``` The algorithm will generate one or many lines depending on how many groups we have. To be able to draw those lines, let's create a helper function: ```python theme={null} def _line(x0, coef, intercept, c): return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1] ``` This function is a helper function meant to be used on the back-end. The underscore at the beginning of its name tells Framework that this function is private, and the front-end won't know about its existence. To make the plot more readable, let's quickly define some colours for our plots: ```python theme={null} COLOR = { 0: '#3c64fa', 1: '#00eba8', 2: '#5a677c', 3: '#ff8866', 4: '#d4b2f7', 5: '#c3e6ff', 6: '#045758', 7: '#001435', 8: '#ec3d10', 9: '#38006a' } ``` Now, let's create a plot for our logistic regressions. For that, we will use `plotly.graph_objects` to have full control over what will be included in our plot. ```python theme={null} data = [] for i in range(number_of_groups): data.append( go.Scatter( x=X[y == i][:, 0], y=X[y==i][:, 1], mode='markers', name='Group '+str(i), hoverinfo='none', marker=dict( color=COLOR[i], symbol='circle', size=10 ) ) ) for i in range(1 if number_of_groups < 3 else number_of_groups): data.append(go.Scatter( x=[-20, 20], y=[ _line(-20, coef, intercept, i), _line(20, coef, intercept, i) ], mode='lines', line=dict(color=COLOR[i], width=2), name='Logistic Regression' )) layout = go.Layout( width=700,height=700, hovermode='closest', hoverdistance=1, xaxis=dict( title='Feature 1', range=[-20,20], fixedrange=True, constrain="domain", scaleanchor="y", scaleratio=1 ), yaxis=dict( title='Feature 2', range=[-20,20], fixedrange=True, constrain="domain" ), paper_bgcolor='#FFFFFF', margin=dict(l=30, r=30, t=30, b=30), ) fig = go.Figure(data=data, layout=layout) state['figure'] = fig ``` After saving and running the code, we should get something like this: But as you could notice, when we change our slider values, nothing happens. It's because our function is currently called only once on app initialisation and not after input changes. To change this behaviour, let's set the event handler for `wf-number-change` in all slider inputs to `update`, which is the name of our function in the Python code. Notice that `_line` is not visible there because it's private to the back-end. If we would change its name to `line`, then it would be visible on this list. Set also event handler for dropdown input `wf-option-change` and `wf-click` in the button, also to `update`. And done! You can have fun with your new application. Feel free to modify and play with other options. Final code for the application should look something like this: ```python theme={null} import writer as wf import plotly.graph_objects as go from sklearn.linear_model import LogisticRegression from sklearn.datasets import make_blobs COLOR = { 0: '#3c64fa', 1: '#00eba8', 2: '#5a677c', 3: '#ff8866', 4: '#d4b2f7', 5: '#c3e6ff', 6: '#045758', 7: '#001435', 8: '#ec3d10', 9: '#38006a' } def _line(x0, coef, intercept, c): return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1] def update(state): cluster_std = state['cluster_std'] multi_class = state['multi_class'] number_of_points = int(state['number_of_points']) number_of_groups = int(state['number_of_groups']) X, y = make_blobs( n_samples=number_of_points, n_features=2, cluster_std=cluster_std, centers=number_of_groups ) clf = LogisticRegression( solver="sag", max_iter=1000, random_state=42, multi_class=multi_class ).fit(X, y) coef = clf.coef_ intercept = clf.intercept_ score = clf.score(X, y) state["message"] = "training score : %.3f (%s)" % (score, multi_class) data = [] for i in range(number_of_groups): data.append( go.Scatter( x=X[y == i][:, 0], y=X[y==i][:, 1], mode='markers', name='Group '+str(i), hoverinfo='none', marker=dict( color=COLOR[i], symbol='circle', size=10 ) ) ) for i in range(1 if number_of_groups < 3 else number_of_groups): data.append(go.Scatter( x=[-20, 20], y=[ _line(-20, coef, intercept, i), _line(20, coef, intercept, i) ], mode='lines', line=dict(color=COLOR[i], width=2), name='Logistic Regression' )) layout = go.Layout( width=700,height=700, hovermode='closest', hoverdistance=1, xaxis=dict( title='Feature 1', range=[-20,20], fixedrange=True, constrain="domain", scaleanchor="y", scaleratio=1 ), yaxis=dict( title='Feature 2', range=[-20,20], fixedrange=True, constrain="domain" ), paper_bgcolor='#EEEEEE', margin=dict(l=30, r=30, t=30, b=30), ) fig = go.Figure(data=data, layout=layout) state['figure'] = fig initial_state = wf.init_state({ "my_app": { "title": "Logistic regression visualizer" }, "message": None, "figure": None, "multi_class": "ovr", "number_of_groups": 2, "number_of_points": 50, "cluster_std": 2, }) update(initial_state) ``` ## Troubleshooting ### Errors When your code has an error, you will be notified with a notification in the app, and also in the console, you can find useful logs. ### Debugging To check some intermediate values in your Python code, you can just use `print()` function. All logs will be available in the terminal. ## Conclusion Congratulations! You've successfully created a logistic regression visualisation tool using Framework. You can further customise and enhance this tool to suit your specific needs. ## Additional Resources * [Scikit-learn Documentation](https://scikit-learn.org/stable/) * [Plotly Documentation](https://plotly.com/python/) Feel free to explore these resources to deepen your understanding and expand your capabilities. # Release notes generator Source: https://dev.writer.com/framework/release-notes-generator In this tutorial, you'll build a release notes generator using the Writer Framework. This application will help you generate release notes as formatted HTML for software updates based on user-provided data as a CSV file. You can check out the [finished code on GitHub](https://github.com/writer/framework-tutorials/tree/main/release-notes-generator/end) to see what you'll be building. The application consists of two main parts: the backend, which processes the uploaded CSV file and generates the release notes, and the frontend, which displays the release notes and allows users to download them. ![Finished release notes generator application](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/release_notes/release_gen_1.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=842fe3a65cd5dcec1b0ec64bc90a9061) ## Setting up your project ### Creating a Writer app and getting your API key From the Home screen, click on **Build an app**. ![Writer home screen](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/release_notes/release_gen_2.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=6420bb80483e26ad584e64c621ef5dba) Select Framework as the app type you want to create, enabling you to generate keys and build your app with the Writer Framework. ![App type selection](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/release_notes/release_gen_3.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=4a22fd9137c9e7bd6374de85e06ba13c) On the next screen, you can edit your Writer application name at the top left. Underneath "Authenticate with an API key," click "Reveal" to view and copy your API key. ### Creating the application Next, open your terminal and navigate to the directory where you want to create your application directory. **1. Set the API key environment variable** To pass your API key to the Writer Framework, you'll need to set an environment variable called `WRITER_API_KEY`. Here's how you can set this variable in your terminal session: ```sh On macOS/Linux theme={null} export WRITER_API_KEY=[key] ``` ```sh On Windows theme={null} set WRITER_API_KEY=[key] ``` **2. Clone the application** Run the following command to clone the `framework-tutorials` repo and navigate to the folder containing the starting point for this application. ``` git clone https://github.com/writer/framework-tutorials.git cd framework-tutorials/release-notes-generator/start ``` **3. Edit your project** To edit your project, run the following commands. This will bring up the console, which displays Framework-wide messages and errors, including logs from the API. By default, the Writer Framework Builder is accessible at `localhost:4005`. If this port is in use, you can specify a different port. Open this address in your browser to view your default application setup. ```bash Standard port theme={null} writer edit . ``` ```bash Custom port theme={null} writer edit . --port=3007 ``` ## Introduction to the application setup The template includes some basic code, UI setup, and files to help you get started. ### Included files The files `prompts.py` and `html_template.py` contain helper functions for generating prompts for the AI model and formatting the output HTML, respectively. In the `sample-input` folder, you'll find a sample CSV file that you can use to test the application. Finally, the `custom.css` file in the `static` folder contains custom CSS styles for the application. ### Dependency imports In `main.py`, you'll see that the dependencies are already imported at the top: ```python theme={null} import writer as wf import writer.ai import pandas as pd from prompts import get_release_notes_summary_prompt, get_release_notes_desc_prompt, get_category_prompt from html_template import format_output ``` These dependencies include the Writer Framework, the Writer AI module, and pandas for data manipulation. ### Initial UI The template includes a basic UI setup, including a Page component with a Header component. The Header component also includes an Image. If you want to change the logo image, you can replace the `logo_image_path` variable in the state with the path to your desired image in the `static` folder. ## Initializing the application state First, in `main.py`, set up the initial state for the application. This state will store the application's title, logo image path, file data, metrics, and processing status for each step. You'll also import a custom CSS file to style the application and create a placeholder DataFrame. **1. Create initial DataFrame** Create a placeholder DataFrame on the line above `wf.init_state`: ```python theme={null} placeholder_data = { 'Description': ['Description 1', 'Description 2', 'Description 3'], 'Label': ['Label 1', 'Label 2', 'Label 3'] } initial_df = pd.DataFrame(placeholder_data) ``` **2. Initialize state** Update the initial state for the application at the bottom of `main.py`: ```python theme={null} initial_state = wf.init_state({ "my_app": {"title": "RELEASE NOTES GENERATOR"}, "logo_image_path": 'static/Writer_Logo_black.svg', "file": {"name": "", "file_path": ""}, "metrics": {"new_features": 0, "caveats": 0, "fixed_issues": 0, "total": 0}, "step1": { "raw_csv": initial_df, "completed": "no", "generate-button-state": "yes", "processing-message": None, "styled-table": "

csv table

" }, "step2": { "release-notes": None, "completed": "no", "formatted-release-notes": "notes should go here" }, }) ``` **3. Import custom CSS** Import the custom CSS file below the initial state setup: ```python theme={null} initial_state.import_stylesheet(".description, .list, .summary, .category ", "/static/custom.css") ``` ## Building the file upload functionality First, you'll build the file upload feature. Note that `prompts.py`, `html_template.py`, and `custom.css` are provided in the starting point for the application. There is also a sample CSV file in the `sample-input` folder that you can use to test the application. ### Implementing the file upload handler To handle file uploads, you'll create a function in `main.py` that reads the uploaded CSV file, processes the data, and stores it in the application state. **1. Implementing a file upload handler** In `main.py`, create a function to handle file uploads. This function will read the uploaded CSV file, process the data, and store it in the application state. ```python theme={null} def onchangefile_handler(state, payload): uploaded_file = payload[0] name = uploaded_file.get("name") state["file"]["name"] = name state["step1"]["processing-message"] = f'+File {name} uploaded successfully.' state["file"]["file_path"] = f"data/{name}" file_data = uploaded_file.get("data") with open(f"data/{name}", "wb") as file_handle: file_handle.write(file_data) data = pd.read_csv(state["file"]["file_path"]) df = pd.DataFrame(data) state["step1"]["raw_csv"] = df state["step1"]["generate-button-state"] = "no" ``` **2. Create CSV to DataFrame converter** Define a function to convert the CSV file to a DataFrame: ```python theme={null} def _raw_csv_to_df(state): data = pd.read_csv(state["file"]["file_path"]) df = pd.DataFrame(data) return df ``` ### Displaying the uploaded CSV file Next, you'll display the uploaded CSV file in the application UI. **1. Creating a Step Container** Add a Step Container component to the Page. This will contain the two steps for the application. **2. Create Step components** Drag two Step components into the Step Container. Name the first one "Load CSV file" and the second "Release notes". **3. Configure first Step component** Click on the the first Step component to select it and bring up the Properties pane. Set "Completed" to `@{step1.completed}`. This state reference will contain either "yes" or "no" based on the completion status of the step. **4. Add Message component** Within this Step, add a Message component with the message set to `@{step1.processing-message}`. Scroll down to the Visibility section of the settings. Select "Custom" and set the condition to `step1.processing-message`. **5. Create three-column layout** Add a Column Container component and add three Column components. For the first column, set the width to 0.5. For the third column, set "Content alignment (H)" to "Left" and "Content alignment (V)" to "Bottom." **6. Add file input** In the middle column, place a File Input component labeled "Please upload your CSV file". Set its `wf-file-change` handler to `onchangefile_handler`. **7. Add generate button** In the third column, add a Button labeled "Generate release notes". Set its "Disabled" property to `@{step1.generate-button-state}` and its "Icon" property to `laps`. **8. Add Raw CSV section** Under the columns, create a Section component and set the title to "Raw CSV". **9. Add DataFrame component** In this section, add a DataFrame component to display the raw CSV data. Configure its properties to use `@{step1.raw_csv}` as the data source. Toggle "Enable download," "Use Markdown," and "Wrap text" to "yes". Set the Separator color to `#d4b2f7` using the CSS tab. Your application should now look like this: ![Release notes generator UI](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/release_notes/release_gen_4.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=4570cc9bfa4d318c894e32f478f84543) When using the sample data located in `sample-input/test-data.csv`, the Raw CSV section will display the uploaded CSV file: ![Raw CSV section](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/release_notes/release_gen_5.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=12a34e7eda591446cdfeb37ba54eaf05) ## Generating release notes Now that you've set up the file upload functionality, you can generate release notes based on the uploaded CSV file. ### Defining text completion functions Using the prompts provided, define functions to get the category, release notes summary, and release notes description using AI completion. You'll use these functions to process the uploaded CSV file and generate release notes. **1. Create category function** Define a function to get the category using AI completion: ```python theme={null} def _get_category(desc, label): prompt = get_category_prompt(desc, label) label = writer.ai.complete(prompt) return label ``` **2. Create summary function** Define a function to get the release notes summary: ```python theme={null} def _get_release_notes_summary(label, desc): prompt = get_release_notes_summary_prompt(label, desc) formatted_desc = writer.ai.complete(prompt) return formatted_desc ``` **3. Create description function** Define a function to get the release notes description: ```python theme={null} def _get_release_notes_desc(label, desc): prompt = get_release_notes_desc_prompt(label, desc) formatted_desc = writer.ai.complete(prompt) return formatted_desc ``` ### Implementing the generate functionality You'll next implement the ability to process the CSV and generate release notes. **1. Create category HTML** Define a function to generate HTML for the categories: ```python theme={null} def _create_df_for_category(df,state): unique_categories = df['Primary-Category'] formatted_output_list = list() for category in set(unique_categories): df_category = df[df['Primary-Category']==category] categories = {" New Feature": "new_features", " Caveat": "caveats", " Fixed Issue": "fixed_issues" } curr_category = categories[category] state["metrics"][curr_category]= df_category.shape[0] formatted_output = format_output(category,df_category) formatted_output_list.append(formatted_output) return "".join(formatted_output_list) ``` **2. Create HTML file writer** Define a function to write HTML to a file: ```python theme={null} def _write_html_to_file(html): with open("data/output-html.html", "w") as file_handle: file_handle.write(html) ``` **3. Implement generate button handler** Next, create a function to handle the generate button click. This function will process the uploaded CSV file, generate release notes, and store the formatted output in the application state. ```python theme={null} def handle_generate_button_click(state): state["step1"]["generate-button-state"] = "yes" state["step1"]["processing-message-isVisible"] = True state["step1"]["processing-message"] = "%Hang tight, preparing to process your file" notes_counter = 0 df = _raw_csv_to_df(state) csv_row_count = df.shape[0] for index, row in df.iterrows(): df.at[index,"Primary-Category"] = _get_category(label=row["Labels"], desc=row["Description"]) df.at[index,"Release-Notes-Summary"] = _get_release_notes_summary(label=row["Labels"], desc=row["Description"]) df.at[index,"Release-Notes-Description"] = _get_release_notes_desc(label=row["Labels"], desc=row["Description"]) notes_counter += 1 state["step1"]["processing-message"] = f'%Processing {notes_counter} of {csv_row_count} Release Notes' df_temp = df[["Primary-Category","Release-Notes-Summary","Release-Notes-Description"]] df_sorted = df_temp.sort_values(by='Primary-Category') state["step2"]["release-notes"] = df_sorted state["step1"]["completed"] = "yes" state["step1"]["processing-message"] = "" html = _create_df_for_category(df_sorted,state) _write_html_to_file(html) state["step2"]["formatted-release-notes"] = html state["metrics"]["total"] = df_sorted.shape[0] state["step1"]["generate-button-state"] = "no" ``` **4. Bind button handler to Generate button** Finally, click on the "Generate release notes" button in the UI builder and set its `wf-click` handler to `handle_generate_button_click`. ## Displaying the release notes Now that you've generated the release notes, you can display them in the application UI. ### Implementing helper functions Define helper functions to handle back button clicks, write HTML to a file and download the HTML file. **1. Create back button handler** Define a function to handle the back button click: ```python theme={null} def handle_back_button_click(state): state["step1"]["completed"] = "no" ``` **2. Create file download handler** Define a function to handle downloading the HTML file: ```python theme={null} def handle_file_download(state): html_data = wf.pack_file("data/output-html.html","text/html") file_name = "output-html.html" state.file_download(html_data,file_name) ``` ### Building the initial release notes UI Next, you'll build the UI for the "Release notes" step. **1. Select 'Release notes' Step** To display the Release notes Step component, you'll need to double-click on it. **2. Add Separator** Inside of the Step component, add a Separator component. **3. Add Columns components** Below the Separator, add a Column Container component and a single Column component. **4. Add Back button** In the column, add a Button. Set its text to "Back" and set its `wf-click handler` to `handle_back_button_click`. Set the "Icon" property to `arrow_back`. ### Buiding tabs for Release notes display Below the Back button, add a Tab Container component and two Tab components. Name them "Formatted release notes" and "Release notes". #### Formatted release notes tab In the first tab, you'll display the formatted release notes. **1. Add HTML component** In the first tab, add an HTML Element component. Set the "Element" property `div` and the "Styles" property to the following object: ``` { "padding": "16px", "min-height": "64px", "min-width": "64px", "border-radius": "8px", "background": "white", } ``` Finally, set the "HTML inside" property to `@{step2.formatted-release-notes}`. **2. Create three-column layout** Inside thie HTML Element component, create a three-column layout using a Column Container component and three Column components. **3. Add Metric components** In each column, add three Metric components to display new features, caveats, and fixed issues, respectively. Set the "Name" of these components to a single space to remove the placeholder text: ` `. Then, set the values of these components to `@{metrics.new_features}`, `@{metrics.caveats}`, and `@{metrics.fixed_issues}`. Finally, set the "Note" text to "+New Features", "+Caveats", and "+Fixed Issues" respectively. The "+" sign will display styling that indicates a positive message. **4. Add download button** Under the columns, add a Button component. Set its "Text" to "Download HTML" and its "Icon" to `download`. Then, set the `wf-click` handler to `handle_file_download`. The Formatted release notes tab should look like this when using the sample data: ![Formatted release notes tab](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/release_notes/release_gen_1.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=842fe3a65cd5dcec1b0ec64bc90a9061) #### Release notes tab Finally, you'll add a Dataframe component to the second tab to display the detailed release notes. **1. Add Metric component** In the second tab, start with a Metric component to show the total number of release notes generated. Set the "Name" to "Number of release notes generated" and the "Value" to `@{metrics.total}`. Delete the default value for "Note". **2. Add DataFrame component** Follow this with a DataFrame component to display the detailed release notes, setting the "Data" property to `@{step2.release-notes}`. Configure it for text wrapping, downloading, and searching capabilities. Set the Separator color to `#d4b2f7`. The final Release notes section should look like this: ![Release notes final UI](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/release_notes/release_gen_6.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=a5742f47ca67b0f2c7a05b22aec422e9) You can [see the finished code on GitHub](https://github.com/writer/framework-tutorials/tree/main/release-notes-generator/end) or in `framework-tutorials/release-notes-generator/end` in the `tutorials` repo you cloned at the beginning of the tutorial. ## Conclusion By following these steps, you've created a complete Release notes generator application using Writer Framework. To learn more, explore the rest of the Writer Framework documentation and the API documentation. # Repeater Source: https://dev.writer.com/framework/repeater The *Repeater* component allows you to repeat a group of components according to a list or dictionary. ## How it works *Repeater* repeats its contents for every item of a given list or dictionary. It's similar to a `for each` construct. Each iteration is rendered with a different **context**, a dictionary containing the key and value for the relevant item. By default, in the variables `itemId` and `item`. ### Food Selector example ![Repeater example](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/repeater.example.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=c0b9701b4f9e6efeb7a394d3516994d6) Given the state below, the contents of *Repeater* will be repeated 3 times. For the first iteration, `itemId` will equal `Banana`, and `item` will equal `{"type": "fruit", "colour": "yellow"}`. Components inside *Repeater* will be able to access this data using references such as `@{itemId}` and `@{item.type}`. ```py theme={null} wf.init_state({ "articles": { "Banana": { "type": "fruit", "colour": "yellow" }, "Lettuce": { "type": "vegetable", "colour": "green" }, "Spinach": { "type": "vegetable", "colour": "green" } }, "order_list": [] }) ``` ## Event context When working with *Repeater* components, you can get the context data using the `context` argument in the event handler. Continuing with the Food Selector example above, the following handler can be linked to a *Button* —allowing users to add items to a list. ```py theme={null} # The event handler below adds the itemId # of the relevant article to the order list def handle_add_to_list(state, context): state["order_list"] += [context["itemId"]] ``` > [!WARNING] > > Binding directly to context isn't possible > > Use dynamic accessors when binding inside a *Repeater*. For example, `articles[itemId].colour`. This will bind to a different property of `articles` for every `itemId`. # Sample app library Source: https://dev.writer.com/framework/sample-apps Writer Framework lets you build a wide variety of applications across different domains. Here are some sample apps to get you started, which are all [available on GitHub](https://github.com/writer/framework-tutorials/). > [card] [Code generator](https://github.com/writer/framework-tutorials/tree/main/code-generator) > > Generate React apps editable in a code sandbox. > [card] [Finance content checker](https://github.com/writer/framework-tutorials/tree/main/finance-content-checker) > > Tool for analyzing financial content based on compliance guidelines. > [card] [Finance dashboard](https://github.com/writer/framework-tutorials/tree/main/finance-dashboard) > > AI-powered interactive dashboard for summarizing and visualizing financial data and metrics. Check out the [app tour](https://writer.com/engineering/financial-app-writer-framework-palmyra-fin/) on our Engineering blog. > [card] [Localized promo dashboard](https://github.com/writer/framework-tutorials/tree/main/localized-promo-dashboard) > > Tool to generate promotional content based on uploaded demographic data. > [card] [Patient portal](https://github.com/writer/framework-tutorials/tree/main/patient-portal) > > Generates SOAP notes and extracts ICD codes from patient-doctor chat. > [card] [Product description embedded chat](https://github.com/writer/framework-tutorials/tree/main/pd-embedded-chat) > > Use an embedded no-code chat app to chat with a Knowledge Graph about products. > [card] [Product description page generator](https://github.com/writer/framework-tutorials/tree/main/pdp-generator) > > Tool for generating formatted product description pages. > [card] [Release notes generator](https://github.com/writer/framework-tutorials/tree/main/release-notes-generator) > > Utility for creating formatted, downloadable release notes from CSVs containing GitLab notes. [Full tutorial here](./release-notes-generator). # SEO and social sharing Source: https://dev.writer.com/framework/seo Writer Framework provides powerful options for optimizing your application's metadata to improve SEO (Search Engine Optimization) and enhance how your content appears when shared on social networks. These options are available in the `writer.serve.configure_webpage_metadata` function available in the `server_setup.py` file. ## Page title configuration The page title is a crucial element for your application's SEO. Web crawlers and bots will see this title without loading the full application. By default, they will see `Writer Framework`. ```python theme={null} # ./server_setup.py writer.serve.configure_webpage_metadata(title="My Amazing App") ``` For dynamic titles, you can use a function instead of a static string. The title will be evaluated when a bot loads the page: ```python theme={null} # ./server_setup.py def _title(): last_news = db.get_last_news() return f"Last news: {last_news.title}" writer.serve.configure_webpage_metadata(title=_title) ``` ## Meta tags configuration HTTP headers allow you to specify a title, description, and keywords that search engines will use to understand and index your content. You can configure these tags using the `meta` parameter. ```python theme={null} # ./server_setup.py writer.serve.configure_webpage_metadata( title="My Amazing App", meta={ "description": "My amazing app", "keywords": "WF, Amazing, AI App", "author": "Amazing Company" } ) ``` You can also generate meta tags dynamically using a function: ```python theme={null} # ./server_setup.py def _meta(): last_news = db.get_last_news() return { "description": f"Last news: {last_news.title}", "keywords": f"{last_news.keywords}", "author": "Amazing Company" } writer.serve.configure_webpage_metadata(meta=_meta) ``` ## Social network configuration When users share links to your application on social networks, those platforms will attempt to fetch metadata to create rich previews of your content. You can configure the OpenGraph tags to improve the appearance of your content when shared. ```python theme={null} # ./server_setup.py writer.serve.configure_webpage_metadata( opengraph_tags= { "og:title": "My App", "og:description": "My amazing app", "og:image": "https://myapp.com/logo.png", "og:url": "https://myapp.com" } ) ``` Like meta tags, OpenGraph tags can also be generated dynamically: ```python theme={null} # ./server_setup.py def _opengraph_tags(): last_news = db.get_last_news() return { "og:title": f"Last news: {last_news.title}", "og:description": f"{last_news.description}", "og:image": f"{last_news.image}", "og:url": f"https://myapp.com/news/{last_news.id}" } writer.serve.configure_webpage_metadata(opengraph_tags=_opengraph_tags) ``` By configuring your application's metadata, your application will be more visible in search engines and social networks. # Sessions Source: https://dev.writer.com/framework/sessions Sessions are designed for advanced use cases, being most relevant when Framework is deployed behind a proxy. ## Session information in event handlers You can access the session's unique id, HTTP headers and cookies from event handlers via the `session` argument —similarly to how `state` and `payload` are accessed. The data made available here is captured in the HTTP request that initialised the session. The `session` argument will contain a dictionary with the following keys: `id`, `cookies` and `headers`. Values for the last two are themselves dictionaries. ```py theme={null} # The following will output a dictionary # with the session's id, cookies and headers. def session_inspector(session): print(repr(session)) ``` This enables you to adapt the logic of an event to a number of factors, such as the authenticated user's role, preferred language, etc. ## Session verifiers You can use session verifiers to accept or deny a session based on headers or cookies, thus making sure that users without the right privileges don't get access to the initial state or components. Session verifiers are functions decorated with `wf.session_verifier` and are run every time a user requests a session. A `True` value means that the session must be accepted, a `False` value means that the session must be rejected. ```py theme={null} import writer as wf # Users without the header x-success will be denied the session @wf.session_verifier def check_headers(headers): if headers.get("x-success") is None: return False return True ``` # Social post generator Source: https://dev.writer.com/framework/social-post-generator In this tutorial, you'll use the Writer Framework to build an AI-powered tool for generating social media posts and tags based on the input you provide! The process will take only minutes using a drag-and-drop visual editor to build the user interface and Python for the back-end code. Here's what the finished project will look like: ![Finished social post generator project](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2ab.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=e38dd8f9a9fe0a6b6976706902b45761) ## Prerequisites Before starting, ensure you have: * **A Writer account:** You don't need an account to use Writer Framework, but you'll need one to use the AI module. [Sign up for a free account here](https://app.writer.com/register). * **Python 3.9.2 or later**: Use the installer from [python.org](https://www.python.org/downloads/). * **pip:** This command-line application comes with Python and is used for installing Python packages, including those from Writer. * **A basic understanding of Python:** You should be familiar with the basics of the language. * **Your favorite code editor (optional):** There's a code editor built into Writer for writing back-end code, but you can also use Visual Studio Code, Notepad++, Vim, Emacs, or any text editor made for programming if you prefer. ## Setting up your project ### Create a Writer app and get its API key First, you'll need to create a new app within Writer. **1. Create the app in Writer** Log into Writer. From the Home screen, click on the **Build an app** button. ![Writer home screen](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=8f7d36049df01e27d405a7f07401b8dc) The **Start building** menu will appear, presenting options for the types of apps you can create. Select **Framework**, located under **Developer tools**. This will create a brand new app based on Writer Framework. !["Start building" menu](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_3.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=8e8988274dfd797dde727d2070948200) **2. Copy your app's API key** On the next screen, titled **How to deploy an application**, you can get the API key for the app by clicking on the **Reveal key** button, located under the text **Authenticate with an API key**. Your complete API key will be displayed, and a "copy" button will appear. Click this button to copy the key; you'll use it in the next step. !["How to deploy an application" page](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2a.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=1ac1226cb669cb98048760f5d2dd1285) ### Set up your computer and create the app's project The next step is to set up the Writer Framework environment on your computer. You'll do this by creating a directory for the project, installing dependencies, and creating the project for the application using a template. **1. Open your terminal application** Open your terminal application. On macOS and Linux, this application goes by the name *Terminal*; on Windows, you can use either *Windows PowerShell* (which is preferred) or *Command Prompt*. **2. Install the dependencies** > [!NOTE] > > If you already have the `writer` and `python-dotenv` packages installed on your computer, you can skip this step. Install the `writer` and `python-dotenv` packages by entering the following commands in your terminal application: ``` pip install writer python-dotenv ``` This command tells `pip`, the Python package installer, to install two packages: * `writer`, which provides some command-line commands and enables Python code to interact with Writer and the Writer Framework. * `python-dotenv`, which makes it easy to manage environment variables by loading them from a `.env` file. This one is optional for this exercise, but you might find it useful when working on larger projects. **3. Set the API key environment variable** To pass your API key to the Writer Framework, you need to set an environment variable called `WRITER_API_KEY`. Select your operating system and terminal application below, then copy and paste the command into your terminal application, replacing `[your_api_key]` with the API key you copied earlier: ```sh macOS/Linux (Terminal) theme={null} export WRITER_API_KEY=[your_api_key] ``` ```sh On Windows (Windows PowerShell) theme={null} $env:WRITER_API_KEY=[your_api_key] ``` ```sh On Windows (Command Prompt) theme={null} set WRITER_API_KEY=[your_api_key] ``` The `WRITER_API_KEY` environment variable will remain defined as long your terminal session is open (that is, until you close your terminal application’s window). **4. Create the project** Create the project by entering this command into your terminal application: ``` writer create social-post-generator --template=ai-starter ``` This command sets up a new project called `social-post-generator` using a starter template called `ai-starter` so that you're not starting "from scratch." ## Build the UI Now that you've created the project, it's time to define the UI. The Writer Framework's drag-and-drop capabilities make it easy — even if you haven't done much UI work before! The project editor is a web application that runs on your computer and enables you to define and edit your app's user interface. Launch it by typing the following into your terminal application: ``` writer edit social-post-generator ``` You'll see a URL. Control-click it (command-click on macOS) to open it, or copy the URL and paste it into the address bar of a browser window. The browser window will contain the project editor, which will look like this: ![Project editor](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2b.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=d8e5d597c75f4303eb3f588e7ef5f7a8) You'll see the following: * The **canvas** is in the center. It displays the app's user interface. * The column on the left contains: * The **Core toolkit**, which contains all the UI components. You define the user interface by dragging components from the Toolkit and placing them on the canvas. * The **Component tree**, which shows the arrangement of the UI components on the canvas. It's also useful for selecting items on the canvas, especially when it has a lot of UI components. It's time to build the UI! **1. Examine the header** Select the **Header** component by clicking it — it's the component at the top, containing the title **AI STARTER** and a gray area labeled **Empty Header**. When you click it, you'll see the **properties** panel appear on the right side of the page. This lets you view and edit the properties of the selected component. ![The selected header and its properties panel](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2c.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=1ba5e3c03ec68463569c76c6e55baff2) The first property you'll see in the panel is the **Text** property, which defines the text that appears as the header's title. It should contain the value `@{my_app.title}`. The `@{` and `}` indicate that `my_app.title` is a variable and that its contents should be the text displayed instead of the literal text "my_app.title". You'll set the value of this variable soon. **2. Clear the Section's default title** Select the **Section** component by clicking it — it's just below the **Header** component and contains the title **Section Title** and a gray area labeled **Empty Section**. In the **properties** panel, clear out the value of the **Title** property. This will remove the *Section*'s default title. ![The selected section and its properties panel](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2d.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=6d404fbbeea27b1ccd0214ac42622a2a) **3. Add a Text Input component** The user will need a place to enter words or phrases that the app will use as the basis for generating posts and tags. Drag a **Text Input** component — and note, it's **Text _Input_**, not **Text** — from the **Core toolkit** panel on the left (it's under **Input**, and you may need to scroll down a little to find it) and into the **Section**. Sections can act as containers for other components. > [!NOTE] > > You can search for a specific component by using the search bar at the top of the **Core toolkit** panel. Select the **Text Input** component. In the **properties** panel: * Find the **Label** property and set its value to `Topic for social posts and tags`. * (Optional) Feel free to add some placeholder to the *Text Input* component by setting the value of the **Placeholder** property with something like `Enter words or phrases describing your topic`. ![The text input component and its properties panel](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2e.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=7922ce43b1b0dc522ce4fa3d7de4daae) **4. Add a Button component** Drag a **Button** component from the **Core toolkit** panel (it's under **Other**, and you may need to scroll down a little to find it) into the **Section**, directly below the **Text Input**. The user will click this button to submit their prompt. Select the **Button**. In the **properties** panel: * Set the **Text** property's value to `Generate posts`. * Find the **Icon** property, and set its value to `arrow_forward`. ![The button component and its properties panel](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2f.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=bf1cd3c45cf7aaa3089e45c1103285ff) **5. Add a Message component** The process of creating social media posts and tags takes a few moments. In order to reassure the user that the app is working and hasn't crashed, it will use a **Message** component to display something reassuring while it's generating. Drag a **Message** component from the **Core toolkit** panel into the **Section** positioning it immediately below the **Button**. Select the **Message** component. In the **properties** panel: * Scroll down to the **Style** section and look for the **Loading** property, which sets the color of the **Message** component when it's loading. * Click its **CSS** button, which will cause a text field to appear below it. * Enter this color value into the text field: `#D4FFF2`. ![The message component and its properties panel](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2g.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=193337b7397365784f224687ae4ca8b3) **6. Add a new Section** The **Section** that you were working on is for user input. Let's add a new **Section** to hold the output — the social media posts and tags the app will generate. Drag a **Section** component from the **Toolbox** panel and place it *inside* the **Section** that's already there, just below the **Message** component. > [!NOTE] > > That's right — **Sections** can contain other **Sections**! ![The new section inside the existing section](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2h.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=11dc51570178c77b7b1248f8b0d00110) Select the **Section** you just added. In the **properties** panel: * Find the **Title** property and clear it its value to remove the **Section**'s title. * Scroll down to the **Style** section and look for the **Container background** property, which sets the **Section**'s background color. * Click its **CSS** button, which will cause a text field to appear below it. * Enter this color value into the text field: `#F6EFFD`. ![The new section and its properties](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2i.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=462524d0c44ea635930c7c8aeda22087) **7. Add a Tags component** Writer Framework has a number of useful components to make your apps more functional and beautiful. One of these is the **Tags** component, which can take a list of hashtags (or words, or short phrases) and display them inside colorful "bubbles" to make them stand out. This app will display the social media tags it generates in a **Tags** component. Drag a **Tags** component from the **Toolbox** panel and place it inside the new **Section**. ![The tags component](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2j.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=54bac04c46c186245193ff0b18e1df9a) **8. Add a Separator** Drag a **Separator** component from the **Toolbox** panel and place it inside the new **Section**, just below the **Tags** component. This will separate the tags from the posts. ![The separator](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2k.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=3f7e4b3524ce030c809588e275930e64) **9. Add a Text component** Finally, drag a **Text** component from the **Toolbox** panel and position it below the **Separator**. This will hold the generated social media posts. ![The text component](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2l.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=33db8853d9ac0c7cdebc2e54e856da7a) ## Add the back-end code With the UI laid out, it's time to work on the logic behind it. The logic behind the user interface is defined in a file named `main.py`, which is in your project's directory. This file was automatically generated; you'll update the code in it to define the behavior of your app. The simplest way to edit `main.py` is within the project editor. Click on the "toggle code" button (beside the word **Code**) near the lower left corner of the project editor page. ![Project editor with arrow pointing to toggle code button](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2m.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=23215946becf66a071916c4bfe27aabe) A pane with the name **Code** will appear at the bottom half of the screen, displaying an editor for the the contents of `main.py`. ![Project editor with the code editor displayed](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2n.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=dcf19ac48e57128e2b3487fb23cb22d7) > [!NOTE] > > If you'd rather use a code editor instead of coding in the browser, use it to open the `main.py` file in your project's directory. Now follow these steps: **1. Import libraries and load the Writer Framework API key** You should see the following at the start of the file: ```python theme={null} import writer as wf import writer.ai ``` Replace that code with the following: ```python theme={null} import os import re import writer as wf import writer.ai # Set the API key wf.api_key = os.getenv("WRITER_API_KEY") ``` This code imports the libraries that the application will need and then reads your Writer Framework API key in the `WRITER_API_KEY` environment variable. **2. Create a handler to respond to the user's input** When the user presses the app's **Button**, the app needs to call a function to generate and display the social media posts and tags. Find these comments in the code... ```python theme={null} # Welcome to Writer Framework! # This template is a starting point for your AI apps. # More documentation is available at https://dev.writer.com/framework ``` ...and replace them with the following function: ```python theme={null} def generate_and_display_posts_and_tags(state): print(f"Here's what the user entered: {state['topic']}") # Display message state["message"] = "% Generating social media posts and tags for you..." # Generate and display social posts prompt = f"You are a social media expert. Generate 5 engaging social media posts about {state['topic']}. Include emojis, and put a blank line between each post." state["posts"] = writer.ai.complete(prompt) print(f"Posts: {state['posts']}") # Generate and display hashtags prompt = f"You are a social media expert. Generate around 5 hashtags about {state['topic']}, delimited by spaces. For example, #dogs #cats #ducks #elephants #badgers" pattern = r"#\w+" hashtags = re.findall(pattern, writer.ai.complete(prompt)) state["tags"] = {item: item for item in hashtags} print(f"Tags: {state['tags']}") # Hide message state["message"] = "" ``` The `%` at the start of the string being assigned to `state["message"]` will be replaced by a “spinning circle” progress indicator graphic in the *Message* component. The `pattern` variable in the `# Generate and display hashtags` section defines a regular expression pattern to search for words that begin with the `#` character. The `r` in front of the opening quote specifies that the string is a *raw string*, which means that the `\` character should be treated as a literal backslash and not as the start of an escape character sequence. Note that `generate_and_display_posts_and_tags()` uses `print()` functions for debugging purposes, and you can use them to get a better idea of what's happening in the function. You'll see their output in both your terminal application and in the project editor's 'log' pane (which will be covered shortly) as you use the social post generator. This output will include: * The topic the user entered * The posts generated by the LLM * The hashtags generated by the LLM The `print()` functions don't affect the operation of the social post generator in any way, and you can remove them if you wish. **3. Initialize the application** The final step is to set the application's initial state. Find this code, which should be just after the `generate_and_display_posts_and_tags()` function... ```python theme={null} # Initialise the state wf.init_state({ "my_app": { "title": "AI STARTER" }, }) ``` ...and replace it with this: ```python theme={null} # Initialize the state wf.init_state({ "topic": "writing", "message": "", "tags": {}, "posts": "", "my_app": { "title": "SOCIAL POST GENERATOR" } }) ``` The Writer Framework's `init_state()` method sets the initial value of `state`, a dictionary containing values that define the state of the application. The key-value pairs in `state` are how you store values used by your app and how you pass data between the back-end code and the UI. The code above sets the initial value of `state` so that it has these key-value pairs: * `topic`: A string containing the topic that the application should generate social media posts and tags for. You'll bind its value to the *Text Input* component where the user will enter the topic. * `message`: A string containing text of the message that will be displayed to the user while the application is generating posts and tags. You'll bind its value to the **Message** component. * `tags`: A list containing the hashtags generated by the LLM. You'll bind its value to the **Tags** component. * `posts`: A string containing the social media posts generated by the LLM. You'll bind its value to the **Text** component. * `my_app`: A dictionary containing values that define the application's appearance. This dictionary has a single key-value pair, `title`, which defines the text that appears as the application's title. > [!NOTE] > > For more details about the `state` variable, see our [*Application state*](https://dev.writer.com/framework/application-state#application-state) page. **4. Save the updated code and hide the code editor** That’s all the code. If you edited the code in the browser, save it by clicking the “save” button near the top right corner of the code editor. ![Project editor and code editor, with arrow pointing to save button](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2o.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=d8da7e0bd7c4e66f1754e538246bf465) Click the "toggle code" button to hide the code editor. ## Bind the UI to the back-end code You've built the UI and written the code behind it. Let's connect the two! Go back to the browser window with the project editor and do the following: **1. Observe that the heading at the top of the app is now 'SOCIAL POST GENERATOR'** Earlier, you saw that the **Header** component's **Text** property was set to `@{my_app.title}`, a value in the app's `state` variable. You changed this value when you update the call to the Writer Framework's `init_state()` method. **2. Bind the Text Input component to the 'state' variable's 'topic' key** Select the **Text Input** component. In the **properties** panel, scroll down to the **Binding** section and find the **State element** property. This is where you specify the `state` variable key whose value will be connected to the **Text Input** component. Set its value to `topic`. ![Updating the text input component's state element property](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2p.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=fc53611bc4959c8bad1b2d7af7e19cbb) **3. Connect the Button component to the 'generate_and_display_posts_and_tags()' function** Select the **Button** component. In the **properties** panel, scroll down to the **Events** section and find the **`wf-click`** property. This is where you specify the function to call when the user clicks the button — set its value to `generate_and_display_posts_and_tags`. ![Updating the button's wf-click property](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2q.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=c9c623a7061f1baa2ba98c606a1b8cd2) **4. Bind the Message component to the 'state' variable's 'message' key** Select the **Message** component. In the **properties** panel, find the **Message** property, which specifies the content of the **Message** component. Set its value to `@{message}`. ![Updating the message's message property](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2r.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=6ad60398867b52bd8a9843f725963a9d) **5. Bind the Tags component to the 'state' variable's 'tags' key.** Select the **Tags** component. In the **properties** panel: * Find the **Tags** property, which specifies the source of the tags that the component will display. * Click its **JSON** button. * In the text field below the **JSON** button, set the **Tags** property's value to `@{tags}`. ![Updating the tags component's tags property](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2s.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=58a4c76ca5d884b5248f9cf7d001e0d8) **6. Bind the Text component to the 'state' variable's 'posts' key** Select the **Text** component. In the **properties** panel: * Find the **Text** property, which specifies the content of the **Text** component. Set its value to `@{posts}`. * Set the **Use Markdown** property to **yes**. ![Updating the text component's properties](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2t.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=c2b407d36da8a80322e9b59726a57e3d) **7. Set the visiblity of the Section component containing the Tags and Text components based on the 'state' variable's 'posts' key** Select the **Section** component containing the **Tags** and **Text** components. In the **properties** panel: * Scroll to the **Visibility** property at the bottom. * Click on the **Custom** button. * In the **Visibility value** field, set the value to `posts`. This will cause the **Section** to be visible only when the `state` variable's `posts` key has a non-empty value. ![Updating the inner section's visibility property](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2u.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=66dd75bc9f809d79c0c176b02344ed3b) ## Test the application You've completed all the steps to make a working social post generator, and you can try using it right now, even while editing the user interface! Enter a topic into the **Topic for social posts and tags** text field, then click the **Generate Posts** button\* *twice* — the first time will cause the **properties** panel to appear, and the second click will register as a click. You'll know that you've clicked the button when you see the **Message** component display the text “Generating social media posts and tags for you...” ![Waiting for the generator to finish while the message component displays its message](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2v.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=447377026cf15c91a31ae023e09a8a40) ...and soon after that, you should see some results: ![The results](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2w.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=8592349842ed1474717e26c14496c515) To get a better sense of what the experience will be like for the user, switch to the preview by changing the edit mode (located near the upper left corner of the page) from *UI* mode to *Preview* mode by selecting the **Preview** option: ![The project editor with an arrow pointing to the Preview button](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2x.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=80d54c9686267c8e3b98c45478ecf7e9) Here’s what the app looks like in *Preview* mode: ![The working social post generator, with the project editor in "Preview" mode](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2y.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=5a85e393eff468bcadf056e260e23b95) You can see the output of any `print()` functions and error messages by clicking on the **Log** button located near the upper right corner of the page: ![The social post generator with an arrow pointing to the Log button](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2z.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=8d7cd482ba5658595eba7246578fbe28) Here’s what the app looks like when displaying the log: ![The social post generator, with the log pane displayed](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2aa.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=c27dfb7ee4bed11a5c0908343a4bac3d) It's very helpful to be able to test the application while editing it. As you continue to work with Writer Framework, you'll find yourself alternating between making changes to your application and testing those changes without having to leave the project editor. ## Run the application locally Once you've tested the application, it's time to run it locally. Switch back to your terminal application. Stop the editor with ctrl-c, then run the application by entering the following command: ``` writer run social-post-generator ``` Note that the command starts with `writer run` as opposed to `writer edit`. This launches the application as your users will see it, without any of the editing tools. Even though you can preview your applications in the project editor, it's still a good idea to test it by running it on your computer, outside the project editor, before deploying it. You'll be able to access the application with your browser at the URL that appears on the command line. It should look like this: ![Finished social post generator project](https://mintcdn.com/writer/PCF7UWM79DSDrLoF/framework/images/tutorial/social_post/sp_gen_2ab.png?fit=max\&auto=format\&n=PCF7UWM79DSDrLoF\&q=85\&s=e38dd8f9a9fe0a6b6976706902b45761) > [!NOTE] > > The Writer editor, which you launched with `writer edit social-post-generator`, and your application, which you launched with `writer run social-post-generator`, run on the same URL, but on different *ports* (specified by the number after the `:` character at the end of the URL). ## Conclusion That's it — you've built a functional social post generator using the Writer Framework! Feel free to modify this project! The Writer platform is flexible enough for you to customize, extend, and evolve your application into something completely different! To find out what else you can do, check out the documentation for [Writer Framework](https://dev.writer.com/framework/introduction) and the [Writer API](https://dev.writer.com/introduction). # State schema Source: https://dev.writer.com/framework/state-schema Schema declarations on the [Application state](./application-state) allows Framework to handle complex serialisation scenarios, while also allowing your IDE and toolchains to provide autocomplete and type checking. ## Schema declaration ```python theme={null} import writer as wf class AppSchema(wf.WriterState): counter: int initial_state = wf.init_state({ "counter": 0 }, schema=AppSchema) # Event handler # It receives the session state as an argument and mutates it def increment(state: AppSchema): state.counter += 1 ``` Accessing an attribute by its key is always possible. ```python theme={null} def increment(state: AppSchema): state["counter"] += 1 ``` Attributes missing from the schema remain accessible by their key. ```python theme={null} initial_state = wf.init_state({ "counter": 0, "message": None }, schema=AppSchema) def increment(state: AppSchema): state['message'] = "Hello pigeon" ``` ## Schema composition Schema composition allows you to model a complex Application state. ```python theme={null} class MyappSchema(wf.State): title: str class AppSchema(wf.WriterState): my_app: MyappSchema counter: int initial_state = wf.init_state({ "counter": 0, "my_app": { "title": "Nested value" } }, schema=AppSchema) ``` ## Calculated properties Calculated properties are updated automatically when a dependency changes. They can be used to calculate values derived from application state. ```python theme={null} class MyAppState(wf.State): counter: List[int] class MyState(wf.WriterState): counter: List[int] @wf.property(['counter', 'app.counter']) def total_counter(self): return sum(self.counter) + sum(self.app.counter) initial_state = wf.init_state({ "counter": 0, "my_app": { "counter": 0 } }, schema=MyState) ``` ## Multi-level dictionary Some components like *Vega Lite Chart* require specifying a graph in the form of a multi-level dictionary. A schema allows you to specify that an attribute which contains a dictionary must be treated as a dictionary, rather than as a group of state. ```python theme={null} class AppSchema(wf.WriterState): vegas_graph: dict # Without schema, this handler is execute only once def handle_vega_graph(state: AppSchema): graph = state.vega_graph graph["data"]["values"][0]["b"] += 1000 state.vega_graph = graph initial_state = wf.init_state({ "vegas_graph": { "data": { "values": [ {"a": "C", "b": 2}, {"a": "C", "b": 7}, {"a": "C", "b": 4}, {"a": "D", "b": 1}, {"a": "D", "b": 2}, {"a": "D", "b": 6}, {"a": "E", "b": 8}, {"a": "E", "b": 4}, {"a": "E", "b": 7} ] }, "mark": "bar", "encoding": { "x": {"field": "a", "type": "nominal"}, "y": {"aggregate": "average", "field": "b", "type": "quantitative"} } }, }, schema=AppSchema) ``` ## Type checking A schema allows you to check the integrity of your back-end using the type system. The code below will raise an error with mypy. ```bash theme={null} $ mypy apps/myapp/main.py apps/myapp/main.py:7: error: "AppSchema" has no attribute "countr"; maybe "counter"? [attr-defined] ``` Here is the code, can you spot the error ? ```python theme={null} import writer as wf class AppSchema(wf.WriterState): counter: int def increment(state: AppSchema): state.countr += 1 initial_state = wf.init_state({ "counter": 26, }, schema=AppSchema) ``` # Stylesheets Source: https://dev.writer.com/framework/stylesheets The appearance of your application can be fully customised via CSS stylesheets. These are dynamically linked during runtime and can be switched from the back-end, targeting all or specific sessions. ## Importing a stylesheet Stylesheet imports are triggered via Framework's `mail`, similarly to other features discussed in [Backend-initiated actions](/framework/backend-initiated-actions). When the import is triggered, the front-end downloads the specified stylesheet and creates a `style` element with its contents. The `import_stylesheet` method takes the `stylesheet_key` and `path` arguments. The first works as an identifier that will let you override the stylesheet later if needed. The second is the path to the CSS file.The path specified needs to be available to the front-end, so storing it in the `/static` folder of your app is recommended. The following code imports a stylesheet when handling an event. ```py theme={null} def handle_click(state): state.import_stylesheet("theme", "/static/custom.css") ``` In many cases, you'll want to import a stylesheet during initialisation time, for all users. This is easily achievable via the initial state, as shown below. ```py theme={null} initial_state = wf.init_state({ "counter": 1 }) initial_state.import_stylesheet("theme", "/static/custom.css") ``` > [!TIP] > > Use versions to avoid caching. During development time, stylesheets may be cached by your browser, preventing updates from being reflected. Append a querystring to bust the cache, e.g. use `/static/custom.css?3`. ## Applying CSS classes You can use the property *Custom CSS classes* in the Builder's *Component Settings* to apply classes to a component, separated by spaces. Internally, this will apply the classes to the root HTML element of the rendered component. ![Stylesheets - Component Settings](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/stylesheets.component-settings.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=7bde5b1b655bc18d64c8fe53446cb7cb) ## Tips for effective stylesheets The CSS code for the class used earlier, `bubblegum`, can be found below. Note how the `!important` flag is used when targetting style attributes that are configurable via the Builder. If the flag isn't included, these declarations will not work, because built-in Framework styling is of higher specificity. ```css theme={null} .bubblegum { background: #ff63ca !important; line-height: 1.5; transform: rotate(-5deg); } /* Targeting an element inside the component root element */ .bubblegum > h2 { color: #f9ff94 !important; } ``` > [!WARNING] > > Component structure may change. When targeting specific HTML elements inside components, take into account that the internal structure of components may change across Framework versions. Alternatively, you can override Framework's style variables. This behaves slightly differently though; style variables are inherited by children components. For example, if a *Section* has been assigned the `bubblegum` class, its children will also have a pink background by default. ```css theme={null} .bubblegum { --containerBackgroundColor: #ff63ca; --primaryTextColor: #f9ff94; line-height: 1.5; transform: rotate(-5deg); } ``` The class can be used in *Component Settings*. If the stylesheet is imported, the effect will be immediate. In case the stylesheet has been modified since imported, it'll need to be imported again. ![Stylesheets - Applied Classes](https://mintcdn.com/writer/9jV0H_SSzBim4ReZ/framework/images/stylesheets.applied-classes.png?fit=max\&auto=format\&n=9jV0H_SSzBim4ReZ\&q=85\&s=65444dbafae3a638b47f484b9d04185f) ## Targeting component types Framework components have root HTML elements with a class linked to their type. For example, *Dataframe* components use the class *CoreDataframe*. When writing a stylesheet, you can target all *Dataframe* components as shown below. ```css theme={null} .CoreDataframe { line-height: 2.0; } ``` ## Implementing themes It's possible to switch stylesheets during runtime, by specifying the same `stylesheet_key` in subsequent calls. This allows you to implement a "theme" logic if desired, targeting the whole or a specific part of your app. ```py theme={null} def handle_cyberpunk(state): state.import_stylesheet("theme", "/static/cyberpunk_theme.css") def handle_minimalist(state): state.import_stylesheet("theme", "/static/minimalist_theme.css") ``` # Testing Source: https://dev.writer.com/framework/testing Testing a Framework application is easy. Given that event handlers are plain Python functions that take arguments such as `state` and `payload`, you can inject your own and test whether the outcome is correct. This section will use `pytest` examples. ## State ### Accessing the initial state To get started, import your app's entry point, `main`. This will initialise state and make event handlers available. The initial state is available in the module, at `main.wf.initial_state` provided you imported `writer` as `wf`. ### Creating states For testing purposes, you can create your own state using the `WriterState` class in `writer.core`. Pass a dictionary when constructing it. ```py theme={null} from writer.core import WriterState artificial_state = WriterState({ "a": 3, "b": 6 }) ``` ## Example The code of a Framework application basically consists of two things: 1. Initial state 2. Event handlers It's straightforward to test both, as shown below. ### The app ```py theme={null} import writer as wf def handle_multiplication(state): state["n"] = state["a"]*state["b"] wf.init_state({ "counter": 0, "a": 0, "b": 0 }) ``` ### The tests ```py theme={null} from writer.core import WriterState import main class TestApp: initial_state = main.wf.initial_state artificial_state = WriterState({ "a": 3, "b": 2 }) def test_counter_must_start_from_zero(self): assert self.initial_state["counter"] == 0 def test_handle_multiplication(self): main.handle_multiplication(self.artificial_state) assert self.artificial_state["n"] == 6 ``` # Account management Source: https://dev.writer.com/home/account_management # Agent Builder Source: https://dev.writer.com/home/agent-builder-link # Agent Builder v2 quickstart Source: https://dev.writer.com/home/agent-builder/getting-started Create an agent, sync with GitHub, connect Cursor, Claude Code, or Codex, deploy a snapshot, and promote to production with Agent Builder v2. > [!NOTE] > > Agent Builder v2 is in open beta. Features and limitations described here are subject to change. This guide shows you how to deploy your first agent with Agent Builder v2. After completing these steps, you can create an agent in Control Center, optionally sync it with GitHub, connect your coding tool, deploy from your coding tool or the UI, test in a development environment, and promote to production. ## Prepare your environment Before you begin, make sure you have: * **Control Center access** with Agent Builder v2 enabled for your organization. Your Writer contact can confirm this. * **A coding tool**: Cursor, Claude Code, or Codex, for MCP-based deploy and environment management. * **Docker** installed locally for building and testing your application. * **Application code** with a `Dockerfile` that listens on port 8000 by default, or any other port except 8001 (which is reserved). The port is [configurable per environment](#configure-your-deployment). * **A GitHub account** if you plan to sync a repository when you create the agent or later from the GitHub tab. ## Create an agent in Control Center Start by creating an Agent Builder v2 agent in Control Center. You can sync with GitHub at creation time or start without a repository and connect one later. 1. Log in to Control Center. 2. Go to the **Agents** tab. 3. Select **Build an agent**. 4. Choose how to get started: * **Connect GitHub** to import an existing repository or create a new one. Authenticate with GitHub if prompted, then select an **Owner** and a **Repo**. You can pick an existing repository or choose **Create new repo**, enter a name, and set visibility to **Private** or **Public**. Only repositories where you are an admin appear in the list, because auto-pull needs a push webhook that only admins can add. * **Start manually** to create or upload a new application without connecting GitHub yet. Control Center generates an agent with a unique ID and a **development** environment. > [!TIP] > > If you chose **Start manually**, connect GitHub later from the agent's **GitHub** tab. After the repository is connected, create a branch to sync. Connecting a branch deploys that branch's current commit. Turn on **Auto-pull from remote** to pull when new commits appear on the remote branch. Auto-pulled commits are never promoted to production automatically. > [!WARNING] > > GitHub's authorization screen, including **Request** for organizations that require third-party access approval, appears only the first time you connect your GitHub account. If you join an organization later that needs that approval, select **Disconnect account**, then connect again to request access. ## Configure the MCP server in your coding tool After you create your agent, a **Getting started** modal guides you through connecting an AI coding tool. Connecting the MCP server gives your tool access to listing environments, deploying code, and managing environment variables. 1. In the **Select tools** step, choose **Cursor**, **Claude Code**, or **Codex**. 2. Select **Next**, then complete the **Set up MCP** step for that tool. The MCP configuration looks like this: ```json theme={null} { "mcpServers": { "writer-applications": { "url": "https://app.writer.com/mcp/applications" } } } ``` OAuth tokens refresh automatically, so you don't need to manage token expiration manually. ## Prepare your application Your application needs a `Dockerfile`. Here is an example for a Next.js application: ```dockerfile theme={null} FROM node:20-alpine AS base # ... your build stages ... FROM base AS runner ENV HOSTNAME=0.0.0.0 ENV PORT=8000 EXPOSE 8000 CMD ["node", "server.js"] ``` Your application must listen on a port other than 8001 (which is reserved). The default is 8000; if you use a different port, update it in [Configure your deployment](#configure-your-deployment) for that environment. Package your code as a `.tar.gz` tarball. For a Node.js application: ```shell theme={null} tar --exclude='node_modules' --exclude='.next' --exclude='.git' -czvf myapp.tar.gz . ``` For a Python or FastAPI application: ```shell theme={null} tar --exclude='__pycache__' --exclude='.venv' --exclude='.git' -czvf myapp.tar.gz . ``` ## Upload and deploy You can deploy through GitHub sync, the Control Center UI, or MCP from your coding tool. If a branch is connected with auto-pull enabled, new commits on that branch deploy to the synced environment without a manual upload. **Deploy through the Control Center UI** 1. Go to your agent's **Deploy** tab. 2. Select the **Development** environment. 3. Select **Import new snapshot**. 4. Drag and drop your `.tar.gz` file, or select it to browse. 5. Select **Save**. 6. Wait for the build to complete. The status changes to "In development". **Deploy through MCP from your coding tool** 1. Open Cursor, Claude Code, or Codex with the MCP server configured. 2. Ask your AI coding agent to deploy the agent to development. The MCP server packages your code and uploads it automatically. 3. You can also ask it to list environments, show revision history, or report deployment status. ## Set environment variables Environment variables are injected into your container at runtime and are encrypted at rest. 1. In Control Center, select your **Development** environment. 2. Go to the **Environment variables** tab. 3. Select **Add environment variable**. 4. Enter the variable name and value, for example `WRITER_API_KEY` or `DATABASE_URL`. 5. Save your changes. Development and production environments have separate environment variables. When you promote to production, set production-specific values separately. ## Test in development After your build completes, your application is accessible at the development URL shown in the environment detail panel. * The first load can take 2-5 seconds because of container cold start. * Subsequent requests while the container is warm are fast. * You can view build logs and deployment status in the version history tab. To iterate on your code: 1. Make changes locally. 2. Rebuild your tarball: `tar -czvf myapp.tar.gz .`. 3. Upload a new snapshot through the UI or MCP. 4. Each upload creates a new version in version history. 5. Roll back to any previous version if needed. ## Promote to production When you're satisfied with your development deployment, promote it to production. 1. Open the **Development** environment detail panel. 2. Go to the **Access** tab. 3. Select **Promote to production**. 4. Select who can access the production agent: * **Only you** for private access. * **Specific teams** to select teams from the dropdown. * **All teams** to make it available to everyone in your organization. 5. Select **Promote**. Agent Builder v2 creates a separate **production** environment with its own URL, environment variables, and version history. After you promote, the agent also appears in the [Agents tab in Writer App](#find-your-agent-in-writer-app) for you and anyone you shared it with. ## Find your agent in Writer App After you promote an agent to production, it appears in the **Agents** tab in Writer App. That list includes agents you own and agents that teammates have shared with you. ![](https://mintcdn.com/writer/Pg4chRA0RJ6SI8gu/images/home/agent-builder/agents-tab.png?fit=max\&auto=format\&n=Pg4chRA0RJ6SI8gu\&q=85\&s=9bdc1bc47fd7b1c6a40f787459bd3465) From the Agents tab you can: * Open a production agent to run it. * See the **Version** for each agent, which matches the version of that agent's production environment in Control Center. * See **Views**, which shows how many people have viewed the agent in the past 30 days. * Search and filter by **All**, **Favorites**, **Tags**, or **Owned by**. ### Organize agents with tags As your library of Agent Builder v2 agents grows, tags help you keep everything organized and find what you need. Tags are personal to you, so you can build a system that matches how you work, whether that's by use case, project, or any other category that's useful to you. 1. Go to the **Agents** tab in Writer App. 2. Hover over the agent you want to tag and select **Add tag**. 3. Create a new tag or choose an existing one to apply it. 4. Select **Manage tags** in the Tags filter to rename, delete, or recolor tags. You can apply multiple tags to a single agent if it fits more than one category. Tags only apply to your view of agents. ![](https://mintcdn.com/writer/Pg4chRA0RJ6SI8gu/images/home/agent-builder/agents-tags.png?fit=max\&auto=format\&n=Pg4chRA0RJ6SI8gu\&q=85\&s=05a182b1eea814cfc9e79762188a9c7e) ### Use bulk actions You can manage multiple agents at once from the Agents tab. Use the checkboxes next to your agents to open the bulk actions menu, then select **Add to favorites** or **Tag**. ![](https://mintcdn.com/writer/Pg4chRA0RJ6SI8gu/images/home/agent-builder/agents-bulk-actions.png?fit=max\&auto=format\&n=Pg4chRA0RJ6SI8gu\&q=85\&s=1f434b07a081bd92786886e486b4dd2f) > [!TIP] > > Use tags to create a personal organizational system that grows with your agent library. Grouping by workflow type, project, or how often you use an agent can help you find the right one faster. ## Configure your deployment Each environment has deployment settings that control how your container runs. The defaults work for most agents; adjust them when you need to tune resources, cold-start behavior, or the port your app listens on. The configuration applies to the environment's most recent version. 1. Open the environment detail panel and select **Configure deployment**. 2. Adjust the settings as needed: | Setting | Description | Default | | - | - | - | | Instance size | vCPU, RAM, and disk allocated to your container | Small: 1 vCPU, 2 GB RAM, 10 GB disk | | Sleep timeout | How long the container stays warm before going idle. Lower means lower cost and longer cold starts; higher means faster response and higher cost. | 15 minutes | | Default port | The port your application listens on inside the container. Port 8001 is reserved. | Port 8000 | 3. Select **Save**. The settings apply to the latest version in that environment. ![](https://mintcdn.com/writer/Pg4chRA0RJ6SI8gu/images/home/agent-builder/configure-deployment.png?fit=max\&auto=format\&n=Pg4chRA0RJ6SI8gu\&q=85\&s=fa5ce9180ac8ab43b81a059d517bbc00) Development and production each have their own deployment configuration, so you can tune them independently. ### Change the deployment URL Each environment has a deployment URL you can edit from the environment detail panel. Changing it retires the current URL immediately, so update any bookmarks, API callers, or integrations that still use it. 1. Open the Agent Builder v2 agent in Control Center. 2. Select the environment whose URL you want to change. 3. Select the deployment URL at the top of the environment detail panel. 4. Review the confirmation. The current URL stops working, and existing links and integrations break until you update them. 5. Optionally select **Don't warn me again for this environment** if you don't want this confirmation the next time you edit this environment's URL. 6. Select **Yes, edit URL**, then enter the new URL and save. ![](https://mintcdn.com/writer/Pg4chRA0RJ6SI8gu/images/home/agent-builder/change-deployment-url.png?fit=max\&auto=format\&n=Pg4chRA0RJ6SI8gu\&q=85\&s=ad9d57543249944a3288401facbd166e) ## Call your agent via API In addition to the UI-driven experience in Control Center, Agent Builder v2 supports headless usage. If your application exposes HTTP endpoints, you can call them programmatically from any external service, script, or frontend using an API key. This is useful when you want to: * Embed your agent into another application or product surface. * Call your agent from a backend service, scheduled job, or CI pipeline. * Integrate your agent with existing tooling outside Control Center. ### Generate an API key Each environment has its own API keys, so development and production keys are managed separately. An environment API key authenticates machine calls to that environment's `/_api` and `/api` endpoints without a user session. 1. Open your agent in Control Center and select the environment you want to call, such as **Development** or **Production**. 2. Select the three vertical dots in the environment and select **Generate API key**. 3. Select **Generate key**. 4. Copy the key when it's displayed. This is the only time the full key is shown, so store it securely in a secrets manager. ![](https://mintcdn.com/writer/Pg4chRA0RJ6SI8gu/images/home/agent-builder/generate-api-key.png?fit=max\&auto=format\&n=Pg4chRA0RJ6SI8gu\&q=85\&s=13f6294baa28d51af091c5c19dfdf1d0) ### Make a request to your agent Use the environment's deployment URL as the base URL and pass the API key as a bearer token in the `Authorization` header. You can call any endpoint your application exposes. ```shell theme={null} curl -X POST https:/// \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '' ``` The request and response shape is whatever your application defines. Agent Builder v2 doesn't enforce a specific schema, so any endpoint inside your container is callable as long as the API key is valid for that environment. ### Manage keys Each environment has one API key at a time. You can: * **Create a key** in the Control Center UI when you first need API access for an environment. * **Regenerate a key** in the Control Center UI when you need to rotate it. The old key stops working immediately and a new one is issued. ## Next steps * [Learn about Agent Builder v2](/home/agent-builder/overview) to understand supported frameworks, environments, GitHub sync, and limitations. * [Review key concepts](/home/agent-builder/overview#key-concepts) to understand environments, snapshots, and the promotion flow. # Learn about Agent Builder v2 observability Source: https://dev.writer.com/home/agent-builder/observability Use the Observability tab and environment logs to review request performance, inspect individual events, track usage, and tail server and deployment logs for an Agent Builder v2 agent. > [!NOTE] > > Agent Builder v2 is in open beta. Features and limitations described here are subject to change. Each Agent Builder v2 agent has an **Observability** tab with request-level metrics, a request log, and usage data, plus server and deployment logs for each environment. Use these views to confirm a deployment is healthy, debug a failing request, and track who's using the agent and what it's costing. > [!NOTE] > > This page covers monitoring for an individual Agent Builder v2 agent. For organization-wide observability—captured LLM calls across your account, usage and spend, and export APIs—see [Observability overview](/home/observability). To open an agent's observability views, [log in to Control Center](https://app.writer.com/controlcenter), go to the **Agents** tab, select your agent, then select **Observability**. The Observability tab has three views: **Performance**, **Events**, and **Usage**. Server and deployment logs are available separately, from each environment's **Logs** tab on the agent's **Deploy** page. ## Review request performance The Performance view shows request-level metrics for the agent's container over a selected time range, including request volume, latency, and error rate. ![The Performance view showing requests, error rate, average/p95/p99 response time, and a response-time chart over a selected date range](https://mintcdn.com/writer/1qmCY9CE1MaXZPZm/images/agent-builder/observability/performance-view.jpg?fit=max\&auto=format\&n=1qmCY9CE1MaXZPZm\&q=85\&s=d4407b7d9e960f2f235f6ecc73900462) Use the time range controls to select a preset window or a custom start and end date. The metrics update to reflect the selected range; a custom range always covers the full UTC days it spans, not just the hours within them. Watch this view after a deployment or a promotion to confirm the agent is handling traffic normally. A rising error rate or a latency spike that starts right after a deploy usually points to the new version, not to an unrelated dependency. ## Inspect individual events The Events view lists log events from the agent's container, each with an ID, timestamp, level, type, service, and message. Select a row to see more detail about that event. > [!NOTE] > > Agent Builder v2 agent events don't appear in the AI Studio or Control Center event logs. They're only visible in the agent's Observability tab. ![The Events view showing successful and error events per day, with the event log table below](https://mintcdn.com/writer/1qmCY9CE1MaXZPZm/images/agent-builder/observability/events-view.jpg?fit=max\&auto=format\&n=1qmCY9CE1MaXZPZm\&q=85\&s=fae6d849518261bb79196f6eb44d0669) An event is a single log entry from the agent's container, not a trace of everything your application code did while handling a request—it doesn't break out individual model calls, tool calls, or retries. For model-level usage, see [Track usage by team and user](#track-usage-by-team-and-user) below. Use the Events view to confirm an agent is logging activity, to find out when a specific event occurred, and to check its level—for example, whether it logged an error. ## Track usage by team and user The Usage view shows views, unique users, model requests, and spend for the agent's production deployment over a selected time range, with spend broken out per model and a table of the top authenticated users. > [!NOTE] > > The Usage view only reports on the agent's production environment. It doesn't include traffic from staging or other non-production environments. ![The Usage view showing total views, unique users, model requests, spend, a spend-per-model chart, and a top users table](https://mintcdn.com/writer/1qmCY9CE1MaXZPZm/images/agent-builder/observability/usage-view.jpg?fit=max\&auto=format\&n=1qmCY9CE1MaXZPZm\&q=85\&s=ac859eaa8fa16ba5981e859c8f138bf7) Filter by team or seat type to narrow the numbers to a specific group. Use this view to see who's using the agent, how much it's costing, and which models are driving that spend. ## Tail server and deployment logs Each environment has its own **Logs** tab, available from the agent's **Deploy** page: select an environment, then select **Logs**. The logs toggle between two views: * **Server**—streams output from the running environment, so you can see what your application is printing in real time. * **Deployment**—shows per-step build and deploy log lines with timestamps for a snapshot, so you can see exactly where a deployment succeeded or failed. ## Next steps Continue setting up and learning about Agent Builder v2 with these guides. * [Get started with Agent Builder v2](/home/agent-builder/getting-started) to create and deploy an agent. * [Learn about Agent Builder v2](/home/agent-builder/overview) for environments, snapshots, and the promotion flow. * [Review organization-wide observability](/home/observability) for captured LLM calls, usage and spend, and export APIs across Control Center. # Learn about Agent Builder v2 Source: https://dev.writer.com/home/agent-builder/overview Deploy full-code AI agents to Writer from your IDE. Sync with GitHub, connect Cursor, Claude Code, or Codex, and let Writer handle hosting, environments, and deployment. > [!NOTE] > > Agent Builder v2 is in open beta. Features and limitations described here are subject to change. Agent Builder v2 is Writer's full-code agent deployment experience. You build agents in your own IDE with the frameworks you already use, then deploy them to the Writer platform with built-in supervision and governance. This page explains what Agent Builder v2 provides, how it works, and the core concepts you need before you deploy your first agent. With Agent Builder v2, you can: * Deploy custom agents from your IDE or Control Center with no framework lock-in. * Sync an agent with GitHub when you create it, or connect a repository later from the GitHub tab. * Keep separate development and production environments, each with version history. * Manage environment variables for API keys and secrets. * Use MCP server integration with Cursor, Claude Code, or Codex to deploy and manage agents from your coding tool. * Monitor request performance, inspect individual events, and track usage from the agent's [Observability tab](/home/agent-builder/observability), and tail server and deployment logs from each environment's Logs tab on the Deploy page. ## Understand how it works You bring your application code with a `Dockerfile`. Writer handles the containerized hosting, environment management, and deployment pipeline, so you keep full control of your code and development workflow. A typical flow looks like this: 1. Create an agent in Control Center. Choose **Connect GitHub** to import or create a repository, or **Start manually** and connect GitHub later from the agent's GitHub tab. 2. Optionally connect Cursor, Claude Code, or Codex to the Writer MCP server if you want to deploy and manage the agent from your coding tool. 3. Deploy a snapshot to the development environment through GitHub sync, a UI upload, or MCP. 4. Test the development deployment, then promote it to production. For the full walkthrough, see [Get started with Agent Builder v2](/home/agent-builder/getting-started). ## Supported frameworks Agent Builder v2 deploys any dockerized Python or JavaScript/TypeScript application. The following frameworks are tested and verified: | Framework | Language | | - | - | | FastAPI | Python | | Next.js | JavaScript/TypeScript | | LangChain | Python, JavaScript/TypeScript | | LangGraph | Python, JavaScript/TypeScript | | Strands Agents | Python | | Claude Agent SDK | Python | | CrewAI | Python | | Agno | Python | | Letta | Python | | LlamaIndex | Python | | OpenAI Swarm | Python | > [!NOTE] > > If your framework isn't listed, it can still work as long as it runs in a Docker container and listens on a port other than 8001 (which is reserved). ## Key concepts Understanding environments, snapshots, GitHub sync, and the promotion flow helps you reason about how your code moves from development to production. ### Environments Each agent has separate **development** and **production** environments, and you can create additional custom environments. Each environment has its own: * Deployment URL, which you can [change](/home/agent-builder/getting-started#change-the-deployment-url) * Environment variables * Version history * Access controls (production only) ### Snapshots and versions Every time you upload code, Agent Builder v2 creates a new **snapshot** (version). For each agent you can: * View the full version history. * Roll back to any previous version. * Export a snapshot as a `.tar.gz` file. * Delete old versions. ### Promotion flow Promotion copies a snapshot from development to production. Environment variable *keys* are copied, but *values* must be set separately for production to maintain security boundaries. After promotion, the agent appears in the [Agents tab in Writer App](/home/agent-builder/getting-started#find-your-agent-in-writer-app) for you and anyone you shared it with. ### GitHub sync You can connect a GitHub repository when you create an agent or later from the agent's **GitHub** tab. After you connect a repository and a branch, Agent Builder v2 can deploy that branch's current commit and optionally auto-pull new commits from the remote. Auto-pulled commits are never promoted to production automatically. For setup steps and the organization-access limitation, see [Create an agent in Control Center](/home/agent-builder/getting-started#create-an-agent-in-control-center). ## Known limitations Agent Builder v2 has the following limitations during open beta: | Limitation | Details | | - | - | | Public deployment | Disabled during open beta. | | Deployment method | Snapshot-based deploy through GitHub sync, UI tarball upload, or MCP. Full CI/CD pipelines are not supported yet. | | GitHub organization access | GitHub's authorization screen, including requests for organizations that require third-party access approval, appears only on the first account connection. To request access for organizations you join later, disconnect the account and connect again. | | GitHub repository list | Only repositories where you are an admin are listed, because auto-pull requires a push webhook that only admins can add. | | Auto-pull | Auto-pulled commits are never promoted to production automatically. | | Cold start | The first request after inactivity takes about 2-5 seconds. | | Port | Applications must listen on a port other than 8001 (reserved). Port 8000 is the default and is configurable per environment. | | Coding tools | Getting started setup is available for Cursor, Claude Code, and Codex. | | Custom domains | Not yet available. | | Bring-your-own-cloud | Agents are hosted on Writer infrastructure. Bring-your-own-key and bring-your-own-cloud (AWS, GCP, Azure) are on the roadmap. | ## Frequently asked questions > [accordion] Can I use any model provider in my agent? > > Yes. Your agent runs as a standard container, so you can use any SDK, API, or model provider, including Writer models, OpenAI, Anthropic, and AWS Bedrock. Set the relevant API keys as environment variables. > [accordion] Can I connect to my internal databases or APIs? > > Your agent can make outbound network requests to any public endpoint. Connectivity to private databases, such as Snowflake or internal APIs, through private link is in development. Contact Writer to discuss your requirements. > [accordion] What if my framework isn't in the supported list? > > If your application runs in a Docker container and listens on a port other than 8001, it works. The supported frameworks list represents what Writer has explicitly tested. > [accordion] How do I implement authentication for my deployed agent? > > For agents accessible to Writer users (only you, specific teams, or all teams), Writer handles authentication through Control Center access controls. For custom authentication for external users, implement it within your application code, since Agent Builder v2 gives you full control of the request and response lifecycle. > [accordion] How does Agent Builder v2 relate to no-code agents? > > Agent Builder v2 is for developers who want full code control and work in their own IDE. No-code agents are for business users who build with natural language. They share the same backend infrastructure but serve distinct personas. ## Next steps * [Get started with Agent Builder v2](/home/agent-builder/getting-started) to create an agent, sync with GitHub, and deploy your first application. * [Review key concepts](#key-concepts) to understand environments, snapshots, GitHub sync, and the promotion flow. * [Agent Builder v2 observability](/home/agent-builder/observability) to review request performance, events, usage, and server/deployment logs. # API Reference Source: https://dev.writer.com/home/api-reference-link # Invoke no-code agents via the API Source: https://dev.writer.com/home/applications Turn deployed no-code agents into microservices with the Applications API. Use text generation and research agents as tools in your applications. > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. The Applications API allows you to turn deployed no-code agents into microservices, which can also be used as tools in [tool calling](/home/applications-tool-calling). Business users can define inputs, prompts, and outputs, and developers can then add them to other applications, UIs, or services. This guide shows how to use the `/applications` endpoint to generate content from no-code agents. If you do not have a deployed no-code agent, build and deploy one in [Control Center](https://app.writer.com/controlcenter). > [!WARNING] > > The `/applications` endpoint supports only agents with text generation and research capabilities. It does not support chat agents. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Endpoint overview **URL:** `POST https://api.writer.com/v1/applications/{application_id}` > [!WARNING] > > Using the `/applications` endpoint incurs charges for **model usage**. See the [pricing page](/home/pricing) for more information. ```bash cURL theme={null} curl 'https://api.writer.com/v1/applications/' \ -X POST \ -H 'Content-Type: application/json' \ -H "Authorization: Bearer $WRITER_API_KEY" \ --data-raw '{ "inputs": [ { "id": "Product description", "value": [ "Terra running shoe" ] } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.applications.generate_content( application_id="", inputs=[ { "id": "Product description", "value": ["Terra running shoe"] } ] ) print(response.suggestion) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.applications.generateContent( "", { inputs: [ { id: "Product description", value: ["Terra running shoe"] } ] } ); console.log(response.suggestion); ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `application_id` | string | The ID of the deployed agent. You can find this in the URL of the agent in Control Center: `https://app.writer.com/controlcenter/organization//applications/`. You can also use the [List applications](/api-reference/application-api/list-applications) endpoint to get the list of deployed agents and see the application ID. | ### Request body Below are the required and commonly used optional parameters for the `/applications` endpoint. | Parameter | Type | Description | | - | - | - | | `inputs` | array | Input values matching the agent's defined input fields. The input structure depends on the agent capabilities. | | `inputs[].id` | string | The name of the input field. For research, the input id is always `query`. | | `inputs[].value` | array\[string] | An array containing values of the input field. You can pass multiple values for a single input field. If the input field is a file, the value should be the `file_id` from an uploaded file, such as `["1234-abcd-1234"]`. Learn more about how to upload files with the [Files API](/home/files). | ```json theme={null} { "inputs": [ { "id": "string", "value": ["string"] } ] } ``` See the [applications endpoint reference](/api-reference/application-api/applications) for more information on the request body and the additional parameters you can use to control the agent. ### Response format The response format depends on the agent capabilities and whether you set the `stream` parameter to `true` or `false`. Only agents with research support streaming responses at this time. #### Non-streaming response If you set the `stream` parameter to `false`, the response is delivered as a JSON object with the following parameters: | Parameter | Type | Description | | - | - | - | | `title` | string | The name of the output field, as defined in the application. | | `suggestion` | string | The output of the application call. | ```json theme={null} { "title": null, "suggestion": "The Terra running shoe combines lightweight materials with advanced cushioning technology to deliver exceptional comfort and performance for every stride." } ``` #### Streaming response If you set the `stream` parameter to `true`, the response is delivered as [server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events). The event contains several parameters. The content of the chunk is in the `delta` field. You can also use the `stages` field to get the stages of the research assistant application call, such as "Planning the research" or "Researching and organizing findings." Below are the important parameters for extracting the output of the application call. | Parameter | Type | Description | | - | - | - | | `delta` | object | The content of the chunk. | | `delta.content` | string | The output of the application call. | | `delta.stages` | array | The stage of the research assistant application call. | | `delta.stages.content` | string | The content of the stage. | ```json theme={null} data: {'delta': {'title': None, 'content': None, 'stages': [{'id': 'a5d81590-0120-4404-948b-8075e3610f51', 'content': 'Initiating a research assistant: 🚗 Automotive assistant', 'sources': None}]}} ``` ## Example: Text generation Agents used for text generation generate content based on the inputs provided to a specific no-code agent created in Control Center. This is a great way to enable business users to control prompts and outputs while still allowing developers to add them to other applications, UIs, or services. To invoke text generation, you need to provide the application ID and the required inputs to the agent. Inputs are defined in the agent within Control Center. ### Get the text generation inputs To see the required inputs for the agent, you can view the agent in [Control Center](https://app.writer.com/controlcenter), or you can use the [Get application](/api-reference/application-api/application-details) endpoint to get the agent details, including the inputs. The example below shows how to use the `Get application` endpoint to get the list of required inputs with their name and types. ```bash cURL theme={null} curl --location --request GET 'https://api.writer.com/v1/applications/' \ --header "Authorization: Bearer $WRITER_API_KEY" ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() application = client.applications.retrieve( "", ) for input_ in application.inputs: print(f"{input_.name}: {input_.input_type}") ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const application = await client.applications.retrieve(""); for (const input of application.inputs) { console.log(`${input.name}: ${input.input_type}`); } ``` ### Format the request body with the application inputs The `inputs` parameter is an array of objects, each containing an `id` and `value` field. The `id` field is the name of the input field, and the `value` field is the value of the input field. ```json theme={null} { "inputs": [ { "id": "Text input name", "value": ["Input value 1"] }, { "id": "File input name", "value": ["1234-fileid-1234"] } ] } ``` If the input field is a file, the value should be the `file_id` from an [uploaded file](/api-reference/file-api/upload-files). Your request body should be formatted as a JSON object with values for each input. ### Generate content from the agent Once you've formatted the request body with the agent inputs, you can invoke the agent using the [Generate content](/api-reference/application-api/applications) endpoint. The examples below demonstrate calling an agent with text generation capabilities. The agent takes two text inputs: `Product description` and `Target audience`. ```bash cURL theme={null} curl --location --request POST 'https://api.writer.com/v1/applications/' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data-raw '{ "inputs": [ { "id": "Product description", "value": ["Terra running shoe"] }, { "id": "Target audience", "value": ["Runners"] } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.applications.generate_content( application_id="", inputs=[ { "id": "Product description", "value": ["Terra running shoe"] }, { "id": "Target audience", "value": ["Runners"] } ] ) print(response.suggestion) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.applications.generateContent( "", { inputs: [ { id: "Product description", value: ["Terra running shoe"] }, { id: "Target audience", value: ["Runners"] } ] } ); console.log(response.suggestion); ``` ## Example: Research assistant Agents with research capabilities output a final report after performing research in stages. Because of this, they support streaming responses. These agents take an array of inputs that contain a single item, formatted as a JSON object with `id` and `value` parameters. It also takes a `stream` parameter that is set to `false` by default. | Parameter | Type | Description | | - | - | - | | `inputs` | array | An array of objects, each containing an `id` and `value` field. | | `inputs[].id` | string | The name of the input field. For research assistant applications, the input id is always `query`. | | `inputs[].value` | array\[string] | An array containing the research query. | | `stream` | Boolean | Whether to stream the response. Defaults to `false`. | The examples below demonstrate calling an agent to research hotels in San Francisco. The application streams the output as it is generated. ```bash cURL theme={null} curl --location --request POST 'https://api.writer.com/v1/applications/' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data-raw '{ "inputs": [ { "id": "query", "value": ["Provide a list of three hotels in San Francisco near Union Square within the price range of $100 to $200 per night"] } ], "stream": true }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.applications.generate_content( application_id="", inputs=[ { "id": "query", "value": ["Provide a list of three hotels in San Francisco near Union Square within the price range of $100 to $200 per night"] } ], stream=True ) for chunk in response: if chunk.delta.content: print(chunk.delta.content, end="", flush=True) elif chunk.delta.stages: print(chunk.delta.stages[0].content) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.applications.generateContent( "", { inputs: [ { id: "query", value: ["Provide a list of three hotels in San Francisco near Union Square within the price range of $100 to $200 per night"] } ], stream: true } ); for await (const chunk of response) { if (chunk.delta.content) { process.stdout.write(chunk.delta.content); } else if (chunk.delta.stages) { console.log(chunk.delta.stages[0].content); } } ``` ## Next steps Now that you've invoked a no-code agent via the API, learn other ways you can use no-code agents via the API: * [Run no-code agents asynchronously](/home/async-applications) * [Use no-code agents in tool calling](/home/applications-tool-calling) # Use no-code agents as tools Source: https://dev.writer.com/home/applications-tool-calling > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. You can use deployed no-code agents as tools in [chat completions](/api-reference/completion-api/chat-completion) with Palmyra X4 and X5. This approach allows you to: * Use no-code agents alongside other tools * Chain multiple no-code agents together * Combine outputs with other API calls or business logic If you don't have a deployed no-code agent, build and deploy one with text generation or research capabilities in [Control Center](https://app.writer.com/controlcenter) to get an application ID. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Tool structure To use a no-code agent as a tool, define the tool in a `tools` array when making the request to the [chat endpoint](/home/chat-completion). The `tools` array contains an object with the following parameters: | Parameter | Type | Description | | - | - | - | | `type` | string | The type of tool, which is `function` for a no-code agent | | `function` | object | An object containing the tool's description and application ID | | `function.name` | string | The name of the tool | | `function.description` | string | A description of what the tool will be used for | | `function.parameters` | object | An object containing the tool's input parameters | | `function.parameters.type` | string | The string `object` | | `function.parameters.properties` | object | An object containing the tool's parameters in the form of a [JSON schema](https://json-schema.org/). See below for more details. | | `function.parameters.required` | array | An array of the tool's required parameters | ### function.parameters.properties The `function.parameters.properties` object contains the tool's parameter definitions as a [JSON schema](https://json-schema.org/). The object's keys should be the names of the parameters, and the values should be objects containing the parameter's type and description. When the model decides you should use the tool to answer the user's question, it will return the parameters that you should use when calling the function you've defined. Below is an example of a tool definition for a no-code agent that generates product descriptions. ```python Python theme={null} tools = [ { "type": "function", "function": { "name": "generate_product_description", "description": "A function that will invoke an agent for text-generation, specialized in generating product descriptions. Any user request asking for product descriptions should use this tool.", "parameters": { "type": "object", "properties": { "product_name": { "type": "string", "description": "The name of the product" } }, "required": ["product_name"] } } } ] ``` ```javascript JavaScript theme={null} const tools = [ { type: "function", function: { name: "generate_product_description", description: "A function that will invoke an AI agent for text-generation, specialized in generating product descriptions. Any user request asking for product descriptions should use this tool.", parameters: { type: "object", properties: { product_name: { type: "string", description: "The name of the product" } }, required: ["product_name"] } } } ]; ``` > [!NOTE] > > To help the model understand when to use the tool, follow these best practices for the `function.description` parameter: > > * Indicate that the tool is a function that invokes a no-code agent > * Specify the agent's purpose and capabilities > * Describe when the tool should be used > > An example description for a tool that invokes an agent with text-generation: > > > "A function that invokes an AI agent for text-generation, specialized in generating product descriptions. Any user request asking for product descriptions should use this tool." ### Response format When the model decides to use a custom tool, the response from the tool call is returned in the `tool_calls` object. The `tool_calls` object contains the following fields: | Parameter | Type | Description | | - | - | - | | `tool_calls[0].id` | string | The ID of the tool call | | `tool_calls[0].function` | object | An object containing the function to call | | `tool_calls[0].function.type` | string | The type of tool, which is `function` for a no-code agent | | `tool_calls[0].function.name` | string | The name of the function to call | | `tool_calls[0].function.arguments` | string | A JSON-formatted string containing the arguments to pass to the function | Here is an example of a chat completion response that includes a tool call. In this example, the model decides to use the `generate_product_description` tool to answer the user's question, and provides the arguments to pass to the function. ```json sample response[expandable] {11} theme={null} { "content": null, "refusal": null, "role": "assistant", "graph_data": { "sources": null, "status": null, "subqueries": null }, "llm_data": null, "tool_calls": [ { "id": "chatcmpl-tool-123", "function": { "arguments": "{\"product_name\": \"Terra running shoe\"}", "name": "generate_product_description" }, "type": "function", "index": null } ], "image_data": null } ``` ## Usage example The following example demonstrates how to use a no-code agent that performs text generation tasks as a tool in a chat completion. The example uses a hypothetical product description agent, but you can use any no-code agent in this way. ### Create a function that calls your deployed agent First, create a function that calls your deployed agent. You will use this function if the LLM you're chatting with decides to use the tool. The function below takes a `product_name` parameter, invokes the no-code agent with the agent's required input fields, and returns the generated product description. If you are unfamiliar with how to invoke a no-code agent with the SDK, see the [no-code agent guide](/home/applications). ```python Python theme={null} def generate_product_description(product_name): response = client.applications.generate_content( application_id="your-application-id", inputs=[ { "id": "Product name", "value": [product_name] } ] ) return response.suggestion ``` ```javascript JavaScript theme={null} async function generateProductDescription(productName) { const response = await client.applications.generateContent( "your-application-id", { inputs: [ { id: "Product name", value: [productName] } ] } ); return response.suggestion; } ``` ### Define your agent as a tool Next, define your agent as a tool so the LLM knows when to use it. See the [tool structure](#tool-structure) section for more details on the tool object. ```python Python theme={null} tools = [ { "type": "function", "function": { "name": "generate_product_description", "description": "A function that will invoke an agent for text-generation, specialized in generating product descriptions. Any user request asking for product descriptions should use this tool.", "parameters": { "type": "object", "properties": { "product_name": { "type": "string", "description": "The name of the product" } }, "required": ["product_name"] } } } ] ``` ```javascript JavaScript theme={null} const tools = [ { type: "function", function: { name: "generate_product_description", description: "A function that will invoke an agent for text-generation, specialized in generating product descriptions. Any user request asking for product descriptions should use this tool.", parameters: { type: "object", properties: { product_name: { type: "string", description: "The name of the product" } }, required: ["product_name"] } } } ]; ``` ### Use your agent as a tool in a chat completion Add the tools array to the chat endpoint call along with your array of messages. Setting `tool_choice` to `auto` allows the model to choose when to use the no-code agent tool, based on the user's question and the description of the tool. When the model decides to use the tool you've defined, it will indicate that in the `tool_calls` object of the response. This example uses a non-streaming response. For a streaming implementation, and to learn more about processing custom tool call responses, see the [tool calling guide](/home/tool-calling#processing-tool-calls). ```python Python theme={null} import json from writerai import Writer # Initialize the Writer client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() messages = [{"role": "user", "content": "Generate a description for the Terra running shoe"}] # Send the request response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto", stream=False ) # Process the response response_message = response.choices[0].message # Check if the response contains tool calls, #and if so, call the custom function tool_calls = response_message.tool_calls if tool_calls: tool_call = tool_calls[0] tool_call_id = tool_call.id function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if function_name == "generate_product_description": function_response = generate_product_description(function_args["product_name"]) messages.append({ "role": "tool", "tool_call_id": tool_call_id, "name": function_name, "content": function_response }) final_response = client.chat.chat( model="palmyra-x5", messages=messages, stream=False ) print(final_response.choices[0].message.content) # Here's a product description for the Terra running shoe: ... ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const messages = [{ role: "user", content: "Generate a description for the Terra running shoe" }]; const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, tool_choice: "auto", stream: false }); const responseMessage = response.choices[0].message; const toolCalls = responseMessage.tool_calls; // Check if the response contains tool calls, // and if so, call the custom function if (toolCalls && toolCalls.length > 0) { const toolCall = toolCalls[0]; const toolCallId = toolCall.id; const functionName = toolCall.function.name; const functionArgs = JSON.parse(toolCall.function.arguments); if (functionName === "generate_product_description") { const functionResponse = await generateProductDescription( functionArgs.product_name ); messages.push({ role: "tool", tool_call_id: toolCallId, name: functionName, content: functionResponse }); } const finalResponse = await client.chat.chat({ model: "palmyra-x5", messages: messages, stream: false }); console.log(finalResponse.choices[0].message.content); // Here's a product description for the Terra running shoe: ... } ``` Here is the full code example: ```python Python [expandable] theme={null} import json from writerai import Writer # Initialize the Writer client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() def generate_product_description(product_name): response = client.applications.generate_content( application_id="your-application-id", inputs=[ { "id": "Product name", "value": [product_name] } ] ) return response.suggestion tools = [ { "type": "function", "function": { "name": "generate_product_description", "description": "A function that will invoke an agent for text-generation, specialized in generating product descriptions. Any user request asking for product descriptions should use this tool.", "parameters": { "type": "object", "properties": { "product_name": { "type": "string", "description": "The name of the product" } }, "required": ["product_name"] } } } ] messages = [{"role": "user", "content": "Generate a description for the Terra running shoe"}] # Send the request response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto", stream=False ) # Process the response response_message = response.choices[0].message # Check if the response contains tool calls, #and if so, call the custom function tool_calls = response_message.tool_calls if tool_calls: tool_call = tool_calls[0] tool_call_id = tool_call.id function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if function_name == "generate_product_description": function_response = generate_product_description(function_args["product_name"]) messages.append({ "role": "tool", "tool_call_id": tool_call_id, "name": function_name, "content": function_response }) final_response = client.chat.chat( model="palmyra-x5", messages=messages, stream=False ) print(final_response.choices[0].message.content) # Here's a product description for the Terra running shoe: ... ``` ```javascript JavaScript [expandable] theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); async function generateProductDescription(productName) { const response = await client.applications.generateContent( "your-application-id", { inputs: [ { id: "Product name", value: [productName] } ] } ); return response.suggestion; } const tools = [ { type: "function", function: { name: "generate_product_description", description: "A function that will invoke an agent for text generation, specialized in generating product descriptions. Any user request asking for product descriptions should use this tool.", parameters: { type: "object", properties: { product_name: { type: "string", description: "The name of the product" } }, required: ["product_name"] } } } ]; const messages = [{ role: "user", content: "Generate a description for the Terra running shoe" }]; const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, tool_choice: "auto", stream: false }); const responseMessage = response.choices[0].message; const toolCalls = responseMessage.tool_calls; // Check if the response contains tool calls, // and if so, call the custom function if (toolCalls && toolCalls.length > 0) { const toolCall = toolCalls[0]; const toolCallId = toolCall.id; const functionName = toolCall.function.name; const functionArgs = JSON.parse(toolCall.function.arguments); if (functionName === "generate_product_description") { const functionResponse = await generateProductDescription( functionArgs.product_name ); messages.push({ role: "tool", tool_call_id: toolCallId, name: functionName, content: functionResponse }); } const finalResponse = await client.chat.chat({ model: "palmyra-x5", messages: messages, stream: false }); console.log(finalResponse.choices[0].message.content); // Here's a product description for the Terra running shoe: ... } ``` ## Next steps Now that you've defined a custom tool, explore other ways to extend your applications: * [Ask questions to a Knowledge Graph in a chat](/home/kg-chat) * [Delegate questions to another model](/home/model-delegation) * [Analyze images in a chat](/home/chat-with-images) # Run agents asynchronously Source: https://dev.writer.com/home/async-applications Process no-code agent requests asynchronously or in batches with the async applications API. Generate content for multiple items efficiently. > [!NOTE] > > No-code applications are now called no-code agents. The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. With asynchronous agents, your team can build and deploy no-code agents in [Control Center](https://app.writer.com/controlcenter) and use the [async applications API](/api-reference/application-api/generate-application-job) to generate content asynchronously or in batches. For example, your product team can build a no-code agent that creates product description pages, and then you can use the async applications API to generate pages in batches for multiple products. This guide helps you understand how to run async jobs. The API is similar to the [applications API](/home/applications), but it allows you to process batches of requests asynchronously. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Endpoint overview **URL:** `POST https://api.writer.com/v1/applications/{application_id}/jobs` ```bash cURL theme={null} curl 'https://api.writer.com/v1/applications//jobs' \ -X POST \ -H 'Content-Type: application/json' \ -H "Authorization: Bearer $WRITER_API_KEY" \ --data-raw '{ "inputs": [ { "id": "Input name", "value": [ "Input value" ] } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() job_response = client.applications.jobs.create( application_id="", inputs=[ { "id": "Input name", "value": [ "Input value" ] } ] ) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.applications.jobs.create( "", { inputs: [ { id: "Input name", value: [ "Input value" ] } ] } ) ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `application_id` | `string` | The ID of the no-code agent | ### Request body The async applications API has the same request body structure as the [no-code agents API](/home/applications#request-body). It should contain an array of input objects matching the no-code agent's input schema. ### Response format A successful job creation request returns a JSON object with the following structure: | Parameter | Type | Description | | - | - | - | | `job_id` | `string` | The ID of the job | | `status` | `string` | The status of the job. Can be `in_progress`, `completed`, or `failed`. | | `created_at` | `string` | The date and time the job was created | ```json theme={null} { "job_id": "123-456-789", "status": "in_progress", "created_at": "2024-03-15T10:00:00Z" } ``` ## Usage example The following example demonstrates using the async applications API to generate content asynchronously with a hypothetical product description generation agent. ### Create and deploy a no-code agent First, create and deploy a no-code agent in [Control Center](https://app.writer.com/controlcenter). ### Create an async job Send a `POST` request with the inputs for the agent to create an async job. ```bash cURL theme={null} curl 'https://api.writer.com/v1/applications//jobs' \ -X POST \ -H 'Content-Type: application/json' \ -H "Authorization: Bearer $WRITER_API_KEY" \ --data-raw '{ "inputs": [ { "id": "Product descriptions", "value": [ "Terra running shoe", "Aqua swim goggles", "Flex yoga mat" ] } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() job = client.applications.jobs.create( application_id="", inputs=[ { "id": "Product descriptions", "value": [ "Terra running shoe", "Aqua swim goggles", "Flex yoga mat" ] } ], ) print(f"Created job: {job.id}") ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const job = await client.applications.jobs.create( "", { inputs: [ { id: "Product descriptions", value: [ "Terra running shoe", "Aqua swim goggles", "Flex yoga mat" ] } ] } ); console.log(`Created job: ${job.id}`); ``` ### Check job status Use the job ID from the creation response to check the status of your job and see the results. ```bash cURL theme={null} curl 'https://api.writer.com/v1/applications/jobs/' \ -H "Authorization: Bearer $WRITER_API_KEY" ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() job_status = client.applications.jobs.retrieve("") print(f"Job status: {job_status.status}") if job_status.status == "completed": print(f"Job results: {job_status.data.suggestion}") ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const jobStatus = await client.applications.jobs.retrieve(""); console.log(`Job status: ${jobStatus.status}`); if (jobStatus.status === "completed") { console.log(`Job results: ${jobStatus.data.suggestion}`); } ``` The response includes the current status. If the job has completed, the results are in the `data.suggestion` field, which has the same structure as the [no-code agents API](/home/applications#response-format). ```json theme={null} { "id": "123-456-789", "status": "completed", "application_id": "2932402-23429023894-234234234", "created_at": "2025-02-10T18:18:09.501223Z", "completed_at": "2025-02-10T18:18:14.470324Z", "data": { "title": "Social post", "suggestion": "# Social post\nImage: A photo of a person running in a pair of Terra running shoes.\n\nCaption:\n\nIntroducing the all-new Terra running shoe, designed to take you further than ever before. With its innovative cushioning system and durable outsole, the Terra is perfect for runners of all levels.\n\nWhether you're hitting the trails or pounding the pavement, the Terra will keep you comfortable and supported mile after mile. So what are you waiting for? Lace up a pair of Terras and start your journey today!\n\n#TerraRunningShoe #RunFurther #NeverStopExploring #GetOutside" }, "error": null } ``` ### List all jobs You can retrieve all jobs for an application to monitor batch processing: ```bash cURL theme={null} curl 'https://api.writer.com/v1/applications//jobs' \ -H "Authorization: Bearer $WRITER_API_KEY" ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() jobs = client.applications.jobs.list( application_id="" ) for job in jobs.result: print(f"Job {job.id}: {job.status}") ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const jobs = await client.applications.jobs.list( "" ); jobs.result.forEach(job => { console.log(`Job ${job.id}: ${job.status}`); }); ``` ### Retry failed jobs If a job fails, you can retry it using the retry endpoint: ```bash cURL theme={null} curl 'https://api.writer.com/v1/applications/jobs//retry' \ -X POST \ -H "Authorization: Bearer $WRITER_API_KEY" ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() retry_response = client.applications.jobs.retry("") print(f"Retried job: {retry_response.id}") ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const retryResponse = await client.applications.jobs.retry(""); console.log(`Retried job: ${retryResponse.id}`); ``` ## Next steps By following this guide, you can use the async Applications API to handle large-scale tasks. Next, learn how to enhance your no-code agents with [Knowledge Graph](/home/knowledge-graph), our tool for RAG. # Export audit events Source: https://dev.writer.com/home/audit-events-export Poll organization audit events with the Audit Events Export API, and resume the feed from a cursor. This guide shows you how to poll organization audit events with the Audit Events Export API. After you connect a poller or an incremental connector, you can land those records in a data warehouse, SIEM, or compliance platform. The feed combines Writer's two audit contracts (legacy administration events and newer platform audit events) into one stream, discriminated by a `source` field on every row. You do not need separate pollers for each contract. ## Prerequisites Before you export audit events, make sure you have: * A Writer API key. See instructions in the [API keys guide](/api-reference/api-keys). ## Call the export endpoint Request audit events for one organization. **URL:** `GET https://api.writer.com/api/observability/v1/organization/{organizationId}/audit/events/export` Call it with `order=tail` and no `cursor` or `start_date` to start at the current time. Only newly settled rows stream forward. ```bash cURL theme={null} curl --get --location \ "https://api.writer.com/api/observability/v1/organization//audit/events/export" \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data-urlencode "order=tail" \ --data-urlencode "limit=1000" ``` ```python Python theme={null} import os import requests organization_id = "" api_key = os.environ["WRITER_API_KEY"] response = requests.get( "https://api.writer.com/api/observability/v1/organization/" f"{organization_id}/audit/events/export", headers={"Authorization": f"Bearer {api_key}"}, params={"order": "tail", "limit": 1000}, timeout=60, ) response.raise_for_status() print(response.json()) print(response.headers["x-next-cursor"]) ``` ```javascript JavaScript theme={null} const organizationId = ""; const apiKey = process.env.WRITER_API_KEY; const params = new URLSearchParams({ order: "tail", limit: "1000", }); const response = await fetch( `https://api.writer.com/api/observability/v1/organization/${organizationId}/audit/events/export?${params}`, { headers: { Authorization: `Bearer ${apiKey}` } }, ); if (!response.ok) { throw new Error(`Export request failed with status ${response.status}`); } const body = await response.json(); console.log(body); console.log(response.headers.get("x-next-cursor")); ``` ## Authenticate requests Send the Writer API key on every request. ```http theme={null} Authorization: Bearer ``` Each key is bound to a single organization and can export audit events only for that organization. A request that uses a key against a different `organizationId` returns `403 Forbidden`. Missing or malformed credentials return `401 Unauthorized` at the public authentication boundary. ## Choose a start point You choose where the stream begins. After the first response, page with the cursor alone. The cursor already encodes your position and, for a browse continuation, the window it was cut from. ### Start from the current time Call the endpoint with `order=tail` and neither `cursor` nor `start_date`. The stream starts at the current time, with no backfill. ### Backfill from a date Pass `start_date` with `order=tail` to request retained events from that ingestion time, then continue polling after the backlog drains. `start_date` accepts an ISO-8601 timestamp, epoch seconds, or epoch milliseconds. For example, `start_date=2026-07-01T00:00:00Z`. ### Browse a historical window Pass both `start_date` and `end_date` with `order=browse` (the default) to walk a bounded `[start_date, end_date]` window newest-first. The response's `total_count` is the exact number of events in the window, independent of `limit` and `cursor`. Omit both dates to browse the default window (now minus 90 days through now). ### Stay inside the retention window A `start_date` older than the retention window (90 days by default) returns `400 Validation Error`. Available history depends on completed backfills; this does not guarantee full historical coverage. ### Page with the cursor alone After you store `x-next-cursor`, send it as the `cursor` query parameter and omit `start_date` and `end_date`. Sending either date together with `cursor` returns `400` because the cursor already encodes the window. The cursor is scoped to the order (`browse` or `tail`) that issued it; presenting a browse cursor with `order=tail` (or the reverse) returns `400`. ## Set query parameters These parameters control paging and the browse window. The audit export has no filters, no `format` option, and no `include_bodies` option. It always returns native JSON. | Parameter | Values | Default | Description | | - | - | - | - | | `order` | `browse`, `tail` | `browse` | `tail` selects the incremental stream. | | `cursor` | Opaque string | None | Resume token from a prior `x-next-cursor` header. Scoped to the order that issued it. | | `start_date` | ISO-8601, epoch seconds, or epoch milliseconds | Tail: now; browse: now minus 90 days if both dates are omitted | Tail backfill start, mutually exclusive with `cursor`. Browse window start. | | `end_date` | ISO-8601, epoch seconds, or epoch milliseconds | Browse: now if both dates are omitted | Browse window end. Rejected when `order=tail`. | | `limit` | Integer ≥ 1 | `100` | Page size. Clamped to 1000; a larger value is reduced rather than rejected. | For `order=browse`, provide both `start_date` and `end_date`, or omit both. Providing only one date returns `400 Validation Error`. ## Read the response Responses put the resume token and the caught-up signal in headers. The body mirrors them in `pagination` so a consumer can read either. ### Read response headers Use these headers to resume and, in tail mode, decide when the settled backlog is drained. | Header | Meaning | | - | - | | `x-next-cursor` | Opaque resume token. Set while another page is available, and on every tail response. A caught-up tail echoes the current position. Absent on the last browse page. | | `x-has-more` | `true` when another page is immediately available. `false` when the stream is caught up (tail) or on the last window page (browse). | | `x-total-count` | `order=browse` only: exact number of events in `[start_date, end_date]`, independent of `limit` and `cursor`. | | `x-tail-watermark` | `order=tail` only: settled boundary in epoch milliseconds. The boundary is now minus a 5-minute settle lag. Rows with `inserted_at_ms` newer than this value are withheld from the page until they settle. | | `retry-after` | Seconds to wait. Present only on `429`. | ### Read the body The body is a JSON object. `result` holds the audit event rows. On a browse response, `total_count` repeats `x-total-count`. `pagination.next_cursor` mirrors `x-next-cursor` while another page is available, and is `null` on the last browse page; a tail response always sets it. For example: ```json theme={null} { "result": [ { "event_id": "01HR9F8PZ9S2E9S7D8EXAMPLE1", "organization_id": 644693, "event_time_ms": 1761148800000, "inserted_at_ms": 1761148812345, "source": "platform_audit_event", "event_category": "auth", "audit_event_type": "auth_login_success", "outcome_result": "SUCCESS", "outcome_reason": null, "outcome_reason_description": null, "actor_id": "9321", "actor_type": "USER", "actor_alternate_id": null, "actor_display_name": "jane.doe@example.com", "actor_impersonator_id": null, "client_ip_address": "203.0.113.42", "client_country": "US", "request_method": "POST", "request_path": "/api/auth/login", "response_status_code": 200, "response_time_ms": 42, "response_error_code": null, "parent_event_id": null, "action_id": null, "targets": [{ "type": "User", "id": "9321" }], "metadata": { "mfa": "totp" } } ], "total_count": 1, "pagination": { "limit": 1000, "has_more": false, "next_cursor": null } } ``` ## Read row fields Every event row carries both ordering axes and the stored actor record. Use `event_id` as the upsert key. | Field | Type | Notes | | - | - | - | | `event_id` | string | Stable event identity. Upsert key. A re-ingested revision reuses this ID with a newer `inserted_at_ms` (tail only). | | `organization_id` | integer | The organization the event belongs to; matches the path. | | `event_time_ms` | integer | Event time, epoch ms. Browse ordering axis. | | `inserted_at_ms` | integer | Ingestion time, epoch ms. Tail ordering axis. | | `source` | string | `reporting_admin_audit` for legacy administration events, `platform_audit_event` for newer platform audit events. Discriminates row shape in `targets`. | | `event_category` | string | One of `admin`, `api`, `auth`, `authz`. Platform events may introduce new categories over time. | | `audit_event_type` | string | Raw type as stored; legacy types verbatim, platform types as emitted. Not translated to a catalog label. | | `outcome_result` | string | `SUCCESS`, `FAILURE`, `PARTIAL`, or `UNKNOWN`. | | `outcome_reason` | string \| null | Short reason code when the outcome is not `SUCCESS`. | | `outcome_reason_description` | string \| null | Human-readable reason, when available. | | `actor_id` | string | Stable actor identifier. | | `actor_type` | string | `USER`, `SERVICE`, `API_KEY`, `ANONYMOUS`, or another emitted type. | | `actor_alternate_id` | string \| null | A secondary identifier for the actor (such as an external IdP subject), when available. | | `actor_display_name` | string \| null | Display name as stored on the event. Not refreshed from the user directory. | | `actor_impersonator_id` | string \| null | Impersonator's actor identifier, when the event was recorded under impersonation. | | `client_ip_address` | string \| null | Caller IP as recorded by the service. | | `client_country` | string \| null | ISO country code resolved from the client IP, when available. | | `request_method` | string \| null | HTTP method on the originating request, when the event was recorded on an HTTP path. | | `request_path` | string \| null | HTTP path on the originating request, when the event was recorded on an HTTP path. | | `response_status_code` | integer \| null | HTTP status code on the originating response, when the event was recorded on an HTTP path. | | `response_time_ms` | integer \| null | Response time of the originating request in milliseconds, when the event was recorded on an HTTP path. | | `response_error_code` | string \| null | Service error code on failure, when available. | | `parent_event_id` | string \| null | Parent event's `event_id` when the audit record belongs to a chain. | | `action_id` | string \| null | Correlation identifier shared with Writer action logs, when available. | | `targets` | array \| null | Parsed platform targets (resources the event acted on). Always `null` for `source=reporting_admin_audit`; emitted platform events populate it. | | `metadata` | object | Parsed event payload: the legacy `data` object for `reporting_admin_audit`, or the whole platform `event` branch for `platform_audit_event`. Shape varies by type. | > [!NOTE] > > The export row reflects the stored audit record. The actor's current directory > name, email, and avatar are not joined in on the export, so historical events > stay stable when users rename or leave the organization. Use `actor_id` to > join against your own directory snapshot when you need the current identity. ## Store and resend the cursor The cursor is a versioned, HMAC-signed token. Treat it as an opaque string. Store it verbatim and send it back unchanged on the `cursor` parameter. > [!WARNING] > > Do not parse, truncate, or reconstruct the cursor. A tampered or > version-incompatible token returns `400 Validation Error` with detail `Invalid > cursor`. A browse cursor also carries the `(start_date, end_date)` window it > was cut from, so changing the window on a continuation is rejected with > `cursor was issued for a different from_ms/to_ms window; restart paging without a cursor`. ## Apply delivery guarantees Tail mode is an ordered revision feed. The settlement delay does not make an event immutable, and a cursor identifies a position rather than a fixed snapshot. * **Browse ordering.** Browse pages return in `(event_time_ms DESC, event_id DESC)` order within the requested window. Browse collapses to the latest revision per `event_id`. * **Tail ordering.** Tail pages return in `(inserted_at_ms ASC, event_id ASC)` order. Replaying a cursor returns no row that ordered before that cursor. * **Settled window.** A tail page contains only rows whose `inserted_at_ms` is at or before `x-tail-watermark`. The watermark is now minus a 5-minute settle lag. An event with an older `event_time_ms` and a newer `inserted_at_ms` arrives when the watermark passes that `inserted_at_ms`. Settlement is not record finality. * **Revision-aware upserts.** Later revisions can deliver the same `event_id` again on tail. Upsert on `event_id`, retaining the newest `inserted_at_ms`, so an older replay cannot overwrite a newer revision. Never permanently discard an ID because you have already seen it. * **Replay.** Replaying a cursor can observe newer rows at or after that position. After the stream is caught up, polling again can return newly settled rows. ## Stay within limits Each organization has a fixed window of 120 requests per 60 seconds by default. A request over that limit returns `429 Rate Limited` with a `retry-after` header. The value is the whole seconds until the window resets, with a minimum of one second. The limit is checked before authentication. Wait for `retry-after`, then retry. `limit` is clamped to 1000. A larger value is reduced to 1000 rather than rejected. ## Handle errors Service error bodies use the Problem+JSON shape, with `code` and `detail`. Gateway authentication errors can use a different envelope: an unauthenticated public request can return `401` with generic JSON rather than the service Problem+JSON shape. Handle the HTTP status even when the body does not contain a service error code. | Status | Code | When | | - | - | - | | `400` | `VALIDATION_ERROR` | Tampered or version-incompatible cursor. `start_date` older than retention. `end_date` with tail. `start_date` with `cursor`. Only one browse date bound. Browse cursor presented with `order=tail` (or the reverse). Browse continuation whose cursor was issued for a different `(start_date, end_date)`. | | `401` | `UNAUTHORIZED` or gateway-specific | Missing, malformed, or rejected credentials at the public authentication boundary. | | `403` | `FORBIDDEN` or gateway-specific | The key targets a different organization, or the gateway or API-key verifier denies access. | | `429` | `RATE_LIMITED` | The per-organization rate limit is exceeded. The response includes `retry-after`. | ## Poll for new audit events Poll with the returned `x-next-cursor` to pick up newly settled events and revisions: * **Drain and pause:** Drain settled pages until `x-has-more` is `false`, then pause before polling again. * **Upsert revisions:** Upsert by `event_id`, retaining the newest `inserted_at_ms`. A primary key alone does not prevent older retries from overwriting newer revisions. * **Persist cursor:** Save the cursor only after the complete page is successfully processed. Restart from that saved cursor. These examples keep the cursor in memory only. * **Handle rate limits:** On `429`, wait for `retry-after` before retrying. The 30-second pause in these examples applies after the stream is caught up. The Python and JavaScript examples emit each complete row revision as JSON to stdout. The cURL example prints each response body. ```bash cURL theme={null} #!/usr/bin/env bash set -euo pipefail organization_id="" poll_interval_seconds=30 cursor="" base_url="https://api.writer.com/api/observability/v1/organization/${organization_id}/audit/events/export" while true; do headers_file=$(mktemp) body_file=$(mktemp) args=( --silent --show-error --get --location --output "$body_file" --dump-header "$headers_file" --header "Authorization: Bearer ${WRITER_API_KEY}" --data-urlencode "order=tail" --data-urlencode "limit=1000" ) if [[ -n "$cursor" ]]; then args+=(--data-urlencode "cursor=${cursor}") fi status=$(curl "${args[@]}" --write-out "%{http_code}" "$base_url") if [[ "$status" == "429" ]]; then retry_after=$(grep -i '^retry-after:' "$headers_file" | tail -n 1 | awk '{print $2}' | tr -d '\r') rm -f "$headers_file" "$body_file" sleep "${retry_after:-1}" continue fi if [[ "$status" != "200" ]]; then echo "Export request failed with status ${status}" >&2 cat "$body_file" >&2 rm -f "$headers_file" "$body_file" exit 1 fi cat "$body_file" echo cursor=$(grep -i '^x-next-cursor:' "$headers_file" | tail -n 1 | cut -d' ' -f2- | tr -d '\r') has_more=$(grep -i '^x-has-more:' "$headers_file" | tail -n 1 | awk '{print $2}' | tr -d '\r') rm -f "$headers_file" "$body_file" if [[ "$has_more" != "true" ]]; then sleep "$poll_interval_seconds" fi done ``` ```python Python theme={null} import json import os import time import requests organization_id = "" api_key = os.environ["WRITER_API_KEY"] poll_interval_seconds = 30 cursor = None url = ( "https://api.writer.com/api/observability/v1/organization/" f"{organization_id}/audit/events/export" ) while True: params = {"order": "tail", "limit": 1000} if cursor: params["cursor"] = cursor response = requests.get( url, headers={"Authorization": f"Bearer {api_key}"}, params=params, timeout=60, ) if response.status_code == 429: retry_after = int(response.headers.get("retry-after", "1")) time.sleep(max(retry_after, 1)) continue response.raise_for_status() for row in response.json()["result"]: print(json.dumps(row), flush=True) cursor = response.headers["x-next-cursor"] if response.headers.get("x-has-more") != "true": time.sleep(poll_interval_seconds) ``` ```javascript JavaScript theme={null} const organizationId = ""; const apiKey = process.env.WRITER_API_KEY; const pollIntervalMs = 30000; let cursor = null; function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function pollAuditEvents() { const url = `https://api.writer.com/api/observability/v1/organization/${organizationId}/audit/events/export`; while (true) { const params = new URLSearchParams({ order: "tail", limit: "1000", }); if (cursor) { params.set("cursor", cursor); } const response = await fetch(`${url}?${params}`, { headers: { Authorization: `Bearer ${apiKey}` }, }); if (response.status === 429) { const retryAfter = Number(response.headers.get("retry-after") ?? "1"); await sleep(Math.max(retryAfter, 1) * 1000); continue; } if (!response.ok) { throw new Error(`Export request failed with status ${response.status}`); } const body = await response.json(); for (const row of body.result) { console.log(JSON.stringify(row)); } cursor = response.headers.get("x-next-cursor"); if (response.headers.get("x-has-more") !== "true") { await sleep(pollIntervalMs); } } } pollAuditEvents(); ``` ## Connect Airbyte, Fivetran, or Singer The cursor and caught-up signal are header strings, so an incremental connector can store them as a bookmark. Read `x-next-cursor` from the header, emit every revision, and configure the destination to upsert on `event_id`, retaining the newest `inserted_at_ms`. Save the bookmark only after the destination processes the page. The same mapping that the [Logs Export](/home/logs-export#connect-airbyte-fivetran-or-singer) uses applies here, with `event_id` as the record primary key instead of `log_id`. On `429`, honor `retry-after` before retrying. ## Review default limits These operational defaults apply to the audit events export. To request different values, contact your Customer Success team. | Setting | Default | Effect | | - | - | - | | Settle lag | 5 minutes | Withholds rows newer than now minus the lag; later revisions can still arrive. | | Export retention | 90 days | Oldest `start_date` a tail backfill can request. | | Rate limit (requests) | 120 | Requests per window, per organization. | | Rate limit (window) | 60 seconds | Length of the rate-limit window. | | Page size | 1000 | Maximum `limit`; a larger value is clamped rather than rejected. | ## Next steps Pull related telemetry alongside your audit events. * [Export logs](/home/logs-export): Poll captured LLM calls, agent-run records, and agent feedback into a warehouse or SIEM * [Event logs](/home/event-logs): View, filter, and search request logs in Control Center # Engineering Blog Source: https://dev.writer.com/home/blog # Changelog Source: https://dev.writer.com/home/changelog Stay up to date with the latest changes to the Writer API and SDKs. > [!TIP] > > To see the latest features and major improvements across the Writer platform, check out [What's new at Writer](https://support.writer.com/article/40-whats-new-at-writer). **2026-06-02** Python and Node SDK v3.0.0 ## Released version 3.0.0 of the Python and Node SDKs Version 3.0.0 of the [Python](https://github.com/writer/writer-python) and [Node](https://github.com/writer/writer-node) SDKs includes the following changes: * Removes AI detection, Medical Comprehend, and Context-Aware Text Splitting from the Python and Node SDKs * Removes deprecated MCP tool schemes from the Node SDK MCP server See below for more details about each of these changes. ### Removed API methods Version 3.0.0 removes the following methods from the Python and Node SDKs. You cannot call these methods in 3.0.0: * AI detection * [Medical Comprehend](/api-reference/migration-guides/comprehend-medical) * Context-Aware Text Splitting If your application uses any of these methods, update your code before upgrading to 3.0.0. ### Node SDK The Node SDK MCP server now only supports **code mode**. Removed tool schemes: * **All tools** (`--tools=all`): exposed one MCP tool per API endpoint * **Dynamic tools** (`--tools=dynamic`): exposed tools to discover and invoke API endpoints dynamically Removed flags also include `--resources`, `--tags`, `--client`, and related filtering and compatibility options. Before upgrading to 3.0.0, remove those flags from your startup command and invoke the server with `npx -y writer-sdk-mcp@latest` or `node /path/to/mcp/server`. Supported flags are `--port`, `--transport`, `--socket`, and `--tools=docs`. **2026-02-06** Python SDK v2.4.0 ## Released version 2.4.0 of the Python SDK Version 2.4.0 of the [Python SDK](https://github.com/writer/writer-python) includes updated default retry behavior and Knowledge Graph file upload support. ### Default retry behavior Retry defaults are now: * **Maximum retries**: 7 attempts * **Initial delay**: 1 second * **Maximum delay**: 60 seconds Override these defaults by passing `max_retries` when instantiating the client. See the [Python SDK documentation](https://github.com/writer/writer-python) for details. ### Knowledge Graph file upload support You can now pass the `graphId` parameter when [uploading files](/home/files#upload-a-file) to associate files with a Knowledge Graph during upload. When you provide a `graphId`, the uploaded file is automatically attached to the specified Knowledge Graph. ```python Python theme={null} from pathlib import Path from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() file_path = Path("") # Replace with your file path, for example: /path/to/document.pdf file_name = file_path.name # Get the filename from the path file_ = client.files.upload( content=file_path.read_bytes(), content_disposition=f"attachment; filename={file_name}", # Replace with your file name, for example: document.pdf content_type="application/pdf", graph_id="" # Replace with your Knowledge Graph ID, for example: 6029b226-1ee0-4239-a1b0-cdeebfa3ad5a ) print(file_.id) ``` ```javascript JavaScript theme={null} import fs from 'fs'; import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const file = await client.files.upload({ content: fs.createReadStream(""), // Replace with your file path, for example: /path/to/document.pdf "Content-Disposition": "attachment; filename=", // Replace with your file name, for example: document.pdf "Content-Type": "application/pdf", // Replace with your file type, for example: application/pdf graphId: "" // Replace with your Knowledge Graph ID, for example: 6029b226-1ee0-4239-a1b0-cdeebfa3ad5a }); console.log(file.id); ``` For more information, see the [file management guide](/home/files#upload-a-file). **2025-12-02** External models and guardrails ## External models and guardrails now available You can now add external models from providers like AWS Bedrock to use alongside Palmyra models in AI Studio. You can also configure guardrails from third-party providers such as AWS Bedrock to monitor and filter agent inputs and outputs, helping enforce content safety and compliance. ### External models Add models from AWS Bedrock directly in the AI Studio UI. Once configured, external models appear in the [list models endpoint](/api-reference/completion-api/list-models) and can be used in chat completions by specifying the model ID. To use an external model, pass its model ID to the `model` parameter in your API requests: ```bash theme={null} curl -X POST https://api.writer.com/v1/chat \ -H "Authorization: Bearer $WRITER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-external-model-id", "messages": [{"role": "user", "content": "Hello!"}] }' ``` For setup instructions, see the [external models guide](/home/external-models). ### Guardrails Configure AWS Bedrock Guardrails to enforce content safety, PII protection, and compliance policies across your AI agents. Guardrails can evaluate requests before, during, or after model calls. For setup instructions, see the [guardrails guide](/home/guardrails). **2025-10-03** Python and Node SDK v2.3.2 ## Released version 2.3.2 of the Python and Node SDKs Version 2.3.2 of the [Python](https://github.com/writer/writer-python) and [Node](https://github.com/writer/writer-node) SDKs adds support for the following new features: ### Knowledge Graph query configuration Added support for the `query_config` parameter in both chat completions with Knowledge Graph tools and direct Knowledge Graph queries. This parameter allows you to fine-tune search behavior and control response generation. Key configuration options: * **`inline_citations`**: Enable inline citations within response text * **`search_weight`**: Control the balance between keyword and semantic search * **`grounding_level`**: Control how closely responses match source material * **`max_snippets`**: Set the number of text snippets to retrieve * **`keyword_threshold`**: Set keyword matching strictness * **`semantic_threshold`**: Set semantic similarity requirements ### Inline citations SDK support for inline citations in Knowledge Graph responses, allowing you to programmatically extract and correlate citations with their source material. Citations appear in the format `[filename](cite_id)` within response text and you can match them with source data from the `references` object. ### Upload types for no-code applications Added support for the `upload_types` parameter in no-code applications, allowing you to see which file types you can upload through file input fields. For more details on these features: * Knowledge Graph query configuration: [Knowledge Graph query configuration guide](/home/knowledge-graph-query-config) * Inline citations: [Work with inline citations](/home/inline-citations) * Upload types: [No-code applications API reference](/api-reference/application-api/application-details) **2025-09-11** Knowledge Graph query configuration and inline citations ## Knowledge Graph query configuration and inline citations Added comprehensive query configuration options for Knowledge Graph operations, allowing you to fine-tune search behavior and enable inline citations in responses from the [Knowledge Graph chat completions tool](/home/kg-chat) and [direct Knowledge Graph queries](/home/kg-query). ### New query configuration parameters The `query_config` parameter is now available for both chat completions with Knowledge Graph tools and direct Knowledge Graph queries. This parameter includes: * **`inline_citations`**: Enable inline citations within response text, showing which sources support each part of the response * **`search_weight`**: Control the balance between keyword and semantic search (0-100, default: 50) * **`max_subquestions`**: Set the maximum number of sub-questions for complex queries (1-10, default: 6) * **`grounding_level`**: Control how closely responses match source material (0.0-1.0, default: 0.0) * **`max_snippets`**: Set the number of text snippets to retrieve (5-25 recommended, default: 30) * **`max_tokens`**: Control the maximum response length (100-8000, default: 4000) * **`keyword_threshold`**: Set keyword matching strictness (0.0-1.0, default: 0.7) * **`semantic_threshold`**: Set semantic similarity requirements (0.0-1.0, default: 0.7) For detailed information about all configuration options and their effects, see the [Knowledge Graph query configuration guide](/home/knowledge-graph-query-config). For more information about inline citations, see the [Work with inline citations in Knowledge Graph responses](/home/inline-citations) guide. **2025-08-20** Python and Node SDK v2.3.1 ## Released version 2.3.1 of the Python and Node SDKs This patch release fixes a bug introduced in version 2.3.0 where the `Graph` class wasn't accessible. The `Graph` class is now available in the Python and Node SDKs as it was previously. For more information on working with Knowledge Graphs with the Python and Node SDKs, see the [Knowledge Graphs usage guide](/home/knowledge-graph). **2025-08-19** langchain-writer v0.3.3 ## langchain-writer v0.3.3 The [langchain-writer](https://github.com/writer/langchain-writer) package now includes the [web search tool](/home/web-search-tool) for chat completions. This tool allows you to search the web for current information during a conversation with a Palmyra model. For more details, see the [langchain-writer changelog](https://github.com/writer/langchain-writer/releases/tag/v0.3.3). **2025-08-14** Python and Node SDK v2.3.0 ## Released version 2.3.0 of the Python and Node SDKs Version 2.3.0 of the [Python](https://github.com/writer/writer-python) and [Node](https://github.com/writer/writer-node) SDKs adds support for the following new features: * [Web search API](#web-search-api) * [Web search tool for chat completions](#web-search-tool-for-chat-completions) * [Web connector URLs for Knowledge Graphs](#web-connector-urls-for-knowledge-graphs) * [Image support in chat completions](#image-support-in-chat-completions) See below for more details about each of these features. ### Web search and web connector URLs Three new features are now available to enhance your AI applications with web content and search capabilities: * [Web search tool API](#web-search-tool-api) * [Web search tool for chat completions](#web-search-tool-for-chat-completions) * [Web connector URLs for Knowledge Graphs](#web-connector-urls-for-knowledge-graphs) #### Web search API The new [web search tool API](/home/web-search) allows you to search the web for current information and get real-time results. This tool is useful for finding factual information, news, and data that may not be available in your model's training data. Key features: * Search for current information and news * Filter results by domain, time range, and geographic location * Control search depth and result comprehensiveness * Support for both general and news-specific searches #### Web search tool for chat completions The [web search prebuilt tool](/home/web-search-tool) for chat completions enables your AI assistant to search the web during conversations with Palmyra models. This allows your AI to provide up-to-date information and answer questions about current events. #### Web connector URLs for Knowledge Graphs [Web connector URLs](/home/web-connector-url) allow you to automatically extract and index content from websites into your Knowledge Graphs. This enables you to: * Process single pages or entire sub-pages * Monitor the status of URL processing * Exclude specific URLs from processing * Query web content through your Knowledge Graph ### Image support in chat completions Added support for [mixed content in chat completions](/home/chat-with-images) with Palmyra X5, allowing you to include images directly in your chat messages. This feature enables rich visual conversations without needing to use the separate Vision tool. ### References For more information, see the following API reference docs and guides: * Web search tool: [API reference](/api-reference/tool-api/web-search) and [guide](/home/web-search) * Web search tool for chat completions: [API reference](/api-reference/completion-api/chat-completion#body-tools) and [guide](/home/web-search-tool) * Web connector URLs for Knowledge Graphs: [API reference](/api-reference/kg-api/update-graph#body-urls) and [guide](/home/web-connector-url) * Chat with images: [API reference](/api-reference/completion-api/chat-completion#body-messages-content) and [guide](/home/chat-with-images) **2025-08-12** Vision chat support for Palmyra X5 ### Vision chat support for Palmyra X5 Added support for [mixed content in chat completions](/home/chat-with-images) with Palmyra X5, allowing you to include images directly in your chat messages. This feature enables rich visual conversations without needing to use the separate Vision tool. Key capabilities: * Send messages containing both text and images * Support for multiple images in a single message * Use of data URLs for local images * Natural conversation flow with visual context Below is an example of a chat completion request that includes a message with both text and an image. ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/chat' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "What do you see in this image?" }, { "type": "image_url", "image_url": { "url": "https://example.com/image.jpg" } } ] } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.chat.chat( model="palmyra-x5", messages=[ { "role": "user", "content": [ { "type": "text", "text": "What do you see in this image?" }, { "type": "image_url", "image_url": { "url": "https://example.com/image.jpg" } } ] } ] ) print(response.choices[0].message.content) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.chat.chat({ model: "palmyra-x5", messages: [ { role: "user", content: [ { type: "text", text: "What do you see in this image?" }, { type: "image_url", image_url: { url: "https://example.com/image.jpg" } } ] } ] }); console.log(response.choices[0].message.content); ``` **2025-01-27** Web search and web connector URLs released ## Web search and web connector URLs released Three new features are now available to enhance your AI applications with web content and search capabilities: * [Web search tool API](#web-search-tool-api) * [Web search tool for chat completions](#web-search-tool-for-chat-completions) * [Web connector URLs for Knowledge Graphs](#web-connector-urls-for-knowledge-graphs) ### Web search tool API The new [web search tool API](/home/web-search) allows you to search the web for current information and get real-time results. This tool is useful for finding factual information, news, and data that may not be available in your model's training data. Key features: * Search for current information and news * Filter results by domain, time range, and geographic location * Control search depth and result comprehensiveness * Support for both general and news-specific searches ### Web search tool for chat completions The [web search prebuilt tool](/home/web-search-tool) for chat completions enables your AI assistant to search the web during conversations with Palmyra models. This allows your AI to provide up-to-date information and answer questions about current events. ### Web connector URLs for Knowledge Graphs [Web connector URLs](/home/web-connector-url) allow you to automatically extract and index content from websites into your Knowledge Graphs. This enables you to: * Process single pages or entire sub-pages * Monitor the status of URL processing * Exclude specific URLs from processing * Query web content through your Knowledge Graph For more information, see the following guides: * [Web search tool API documentation](/api-reference/tool-api/web-search) * [Web search tool for chat completions](/home/web-search-tool) * [Web connector URLs for Knowledge Graphs](/home/web-connector-url) **2025-07-16** Writer Strands Agents integration released ## Writer Strands Agents integration released You can now use Writer's models with [AWS' Strands Agents](https://github.com/strands-agents/sdk-python), an open-source SDK for building and deploying AI agents. See the new [Strands integration guide](/home/integrations/strands) for setup instructions, configuration, and examples. **2025-07-16** 2.2.1 of the Python and Node SDKs ## Released version 2.2.1 of the Python and Node SDKs Version 2.2.1 of the [Python](https://github.com/writer/writer-python) and [Node](https://github.com/writer/writer-node) SDKs adds support for filtering files by file type. To filter files by type, use the `file_types` parameter to pass a comma-separated string of file extensions (without the dot) to the `files.list` method. The following code shows how to filter for only PDF and DOCX files: ```python Python theme={null} files = client.files.list(file_types="pdf,docx") ``` ```javascript JavaScript theme={null} const files = await client.files.list({ file_types: 'pdf,docx' }); ``` For more information on the `files.list` method and its parameters, refer to the [List Files API documentation](/api-reference/file-api/get-all-files). **2025-07-10** instructor-writer supports JSON output ## Writer Instructor integration now supports JSON output Added support for the `WRITER_JSON` mode in the [Instructor integration](/home/integrations/instructor#json-mode). This mode allows you to receive structured output directly as JSON, following your specified schema, making it easier to work with validated, structured data from LLM responses. **2025-05-12** langchain-writer v0.3.1 ## langchain-writer v0.3.1 The [langchain-writer](https://github.com/writer/langchain-writer) package now includes the [translation tool](/home/translation-tool) for chat completions. This tool allows you to translate text between languages during chats with Palmyra LLMs. For more details, see the [langchain-writer changelog](https://github.com/writer/langchain-writer/releases/tag/v0.3.1). **2025-05-02** Filter files by type ## Filter files by type The [`/v1/files` endpoint](/api-reference/file-api/get-all-files#parameter-file-types) now supports filtering files by extension type. To filter files by type, pass a comma-separated string of file extensions to the `file_types` query parameter. For example, `file_types=txt,pdf,docx`. ```bash cURL theme={null} curl --location --request GET "https://api.writer.com/v1/files?file_types=txt,pdf,docx" \ --header "Authorization: Bearer $WRITER_API_KEY" \ ``` The `file_types` parameter will be available in the next version of the Python and Node SDKs. **2025-04-30** Python and Node SDK v2.2.0 ## Released version 2.2.0 of the Python and Node SDKs Version 2.2.0 of the [Python](https://github.com/writer/writer-python) and [Node](https://github.com/writer/writer-node) SDKs adds support the following features: * [Structured output](/home/structured-output) for the chat completions endpoint * [AI detection endpoint](/home/ai-detect) * [Text translation endpoint](/home/translation) * [The text translation tool](/home/translation-tool) for chat completions The [langchain-writer](https://github.com/writer/langchain-writer) package has been updated to support structured output. See the [langchain-writer changelog](https://github.com/writer/langchain-writer/releases/tag/v0.3.0) for more details. See the API reference documentation for information about the new endpoints and tools: * [Structured output for chat completions](/api-reference/completion-api/chat-completion#body-response-format) * [AI detection](/api-reference/tool-api/ai-detect) * [Text translation](/api-reference/translation-api/translate) * [The text translation tool](/api-reference/completion-api/chat-completion#body-tools) **2025-04-29** Palmyra X5 and X4 on Amazon Bedrock ## Palmyra X5 and X4 now available on Amazon Bedrock Palmyra X5 and X4 are now available on [Amazon Bedrock](https://aws.amazon.com/bedrock/). Amazon Bedrock is a fully managed service from AWS that enables developers to build and scale generative AI applications using foundation models from leading AI companies. This integration allows you to use Palmyra X5 and X4 in Amazon's serverless environment. See the following resources for more information: * [Guide for setting up and using Palmyra X5 and X4 on Amazon Bedrock](/home/integrations/bedrock) * [AWS blog post about using Palmyra X5 and X4 on Amazon Bedrock](https://aws.amazon.com/blogs/aws/writer-palmyra-x5-and-x4-foundation-models-are-now-available-in-amazon-bedrock/) **2025-04-28** Palmyra X5 ## Palmyra X5 model now available The [Palmyra X5 model](/home/models#palmyra-x5) is now available via the API and SDKs. Palmyra X5 is Writer's newest and most advanced model for building and scaling AI agents, featuring a 1 million token context window, adaptive reasoning, and industry-leading speed and cost efficiency. > [!NOTE] > > As part of this release, Palmyra X 004 is now called Palmyra X4. Palmyra X5's 1M token context window further streamlines enterprise workflows and unlocks complex, multi-step use cases that weren't possible before, such as: **Multi-step agentic workflows** * **Support documentation**: Classify requests, assess urgency, assign a human review, stage updates in a CMS, and publish after approval. * **Fund reporting**: Streamline the analysis and preparation of detailed reports on the performance and status of investment funds, using reporting and research data pulled in from third-party systems * **Content lifecycle management**: Flag content that could be outdated, generate suggested revisions, and share them for human review. **Large data requirements**: * **Customer feedback analysis**: Analyze large volumes of customer feedback to identify common themes, summarize sentiments, and generate actionable insights. * **Research and development**: Process and summarize multiple technical reports, research papers, and experimental data, accelerating innovation and product development. * **Financial reporting**: Process and summarize annual reports, SEC filings, and market analysis reports together at once to extract financial data, identify trends, and generate executive summaries. * **Legal document analysis**: Analyze lengthy legal documents, including contracts, patents, and compliance reports, to identify key clauses, flag potential risks, and ensure regulatory compliance. * **Medical records analysis**: Analyze and summarize large files of medical records containing structured and unstructured data, including patient records, clinical trial reports, audit reports, and more. See the [Palmyra X5 model overview](/home/models#palmyra-x5) for more details and [examples of using Palmyra X5 with the text generation and chat completion endpoints](/home/models#using-models-with-the-writer-api). **2025-04-15** langchain-writer supports Python 3.9 ## Writer LangChain integration now supports Python 3.9 The [Writer LangChain integration](/home/integrations/langchain) now supports versions of Python 3.9 and higher, as of [version 0.2.0](https://github.com/writer/langchain-writer/releases/tag/v0.2.0). **2025-04-10** Terminology updates ## Terminology updates As part of Writer's [recent product announcement](https://writer.com/blog/writer-ai-hq), no-code applications are now called [no-code agents](/no-code/introduction). The [Applications API](/api-reference/application-api/applications), which you can use to programmatically interact with no-code agents, still uses the term `application` to minimize breaking changes. The guides for [invoking no-code apps](/home/applications), [async applications](/home/async-applications), and [using no-code apps as tools](/home/applications-tool-calling) have been updated to reflect the new terminology. However, the [Applications API](/api-reference/application-api/applications) reference documentation still reflects previous terminology. **2025-04-04** Python and Node SDK v2.1.0 ## Released version 2.1.0 of the Python and Node SDKs This release adds support for the [vision endpoint](/api-reference/vision-api/analyze-images) and the [vision tool](/home/vision-tool) for chat completions. It also adds streaming helper methods to process streaming responses from the chat completions endpoint. * [Streaming helpers in Python](https://github.com/writer/writer-python?tab=readme-ov-file#streaming-helpers) * [Streaming helpers in Node](https://github.com/writer/writer-node?tab=readme-ov-file#streaming-helpers) **2025-03-26** New cookbooks ## New cookbooks for Palmyra models We've added three new [cookbooks](/home/cookbooks#palmyra-models) to help you explore domain-specific Palmyra models for creative, financial, and medical use cases. * [Palmyra Creative](https://github.com/writer/cookbooks/blob/main/models/palmyra_creative.ipynb) * [Palmyra Fin](https://github.com/writer/cookbooks/blob/main/models/palmyra_fin.ipynb) * [Palmyra Med](https://github.com/writer/cookbooks/blob/main/models/palmyra_med.ipynb) **2025-03-20** New vision endpoint ## Palmyra Vision now available via the API The Palmyra Vision model is now available via the API with the [`/vision` endpoint](/api-reference/vision-api/analyze-images). ```bash cURL theme={null} curl -X POST \ 'https://api.writer.com/v1/vision' \ -H 'Content-Type: application/json' \ -H "Authorization: Bearer $WRITER_API_KEY" \ --data-raw '{ "model": "palmyra-vision", "prompt": "What's the difference between the image {{image_1}} and the image {{image_2}}?", "variables": [ {"name": "image_1", "file_id": "f1234"}, {"name": "image_2", "file_id": "f5678"} ] }' ``` The `/vision` endpoint analyzes images based on a prompt. You can use the endpoint for a variety of use cases, including: * Extracting handwritten text * Interpreting charts and graphs * Generating product descriptions Find additional use cases in the [Palmyra Vision overview](https://writer.com/llms/palmyra-vision/). See the [vision API guide](/home/analyze-images) for a detailed walkthrough of uploading images and passing them to the `/vision` endpoint, or check out the full [vision API reference](/api-reference/vision-api/analyze-images). **2025-03-10** langchain-writer v0.1.0 ## Released langchain-writer v0.1.0 * Updated tool binding to align with standard LangChain tool calling conventions. * Added a new `NoCodeAppTool` tool for using no-code applications as tools. * Added a new `LLMTool` tool for delegating to a specific Palmyra model. See the [guide to using the LangChain integration](/home/integrations/langchain) and the [package documentation](https://github.com/writer/langchain-writer/tree/main/docs) for more details. **2025-03-05** New cookbooks ## New cookbooks for tool calling and no-code applications We've added three new [cookbooks](/home/cookbooks) to help you get started with no-code applications and tool calling. * [Generating content from no-code applications with the SDK](https://github.com/writer/cookbooks/blob/main/applications/application_basic_usage.ipynb) * [Delegating a medical question to the `palmyra-med` model](https://github.com/writer/cookbooks/blob/main/tool_calling/tool_calling_llm.ipynb) * [Using the Knowledge Graph chat tool](https://github.com/writer/cookbooks/blob/main/tool_calling/tool_calling_kg.ipynb) **2025-03-03** palmyra-fin ## Palmyra Fin model updates Palmyra Fin, our financial model, now has a 128k context window, up from 32k. To use the Palmyra Fin model in the API and SDKs, use the `palmyra-fin` model ID. The `palmyra-fin-32k` model ID is now deprecated. **2025-02-28** langchain-writer v0.0.3 ## Released Writer LangChain integration We're excited to announce the first release of `langchain-writer`, the official Writer LangChain integration. This release includes: * The `ChatWriter` model for text generation * Tool calling capabilities, including the `GraphTool` for retrieving information from a Knowledge Graph * Additional tools like the `PDFParser` for parsing PDFs and the `WriterTextSplitter` for intelligent text splitting Check out the [tutorial](/home/integrations/langchain) to get started and the full [integration documentation](https://github.com/writer/langchain-writer/blob/main/docs/) for more details. **2025-02-27** Python and Node SDK v2.0.0 ## Released version 2.0.0 of the Python and Node SDKs The 2.0.0 release includes new functionality for the Writer SDKs for Python and Node: * **Model delegation tool**: A prebuilt, remotely executed tool that lets you delegate domain-specific requests to the appropriate Palmyra model. For example, if your application has finance questions, you can use the tool to allow Palmyra X4 to delegate these questions to Palmyra Financial. Read more in our [model delegation guide](/home/model-delegation). * **Retrieve application details**: Retrieve details for all of your no-code applications. Programmatically retrieve application inputs rather than relying on the AI Studio UI. This pairs well with our guide on [using no-code applications as tools](/home/applications). * **Async jobs**: Trigger no-code application content generation asynchronously and retrieve or retry the job at a later time. This is great for long-running no-code applications, such as research assistant applications. To learn more, check out the [guide on async jobs](/home/async-applications). * **Associate Knowledge Graphs with chat applications**: Retrieve or update which Knowledge Graphs are associated with no-code chat applications. > [!WARNING] > > The 2.0.0 release includes some breaking changes to the underlying models used in chat completion. This won't affect you if you are only using chat completion via the `Writer.chat.chat` method, but it will if you are importing specific types directly. See below for more details about changes in each SDK. See the SDK repositories for the full changelogs: * [Python](https://github.com/writer/writer-python/releases) * [Node](https://github.com/writer/writer-node/releases) ### Python SDK See below for the mapping of old types to new types: | Old | New | | - | - | | `chat_chat_params.Tool` | `types.shared_params.tool_param.ToolParam` | | `types.Chat` | `types.chat_completion.ChatCompletion` | | `types.chat.ChoiceMessageGraphDataSource` | `types.shared.source.Source` | | `types.chat.ChoiceMessageGraphDataSubquerySource` | `types.shared.source.Source` | | `types.chat_completion_chunk.ChoiceDeltaGraphData` | `types.shared.graph_data.GraphData` | | `types.chat_completion_chunk.Usage` | `types.chat_completion_usage` | | `types.chat_completion_chunk.ChoiceMessageToolCall` | `types.shared.tool_call_streaming.ToolCallStreaming` | | `types.question.Source` | `types.shared.source.Source` | | `types.question.SubquerySource` | `types.shared.source.Source` | Additionally: * The `types.chat_completion_chunk.Message` type has been moved to its own model: `types.chat_completion_message`. * `types.chat.ChoiceLogprobsContent`, `ChoiceLogprobsRefusal`, `ChoiceLogprobsContentTopLogprob`, and `ChoiceLogprobsRefusalTopLogprob` have all been deduplicated and replaced by a shared model `types.shared.logprobs_token.LogprobsToken`. ### Node SDK See below for the mapping of old types to new types: | Old | New | | - | - | | `ChatResource` | `Chat` | | `Chat` | `ChatCompletion` | | `Chat.Choice` | `ChatCompletionChoice` | | `Chat.Choice.Message` | `ChatCompletionMessage` | | `Chat.Choice.Logprobs` | `Shared.Logprobs` | | `Chat.Choice.Logprobs.Content` | `Shared.LogprobsToken` | | `Chat.Choice.Logprobs.Refusal` | `Shared.LogprobsToken` | | `Chat.Usage` | `ChatCompletionUsage` | | `ChatCompletionChunk.Choice.Message` | `ChatCompletionMessage` | | `ChatCompletionChunk.Choice.Delta` | `ChatCompletionChunk.Choice.Delta` | | `ChatCompletionChunk.Choice.Delta.GraphData` | `Shared.GraphData` | | `ChatCompletionChunk.Choice.Delta.ToolCall` | `Shared.ToolCallStreaming` | | `ChatCompletionChunk.Choice.Logprobs` | `Shared.Logprobs` | | `ChatCompletionChunk.Usage` | `ChatCompletionUsage` | | `ChatChatParams.Message.GraphData` | `Shared.GraphData` | | `ChatChatParams.Message.ToolCall` | `Shared.ToolCall` | | `ChatChatParams.StringToolChoice` | `Shared.ToolChoiceString` | | `ChatChatParams.JsonObjectToolChoice` | `Shared.ToolChoiceJsonObject` | | `ChatChatParams.FunctionTool` | `Shared.ToolParam.FunctionTool` | | `ChatChatParams.GraphTool` | `Shared.ToolParam.GraphTool` | | `StreamingData` | `CompletionChunk` | | `Completion.Choice.LogProbs` | `Shared.Logprobs` | The Node SDK includes developer experience improvements from [Stainless](https://www.stainlessapi.com/), including using the native `fetch` API, resulting in zero SDK dependencies. **2024-12-20** Python SDK v1.6.1 ## Released version 1.6.1 of the Python SDK * Fixed a typing bug where the `content` field in the `File` did not accept the correct `FileTypes` values. **2024-12-16** Python SDK v1.6.0; Node SDK v1.5.0 ## Released Python SDK version 1.6.0 and Node SDK version 1.5.0 * Added streaming support to the [applications content generation endpoint](/api-reference/application-api/applications) and updated the [No-code applications guide](/home/applications) to reflect this. **2024-11-29** Python SDK v.1.5.0 ## Released Python SDK version 1.5.0 * Added new functionality via manual API updates * Fixed compatibility with the latest `httpx` 0.28.0 release * Improved handling of deprecated arguments (`transport`, `proxies`) to maintain backward compatibility * Fixed compatibility issues with Pydantic `model_dump` method when warnings are passed * Removed the now unused `cached-property` dependency, as we now rely on the standard library implementation for Python 3.8+ * Enhanced logging documentation in README, adding information about the 'info' log level * Updated the recommended log level from 'debug' to 'info' for standard usage * Fixed code formatting for better readability and consistency * Excluded test files from `mypy` checks to avoid false positives * Updated internal compatibility layer for better type checking * Improved error handling for deprecated client configuration options **2024-11-14** Python and Node SDK v1.4.0 ## Released Python and Node SDK versions 1.4.0 * Updated the default timeout on the Writer client to three minutes. # Generate chat completions Source: https://dev.writer.com/home/chat-completion Create multi-turn conversations with AI using the chat completion API. Preserve conversation context and use tool calling for advanced features. > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. The [chat completion endpoint](/api-reference/completion-api/chat-completion) allows you to create a conversation between a user and an AI-assisted chat model. This guide introduces the chat completion endpoint and shows how to create a multi-turn conversation with an LLM, where the conversation history is preserved so the model understands the context of the conversation. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Chat completion versus text generation The chat completion endpoint is similar to the [text generation endpoint](/home/text-generation), but it is designed to handle conversations between a user and an LLM. The chat completion endpoint can generate single messages, or create more complex conversations between a user and an LLM. The text generation endpoint is designed to generate a single text response based on a given prompt. Additionally, the chat completion endpoint offers [tool calling](/home/tool-calling), which you can use to access other LLMs, Knowledge Graphs, and custom functions. ## Endpoint overview **URL:** `POST https://api.writer.com/v1/chat` > [!WARNING] > > Using the `/chat` endpoint results in charges for **model usage**. See the [pricing page](/home/pricing) for more information. ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/chat' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "messages": [ { "role": "user", "content": "You are an expert at writing concise product descriptions for an E-Commerce Retailer" }, { "role": "assistant", "content": "Okay, great I can help write these descriptions. Do you have a specific product in mind?" }, { "role": "user", "content": "Please write a one sentence product description for a cozy, stylish sweater suitable for both casual and formal occasions" } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() chat_response = client.chat.chat( messages=[ { "role": "user", "content": "You are an expert at writing concise product descriptions for an E-Commerce Retailer" }, { "role": "assistant", "content": "Okay, great I can help write these descriptions. Do you have a specific product in mind?" }, { "role": "user", "content": "Please write a one sentence product description for a cozy, stylish sweater suitable for both casual and formal occasions" } ], model="palmyra-x5" ) print(chat_response.choices[0].message.content) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const chatResponse = await client.chat.chat({ messages: [ { role: "user", content: "You are an expert at writing concise product descriptions for an E-Commerce Retailer" }, { role: "assistant", content: "Okay, great I can help write these descriptions. Do you have a specific product in mind?" }, { role: "user", content: "Please write a one sentence product description for a cozy, stylish sweater suitable for both casual and formal occasions" } ], model: 'palmyra-x5' }); console.log(chatResponse.choices[0].message.content); ``` ### Request body Below are the required and commonly used optional parameters for the text generation endpoint. | Parameter | Type | Description | | - | - | - | | `model` | string | **Required**. The [ID of the model](/home/models) to use for the chat completion. This can be a Palmyra model like `palmyra-x5` or `palmyra-x4`, or an [external model](/home/external-models) configured for your organization. | | `messages` | array | **Required**. The conversation history. | | `messages[].role` | string | **Required**. The role of the message sender. Can be `user`, `assistant`, `system`, or `tool`. `system` messages are system prompts, used to provide instructions to the model. `tool` messages are the result of a [tool call](/home/tool-calling#append-the-result-back-to-the-model), and contain the output of the tool call. | | `messages[].content` | string | **Required**. The content of the message. | | `temperature` | float | Temperature influences the randomness in generated text. Defaults to `1`. Increase the value for more creative responses, and decrease the value for more predictable responses. | | `stream` | Boolean | A Boolean value that indicates whether to stream the response. Defaults to `false`. | See the [chat completion endpoint reference](/api-reference/completion-api/chat-completion) for more information on the request body and the additional parameters you can use to control the conversation. ### Response parameters #### Non-streaming response If you set the `stream` parameter to `false`, the response is delivered as a single JSON object. It contains several parameters describing the response, including the `choices` array, which contains the generated text. | Parameter | Type | Description | | - | - | - | | `model` | string | The ID of the model used to generate the response. | | `choices` | array | An array containing one object with the generated text and additional information. | | `choices[0].message.content` | string | The generated text. | See the full list of response parameters in the [chat completion endpoint reference](/api-reference/completion-api/chat-completion). ```json non-streaming response [expandable] theme={null} { "id": "f7aed821-58cf-4210-9d73-538b2cb8ae44", "object": "chat.completion", "choices": [ { "index": 0, "finish_reason": "stop", "message": { "content": "Elevate your wardrobe with this versatile, cozy sweater that seamlessly transitions from casual days to formal evenings.", "role": "assistant", "tool_calls": null, "graph_data": { "sources": null, "status": null, "subqueries": null }, "llm_data": null, "image_data": null, "refusal": null }, "logprobs": null } ], "created": 1741891192, "model": "palmyra-x5", "usage": { "prompt_tokens": 96, "total_tokens": 118, "completion_tokens": 22, "prompt_token_details": null, "completion_tokens_details": null }, "system_fingerprint": "v1", "service_tier": null } ``` #### Streaming response If you set the `stream` parameter to `true`, the response is delivered as [server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events). The event contains several parameters. The content of the chunk is in the `choices[0].delta.content` parameter. | Parameter | Type | Description | | - | - | - | | `choices[0].delta.content` | string | The content of the chunk. | ```python streaming response [expandable] theme={null} data: {'id': '3bb941e2-4dab-4ceb-b4e3-45a429f40c72', 'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'finish_reason': None, 'message': {'content': 'This', 'role': 'assistant', 'tool_calls': None, 'graph_data': {'sources': None, 'status': None, 'subqueries': None}, 'llm_data': None, 'image_data': None, 'refusal': None}, 'delta': {'content': 'This', 'role': 'assistant', 'tool_calls': None, 'graph_data': {'sources': None, 'status': None, 'subqueries': None}, 'llm_data': None, 'image_data': None, 'refusal': None}, 'logprobs': None}], 'created': 1741891257, 'model': 'palmyra-x5', 'usage': None, 'system_fingerprint': 'v1', 'service_tier': None} ``` ## Sample application The following sample application uses the Python and JavaScript SDKs to create a command-line chatbot. The application asks the user for input, passes the conversation history to the LLM, and streams the response from the LLM. It loops until the user enters the message `exit`. ### Set a system prompt To guide the behavior of the assistant, you can set a system prompt by adding a message with the role `system` to the `messages` array. For example, you can set a system prompt to have the assistant respond in a certain tone or style, or to provide additional context for the conversation. Here's a system prompt that directs the assistant to be casual and use emojis in its responses: ```python Python theme={null} system_prompt = "You are a helpful assistant that responds in a casual, friendly tone and uses emojis in your responses." messages = [ {"role": "system", "content": system_prompt}, ] ``` ```javascript JavaScript theme={null} const system_prompt = "You are a helpful assistant that responds in a casual, friendly tone and uses emojis in your responses."; let messages = [ {role: "system", content: system_prompt}, ]; ``` Learn about [prompting best practices](/home/prompting) to help you create effective system prompts. ### Stream chat responses The sample application streams the responses from the LLM. Streaming improves the user experience, showing the input as it is generated and reducing the latency of the final response. Below are the code snippets from the sample application to stream the chat responses. They use the [`stream` helper method of the `chat` endpoint](/home/streaming#streaming-helpers-for-chat-completions) to print the chat responses to the console in real time. The `stream` method also collects the final response and returns it so it can be added to the conversation history. ```python Python theme={null} # Stream the chat response to the user using the `stream` helper method with client.chat.stream(messages=messages, model="palmyra-x5") as stream: for event in stream: # Check if the event is a content delta, which contains this chunk of the chat response if event.type == "content.delta": print(event.delta, end="", flush=True) # Collect the full response from the stream completion = stream.get_final_completion().choices[0].message.content ``` ```javascript JavaScript theme={null} // Stream the chat response to the user using the `stream` helper method const stream = client.chat.stream({ model: 'palmyra-x5', messages: messages, }) // Print this chunk of the chat response to the console .on('content', (diff) => process.stdout.write(diff)); // Collect the full response from the stream let full_message = await stream.finalChatCompletion(); full_message = full_message.choices[0].message.content; ``` ### Full application The following is the complete sample application that uses the functions defined above to stream the chat responses. The application sets a system prompt, asks the user for an initial message, and then enters a loop to handle the conversation between the user and the LLM. It adds the user's message to the conversation history and streams the response from the LLM to the user. The loop continues until the user enters the message `exit`. ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() end = False system_prompt = "You are a helpful assistant that responds in a casual, friendly tone and uses emojis in your responses." # Ask the user for an initial message input_message = "\nEnter a message for the assistant. Type 'exit' to end the conversation. > " initial_message = input(input_message) # Add the user's message to the conversation history messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": initial_message}] # Main loop to handle the conversation. while not end: # Stream the chat response to the user using the `stream` helper method with client.chat.stream(messages=messages, model="palmyra-x5") as stream: for event in stream: # Check if the event is a content delta, which contains this chunk of the chat response if event.type == "content.delta": print(event.delta, end="", flush=True) # Collect the full response from the stream and add it to the conversation history full_message = stream.get_final_completion().choices[0].message.content messages.append({"role": "assistant", "content": full_message}) new_message = input(input_message) messages.append({"role": "user", "content": new_message}) if new_message == "exit": end = True ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); // helpers for reading user input from the command line // ---------------------------------------------------------------------------- const readline = await import('readline'); // Create an interface for input and output const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); // Prompt the user for input. const prompt = (question) => { return new Promise((resolve) => { rl.question(question, (answer) => { resolve(answer); }); }); }; // ---------------------------------------------------------------------------- let end = false; let system_prompt = "You are a helpful assistant that responds in a casual, friendly tone and uses emojis in your responses."; let initial_message = await prompt("Enter a message for the assistant. Type 'exit' to end the conversation. > "); let messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": initial_message}]; // Main loop to handle the conversation. while (!end) { // Stream the chat response to the user using the `stream` helper method const stream = client.chat.stream({ model: 'palmyra-x5', messages: messages, }) // Print this chunk of the chat response to the console .on('content', (diff) => process.stdout.write(diff)); // Collect the full response from the stream and add it to the conversation history let full_message = await stream.finalChatCompletion(); full_message = full_message.choices[0].message.content; messages.push({role: "assistant", content: full_message}); console.log("\n"); let new_message = await prompt("Enter a message for the assistant. Type 'exit' to end the conversation. > "); messages.push({role: "user", content: new_message}); if (new_message === "exit") { end = true; } } ``` ## Best practices Follow these best practices to ensure that your chatbot behaves as expected: * **Use system messages**: Including a system message can guide the behavior of the assistant, setting expectations for its tone and responsiveness. * **Maintain context**: Ensure that all relevant parts of the conversation are included in the `messages` array to maintain context, as the model doesn't retain memory of past interactions. * **Handle errors gracefully**: Implement [error handling](/api-reference/error-handling) for various HTTP status codes and API-specific errors such as rate limits or malformed requests. * **Manage conversational flow**: Regularly review the conversation's context and adjust it to keep interactions relevant and concise, especially under the model's token limit. ## Next steps Now that you've created a chatbot, learn how to [add tool calling](/home/tool-calling) to your application to enhance the functionality with other LLMs, Knowledge Graphs, and custom functions. * [Create custom functions as tools](/home/tool-calling) * [Access information in Knowledge Graphs](/home/kg-chat) * [Delegate tasks to another model](/home/model-delegation) # Add images to chat completions Source: https://dev.writer.com/home/chat-with-images You can include images directly in your chat conversations with Palmyra X5 using mixed content support. This allows you to send both text and images in the same message, enabling rich visual conversations with Palmyra X5. > [!WARNING] > > Image analysis in chat completions is only supported with the **Palmyra X5** model. Other models don't support the `image_url` content type. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Overview Mixed content support allows you to send messages that contain both text and images in a chat with Palmyra X5. You can include images directly in your chat messages, making conversations more natural and contextual. ## How it works When sending a message to the chat completion endpoint, you can use the `content` field in two ways: 1. **Text-only message**: ```json theme={null} "messages": [ { "role": "user", "content": "Hello, how are you?" } ] ``` 2. **Mixed content message**: ```json theme={null} "messages": [ { "role": "user", "content": [{"type": "text", "text": "What do you see in this image?"}, {"type": "image_url", "image_url": {"url": ""}}] } ] ``` ## Endpoint **URL:** `POST https://api.writer.com/v1/chat` ### Content fragment types #### Text fragment ```json theme={null} { "type": "text", "text": "Your text content here" } ``` #### Image fragment ```json theme={null} { "type": "image_url", "image_url": { "url": "" } } ``` ## Examples ### Single image analysis This example shows how to send a message with a single image. The `content` field is an array of content fragments, where each fragment can be either text or image. The text fragment includes the message for the model to analyze. The image fragment includes the image URL. ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/chat' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "What do you see in this image?" }, { "type": "image_url", "image_url": { "url": "" } } ] } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.chat.chat( model="palmyra-x5", messages=[ { "role": "user", "content": [ { "type": "text", "text": "What do you see in this image?" }, { "type": "image_url", "image_url": { "url": "" } } ] } ] ) print(response.choices[0].message.content) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.chat.chat({ model: "palmyra-x5", messages: [ { role: "user", content: [ { type: "text", text: "What do you see in this image?" }, { type: "image_url", image_url: { url: "" } } ] } ] }); console.log(response.choices[0].message.content); ``` ### Using local images with data URLs You can also use [data URLs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) to send local images without uploading them to a remote server. This is useful for testing or when working with local files: ```bash cURL theme={null} # Convert local image to base64 data URL base64_image=$(base64 -i "") data_url="data:image/jpeg;base64,$base64_image" curl --location 'https://api.writer.com/v1/chat' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data "{ \"model\": \"palmyra-x5\", \"messages\": [ { \"role\": \"user\", \"content\": [ { \"type\": \"text\", \"text\": \"Analyze this local image:\" }, { \"type\": \"image_url\", \"image_url\": { \"url\": \"$data_url\" } } ] } ] }" ``` ```python Python theme={null} import base64 from pathlib import Path from writerai import Writer # Initialize the client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() # Read local image and convert to base64 data URL def image_to_data_url(image_path): with open(image_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode('utf-8') file_extension = Path(image_path).suffix.lstrip('.') mime_type = f"image/{file_extension}" if file_extension in ['jpg', 'jpeg', 'png', 'gif'] else "image/jpeg" return f"data:{mime_type};base64,{encoded_string}" # Convert local image to data URL data_url = image_to_data_url("") response = client.chat.chat( model="palmyra-x5", messages=[ { "role": "user", "content": [ { "type": "text", "text": "Analyze this local image:" }, { "type": "image_url", "image_url": { "url": data_url } } ] } ] ) print(response.choices[0].message.content) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; import fs from 'fs'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); // Convert local image to base64 data URL function imageToDataUrl(imagePath) { const imageBuffer = fs.readFileSync(imagePath); const base64String = imageBuffer.toString('base64'); const fileExtension = imagePath.split('.').pop(); const mimeType = ['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension) ? `image/${fileExtension}` : 'image/jpeg'; return `data:${mimeType};base64,${base64String}`; } // Convert local image to data URL const dataUrl = imageToDataUrl(""); const response = await client.chat.chat({ model: "palmyra-x5", messages: [ { role: "user", content: [ { type: "text", text: "Analyze this local image:" }, { type: "image_url", image_url: { url: dataUrl } } ] } ] }); console.log(response.choices[0].message.content); ``` ### Multiple images with text You can include multiple images in a single message: ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/chat' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Compare these two images and tell me the differences:" }, { "type": "image_url", "image_url": { "url": "" } }, { "type": "image_url", "image_url": { "url": "" } } ] } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.chat.chat( model="palmyra-x5", messages=[ { "role": "user", "content": [ { "type": "text", "text": "Compare these two images and tell me the differences:" }, { "type": "image_url", "image_url": { "url": "" } }, { "type": "image_url", "image_url": { "url": "" } } ] } ] ) print(response.choices[0].message.content) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.chat.chat({ model: "palmyra-x5", messages: [ { role: "user", content: [ { type: "text", text: "Compare these two images and tell me the differences:" }, { type: "image_url", image_url: { url: "" } }, { type: "image_url", image_url: { url: "" } } ] } ] }); console.log(response.choices[0].message.content); ``` ## Next steps * Learn about [chat completions](/home/chat-completion) for text-based conversations * Check out [Palmyra X5](/home/models#palmyra-x5) model capabilities # Cookbooks Source: https://dev.writer.com/home/cookbooks [Writer Cookbooks](https://github.com/writer/cookbooks) are step-by-step guides to help you implement tasks and solve common problems using Writer. Each recipe includes code snippets, explanations, and best practices to enhance your understanding of the Writer platform. ## Featured > [card] [Multimodal chat completion](https://github.com/writer/cookbooks/blob/main/completion/multimodal_chat_x5.ipynb) > > Send both text and images in the same message to enable rich, visual conversations with Palmyra X5. > [card] [Third-party models](https://github.com/writer/cookbooks/blob/main/models/Amazon_Bedrock.ipynb) > > Call third-party Amazon Bedrock models via the Writer SDK, including chat and tool calling. > [card] [Knowledge Graph](https://github.com/writer/cookbooks/blob/main/knowledge_graph/knowledge_graph.ipynb) > > Use our RAG implementation to create, manage, and use structured data to enhance AI capabilities. ## All cookbooks ### Applications > [card] [Working with no-code agents](https://github.com/writer/cookbooks/blob/main/applications/application_basic_usage.ipynb) > > Retrieve no-code agent metadata and generate output from them using the Writer SDK. > [card] [Knowledge Graph management](https://github.com/writer/cookbooks/blob/main/applications/application_graph_management.ipynb) > > Attach a Knowledge Graph to a no-code agent programmatically. > [card] [Run no-code agents asynchronously](https://github.com/writer/cookbooks/blob/main/applications/application_jobs_utilization.ipynb) > > Run no-code agents asynchronously and manage asynchronous jobs. ### Completions > [card] [Text completion](https://github.com/writer/cookbooks/blob/main/completion/text_completion.ipynb) > > Use the Writer Python SDK for text completion tasks. > [card] [Chat completion](https://github.com/writer/cookbooks/blob/main/completion/chat_completion.ipynb) > > Build single-turn and multi-turn chat completions to support conversational AI applications. > [card] [Multimodal chat completion](https://github.com/writer/cookbooks/blob/main/completion/multimodal_chat_x5.ipynb) > > Send both text and images in the same message to enable rich, visual conversations with Palmyra X5. > [card] [Structured completions](https://github.com/writer/cookbooks/blob/main/completion/structured_output_cookbook.ipynb) > > Get predictable, machine-readable responses from Palmyra LLMs using JSON Schema or Pydantic objects. ### Knowledge Graph > [card] [Knowledge Graph](https://github.com/writer/cookbooks/blob/main/knowledge_graph/knowledge_graph.ipynb) > > Use our RAG implementation to create, manage, and use structured data to enhance AI capabilities. > [card] [Knowledge Graph tool calling](https://github.com/writer/cookbooks/blob/main/tool_calling/tool_calling_kg.ipynb) > > Access a Knowledge Graph in a chat. ### Integrations > [card] [Instructor basics](https://github.com/writer/cookbooks/blob/main/integrations/instructor/Instructor.ipynb) > > Extract structured data from text, CSV, and PDF files using Instructor and Writer. > [card] [Advanced Instructor](https://github.com/writer/cookbooks/blob/main/integrations/instructor/Advanced.ipynb) > > Work with nested Pydantic models, retry and repair patterns, and streaming using Instructor and Writer. > [card] [LangChain basics](https://github.com/writer/cookbooks/blob/main/integrations/langchain/LangChain.ipynb) > > Use Writer with LangChain to build chat workflows and LangGraph agents with tool calling. > [card] [Advanced LangChain](https://github.com/writer/cookbooks/blob/main/integrations/langchain/Advanced.ipynb) > > Build Writer-powered LangChain agents with custom middleware, context engineering, and MCP. > [card] [OpenLLMetry](https://github.com/writer/cookbooks/blob/main/integrations/OpenLLMetry.ipynb) > > Monitor, trace, and debug Writer API calls using OpenLLMetry and Traceloop. > [card] [Strands Agents](https://github.com/writer/cookbooks/blob/main/integrations/Strands.ipynb) > > Build agents with the Strands Agents SDK and Writer models, either through direct integration or Amazon Bedrock. ### Models > [card] [List all models](https://github.com/writer/cookbooks/blob/main/models/model_retrieval.ipynb) > > List all of the Palmyra models available in the Writer API. > [card] [Third-party models](https://github.com/writer/cookbooks/blob/main/models/Amazon_Bedrock.ipynb) > > Call third-party Amazon Bedrock models via the Writer SDK, including chat and tool calling. ### Tool calling > [card] [Tool calling fundamentals](https://github.com/writer/cookbooks/blob/main/tool_calling/tool_calling_api.ipynb) > > Learn how to use tool calling to enhance the functionality of your LLM. > [card] [LLM tool calling](https://github.com/writer/cookbooks/blob/main/tool_calling/tool_calling_llm.ipynb) > > Use model delegation to refer a task to another model during a chat. > [card] [Knowledge Graph tool calling](https://github.com/writer/cookbooks/blob/main/tool_calling/tool_calling_kg.ipynb) > > Access a Knowledge Graph in a chat. > [card] [Streaming tool calls](https://github.com/writer/cookbooks/blob/main/tool_calling/tool_calling_streaming.ipynb) > > Use tool calling with streaming responses. > [card] [Math tool calling example](https://github.com/writer/cookbooks/blob/main/tool_calling/tool_calling_math.ipynb) > > Extend the capabilities of your LLM with predefined mathematical functions. ### Tools > [card] [PDF parser](https://github.com/writer/cookbooks/blob/main/tools/pdf_parser.ipynb) > > Parse a PDF file and extract the text as text or markdown. # Custom connectors Source: https://dev.writer.com/home/custom-connectors Create custom connectors from OpenAPI specifications or MCP servers to extend WRITER Agent with your own APIs and tools This guide shows you how to create custom connectors for WRITER Agent. Custom connectors enable integration with internal tools and third-party services not available in the [prebuilt connector library](/home/mcp-gateway#available-connectors). You can create custom connectors in two ways: * **OpenAPI specification**: Upload an OpenAPI definition to expose your API endpoints as tools for WRITER Agent. * **MCP server**: Connect to an external MCP server to make its tools available in WRITER Agent. ## Create a custom connector from an OpenAPI specification ### Prerequisites Before creating an OpenAPI-based custom connector, make sure you have: * An [OpenAPI definition](https://learn.openapis.org/specification/structure.html) that describes your API * **Authentication details** for your API, based on the authentication method you choose: * **API key**: Key name and optional key prefix * **OAuth**: Authorization server URL, access token URL, refresh token URL, and token endpoint authentication method ### Set up the connector Create a custom connector in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select **Create custom connector** 3. Choose **OpenAPI specification** as the connector type 4. Upload your OpenAPI specification file (JSON or YAML format) 5. Enter a **Connector name** and **About this connector** description 6. Configure authentication: * **API key**: Enter the key name and optional key prefix * **OAuth**: Enter your OAuth credentials (authorization server URL, access token URL, refresh token URL, and token endpoint authentication method) 7. Select **Next** to proceed to [tool configuration](#configure-tools) ### Configure tools After uploading your [OpenAPI specification](#create-a-custom-connector-from-an-openapi-specification), the tool configuration screen lets you review and edit the operations defined in your specification. For each tool, you can: * **Edit the tool description**: Double-click or select the pencil icon to modify the description. Clear descriptions help WRITER Agent understand when to use each tool. * **Set the operation type**: Specify whether the tool performs a read, write, update, or delete operation. * **Update the tool name**: Customize the name that appears in WRITER Agent. The **Usage** column shows an estimated token count for each tool, including the tool name, description, and parameters. Use this to identify high-cost tools and reduce token usage. After configuring your tools, select **Save** to create the connector. ### Configure the connector in Control Center After [creating an OpenAPI-based custom connector](#set-up-the-connector), configure it for your organization: 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Find your custom connector and select **Configure** 3. Select who has access by default (all users or specific teams) 4. Select which tools to enable 5. Enter your API key or OAuth credentials, depending on the authentication method configured for the connector After configuration, the connector appears in your connected integrations and is available to authorized users in WRITER Agent. ## Create a custom connector from an MCP server Connect to an external MCP server to make its tools available in WRITER Agent. The MCP server connector supports three authentication methods: * **No auth**: Connect without authentication. * **API key**: Authenticate with an API key. * **OAuth**: Authenticate with OAuth 2.0, at the user level or org level. ### Create the connector 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Select **Create custom connector** 3. Choose **MCP server** as the connector type 4. Enter the MCP server URL 5. Enter a **Connector name** and **About this connector** description 6. Select **Next** to proceed to configuring the connector in Control Center ### Configure the connector in Control Center After entering your MCP server details, the configure step lets you set up access control and authentication: 1. Update the **Profile name** or keep the default 2. Select who has access by default (all teams or specific teams) 3. Select the authentication method for the MCP server: * **No auth**: No credentials required. Select **Next** to complete the connection. * **API key**: Enter the API key details to authenticate with the server. * **OAuth**: Enter your OAuth credentials, including scopes, client ID, and client secret. Select whether authentication is at the user level (each user authenticates individually) or org level (shared connection for the organization). 4. Complete the connection flow After configuration, the connector appears in your connected integrations and is available to authorized users in WRITER Agent. > [!NOTE] > > To route a connector over a private network instead of the public internet, > see [Private endpoints](/home/private-endpoints). ## Edit a custom connector Modify an existing custom connector to update its name, description, or tool configurations. 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Find your custom connector and select **Edit connector** 3. Update the connector name or description as needed 4. Select **Next** to modify tool configurations: * Edit tool descriptions * Update operation types * Modify tool names 5. Select **Save** to apply your changes > [!NOTE] > > When editing a custom connector, you cannot change the connector type (OpenAPI > specification or MCP server), the uploaded specification, or the > authentication type. To use a different specification or connector type, > create a new custom connector. ## Delete a custom connector Deleting a custom connector removes it from your organization's library and disconnects all users. 1. Navigate to **Integrations > Connectors** in [Control Center](https://app.writer.com/controlcenter) 2. Find your custom connector and select **Edit connector** (under the three vertical dots) 3. Select **Delete connector** 4. Confirm the deletion > [!WARNING] > > Deleting a custom connector removes it from your library and disconnects all > users. This action cannot be undone. ## Next steps * [Configure connectors](/home/mcp-gateway): Learn about connector authentication and access control * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools # Choose your development path Source: https://dev.writer.com/home/development_options Compare the developer paths for building on Writer: deploy your own application with Agent Builder v2, or integrate Writer into your stack with the API and SDKs. > [!TIP] > > Need help building? Writer has an in-house solutions team that can build custom > AI agents for you. **[Contact our sales team](https://go.writer.com/contact-sales)** This guide covers the developer paths for building on Writer with code. Choose Agent Builder v2 to deploy your own application to Writer and run it under platform controls, or use the Writer API and SDKs to integrate AI capabilities into an application you host yourself. ## Compare the paths Both paths give you full programming control. The difference is what you build and where it runs. * **Agent Builder v2**: Build your application in your own IDE with any framework, then deploy it to Writer as a dockerized app. Choose this when you want to develop and ship a full application and have Writer run it. Writer handles hosting and environments so you can focus on your code. * **Writer API and SDKs**: Call Writer from an application you build and host yourself. Choose this when you want to embed AI into an existing stack or product surface without moving your application to Writer. ## Build with Agent Builder v2 > [!NOTE] > > Agent Builder v2 is in open beta. Features and limitations described here are > subject to change. Build your agent in your own IDE with the frameworks you already use, then package it as a dockerized Python or JavaScript/TypeScript application and deploy it to Writer. **With Agent Builder v2, you can:** * Build with any framework and deploy from your IDE with no framework lock-in. * Keep separate development and production environments, each with version history. * Add Writer's hosting, supervision, and governance on top of your existing code. ### Getting started resources * [Agent Builder v2 overview](/home/agent-builder/overview) * [Get started with Agent Builder v2](/home/agent-builder/getting-started) ### Example use cases > [accordion] Deployed chat application > > Deploy a full-stack chat application to Writer and run it under platform controls. > [accordion] Framework-based agent > > Deploy an agent built with LangGraph, CrewAI, or another supported framework and run it under Writer governance. ## Build with the Writer API and SDKs The Writer API and SDKs are ideal for engineers who want to embed generative AI into their own stack or access the Writer platform programmatically in any language. **With the Writer API and SDKs, you can:** * Build custom applications with the chat and completion APIs, or integrate with your existing tech stack. * Create knowledge graphs from your own files and documents to power Q\&A and retrieval. * Extend a model's functionality with tool calling to fetch real-time data or run calculations. * Use the REST API in any language, or use the Python or Node SDK. * **Note:** You need an API key to use Writer APIs and SDKs. [Follow the instructions to get your API key](/api-reference/api-keys). ### Getting started resources * [API quickstart](/home/quickstart) * [Get started with Writer SDKs](/home/sdks) * [Python SDK](https://pypi.org/project/writer-sdk/) (`pip install writer-sdk`) * [Node SDK](https://www.npmjs.com/package/writer-sdk) (`npm install writer-sdk`) ### Guides * [Text generation](/home/text-generation) * [Chat completion](/home/chat-completion) * [Knowledge Graph](/home/knowledge-graph) * [Applications API](/home/applications) * [Tool calling](/home/tool-calling) ### Example use cases > [accordion] Integrated chat assistant > > Embed a chat app into an existing tool or service. > [accordion] Integrated text completion > > Add text completion capabilities to a tool or service your company already uses. ## Next steps * [Get started with Agent Builder v2](/home/agent-builder/getting-started) to deploy your first application. * [Follow the API quickstart](/home/quickstart) to make your first API call. * Return to the [platform overview](/home/introduction) to see what you can configure and govern in Control Center. # Encryption Key Management Source: https://dev.writer.com/home/encryption-key-management Control encryption keys for data at rest with Writer-managed or customer-managed (BYOK) encryption across your organization. This page covers how Writer encrypts data at rest and how organization admins can control encryption keys, manage scopes, and connect an external KMS for bring-your-own-key (BYOK) encryption. > [!NOTE] > > Encryption is available on Enterprise plans. Organization admins can manage > encryption settings in Control Center > Security & compliance > Encryption. ## How encryption works Writer uses classic envelope encryption with **AES-256-GCM**. A Data Encryption Key (DEK) encrypts your data, and a Key Encryption Key (KEK)—the master key in KMS—wraps the DEK. The KEK never encrypts application data directly. Depending on enrollment, the KEK is stored in Writer's KMS or your own. Encryption requests flow through the following steps: 1. **Data write**: Writer services send data to the EKM service for encryption 2. **DEK generation**: The EKM service generates a unique DEK for the scope 3. **Key wrapping**: The DEK is sent to the KMS (Writer's or yours) where the KEK wraps it, producing an encrypted DEK (eDEK) 4. **Storage**: Writer encrypts the data with the DEK using AES-256-GCM and stores the eDEK alongside the encrypted data 5. **Data read**: DEK upon retrieval is cached in memory with a five-minute TTL; when the DEK is not in cache, Writer unwraps the eDEK through the KMS and decrypts; when cached, Writer decrypts without contacting the KMS; Writer clears cached DEKs immediately on pause, revoke, rotate, or when the TTL ends ```mermaid theme={null} theme={null} sequenceDiagram participant WS as Writer services participant EKM as EKM Service (Writer) participant KMS as KMS WS->>EKM: Write data EKM->>EKM: Generate DEK for scope EKM->>KMS: Wrap DEK with KEK KMS-->>EKM: Return eDEK EKM->>EKM: Encrypt with DEK (AES-256-GCM), store eDEK WS->>EKM: Read data EKM->>KMS: Unwrap eDEK with KEK KMS-->>EKM: Return DEK EKM-->>WS: Decrypt and return data Note over EKM: DEK cached in memory for five-minute TTL. Evicted on pause, revoke, rotate, or expiry. ``` ## Supported BYOK providers Writer supports BYOK with the following KMS providers: | Provider | Service | | - | - | | **AWS** | [AWS KMS](https://aws.amazon.com/kms/) | | **Azure** | [Azure Key Vault](https://azure.microsoft.com/en-us/products/key-vault) | | **GCP** | [GCP Cloud KMS](https://cloud.google.com/kms/docs) | ## Encryption tiers Default encryption is included on all plans. Writer-managed and BYOK tiers are available on Enterprise plans at no additional cost. | | Default (all plans) | Writer-managed (Enterprise) | BYOK (Enterprise) | | - | - | - | - | | **What's encrypted** | Agent credentials, MCP secrets | All default-tier data plus Writer Agent files, messages, and sessions | Same as Writer-managed | | **KEK ownership** | Writer | Writer | Customer | | **KEK storage** | Writer KMS | Writer KMS (AWS or GCP) | Customer KMS (AWS, Azure, or GCP) | | **Revocation** | Not available | DEK: self-service; KEK: not available | Fully self-service (DEK and KEK) | | **Audit trail** | Writer audit logs | Writer audit logs | Writer audit logs + customer KMS logs | > [!NOTE] > > Encryption currently covers Writer Agent and Connectors. Playbooks, Skills, > custom agents, and no-code agents are not yet covered. ## Scopes Writer organizes encrypted data into hierarchical scopes, each with its own DEK: * **Organization**: Covers all encrypted data in your organization. * **Team**: Covers all Writer Agent data for a single team. * **User**: Covers a user's Writer Agent sessions within a team, including requests, responses, and reasoning output (computer use). Users in multiple teams have a separate user scope in each team. * **Documents**: Covers user-uploaded files and Writer Agent deliverables. * **Connectors**: Covers credentials for each connector instance, so you can pause or revoke access to individual connectors. * **Agent Vault**: Covers agent credentials and secrets. Actions on a parent scope cascade to all child scopes within it. This granular control means you can pause or revoke access to a single team, user, or connector without affecting the rest of your organization. > [!NOTE] > > For Writer-managed encryption, organization-scope revocation requires > [contacting support](mailto:support@writer.com) to prevent accidental data > loss. With BYOK, all scope levels are fully self-service. ## Key actions Organization admins can perform the following actions from the encryption page in Control Center. | Action | Effect | Reversible | | - | - | - | | **Pause** | All decryption requests fail immediately, making data temporarily inaccessible until the key is re-enabled. The key and all wrapped DEKs remain intact. | Yes | | **Resume** | Restores access to a paused scope. | N/A | | **Revoke** | Decryption fails permanently. Depending on your KMS, revocation may mean disabling or scheduling deletion. | No | | **Rotate** | Creates a new KEK version and re-wraps all DEKs under it. The old key can be retained for legacy data or decommissioned per your policy. No downtime. | N/A | > [!WARNING] > > Revoking a key is irreversible. All data encrypted under that scope becomes > permanently inaccessible. ## BYOK controls With BYOK, your customer-managed key (CMK) acts as the KEK and never leaves your cloud provider. Beyond scope-level actions, you can control Writer's access to all encrypted data directly from your KMS console: * **Disable your CMK**: All decrypt operations across your organization fail immediately. Re-enabling the key restores access. * **Delete your CMK**: All decrypt operations fail permanently. This is irreversible. For step-by-step setup instructions, see [Set up BYOK encryption](/home/setup-byok). > [!WARNING] > > Disabling or deleting your CMK affects all encrypted data across your entire > organization, not just a single scope. ## Next steps * [Set up BYOK encryption](/home/setup-byok) to connect your own KMS * [Configure guardrails](/home/guardrails) to enforce content safety and compliance policies # Event logs Source: https://dev.writer.com/home/event-logs View, filter, and search request-level logs to debug issues and audit agent activity in Control Center. Use the Events page in Control Center to find captured LLM calls across your organization, debug failed calls, and understand how your agents interact with models. Logs cover supported LLM calls, not every platform action. Availability can be delayed, and missing source telemetry is not reconstructed. > [!NOTE] > > The Events page is only available to organization admins, IT admins, and AI > Studio full access roles. > [!NOTE] > > Event logs are available for [WRITER > Agent](https://support.writer.com/article/235-ask-writer) and > [API](/api-reference/api-keys)/[SDK](/home/sdks) usage. [Agent Builder > v2](/home/agent-builder/overview) agent events don't appear here or > in AI Studio event logs—see [Agent Builder v2 > observability](/home/agent-builder/observability) for where to find them. ## Access the Events page To open the Events page, [log in to Control Center](https://app.writer.com/controlcenter), select **Activity** in the left sidebar, then select **Observability**. ![The Events page in Control Center showing summary metrics, a request volume chart, and an events table](https://mintcdn.com/writer/vFbqizVppcKHxTck/images/observability-logs-events/navbar-dropdown-observability.png?fit=max\&auto=format\&n=vFbqizVppcKHxTck\&q=85\&s=68623e93185880074cff87f69c01af1d) Use the time range controls to select a preset window or define a custom start and end time. The summary metrics, chart, and events table all update to reflect the selected range. ## Find specific events The events table lists captured calls with their timestamp, success or failure status, model, session ID, creator, and latency when available. To narrow the table to the events you need, use any combination of the following: * **Filters**—narrow by status (success or failure), model, source, or the user that created the request. Combine filters to isolate specific scenarios, such as failed calls for a particular model. * **Search**—search by request ID, session ID, agent run ID, or root agent run ID to locate calls and related activity. * **Time range**—adjust the time window to focus on a specific period of activity. > [!NOTE] > > The **Created by** field displays a resolved user name when the captured call > includes a known user identity. Calls without a resolvable creator can display > **N/A**; creator availability depends on the source, not only whether a call > uses the public API. For continuous export into a warehouse, SIEM, or analytics platform with Airbyte, Fivetran, or Singer, use the [Logs Export API](/home/logs-export). ## Inspect an event Select any row in the events table to open the detail panel. The panel has three tabs: * **Details**—session and request IDs, timestamp, call latency, success or failure status, token usage, model and provider, and call runtime when available. The panel also shows source, run correlation, and guardrail details where recorded (including built-in DLP allow and block outcomes). * **Request**—captured, stored input for the call. * **Response**—captured, stored output for the call. The stored input and output are not necessarily the complete, untouched provider request and response JSON. ### Correlate calls with agent runs When a call has run IDs, the detail panel shows its agent run ID and root agent run ID. Select **View related runs** to find calls associated with the same root. These IDs correlate execution activity only; a root ID does not guarantee a user turn or identify an agent's role. Missing source telemetry and historical records may limit the calls and runs you can inspect. **Agent Response Time** is the lifecycle duration of the selected call's execution leg. It is not the sum of LLM-call latencies, the length of a session or conversation, or exact user-visible latency. Parent, child, and resumed legs remain distinct rather than forming a session total. Timing is unavailable (not zero) for failed or canceled legs, and when lifecycle information is missing or ambiguous. ### Understand unavailable content Body availability is separate from masking. The detail panel reports why captured input or output cannot be shown: * **Not captured** (`not_captured`)—no stored body was captured for the call. * **Pending** (`pending`)—the body is still being processed. * **Unavailable** (`missing` or `failed`)—the stored body cannot be found or retrieved. * **Expired** (`expired`) or **Deleted** (`deleted`)—the stored body has passed its retention window or has been deleted. * **Temporarily unavailable** (`ekm_denied`) or **Authorization unavailable** (`unauthorized`)—body retrieval is blocked by key access or authorization. Select **Retry** when the panel offers it for a retryable pending, temporary key-access, or retrieval failure. Disabling masking does not recover uncaptured, expired, or deleted bodies. ## Mask sensitive content Event logs can capture sensitive information from user prompts and LLM responses. To protect this data, content masking hides these fields in the event detail panel, where they appear as empty values. Masking is enabled by default. To configure masking, select the **Configure masking** control on the Events page. Choose one of the following options and select **Confirm**: * **Enable masking**—user prompts and LLM responses are hidden. These fields appear as empty values in event logs. * **Disable masking**—available captured user prompts and LLM responses are visible in event logs. > [!NOTE] > > API-key body exports use a separate [Logs Export API](/home/logs-export) > authorization path and return available bodies unmasked. ## Next steps Use these guides to export captured logs or review usage. * [Export logs](/home/logs-export): Poll captured calls, terminal-run records, and agent feedback with the Logs Export API * [Built-in DLP guardrail](/home/guardrails-dlp): Block sensitive data before it reaches a model * [Usage and spend](/home/usage-and-spend): Track organization-wide costs and token consumption # Add external models Source: https://dev.writer.com/home/external-models Configure external AI models from providers like AWS Bedrock or OpenRouter to use alongside Palmyra models in Control Center This guide covers how to add and manage external AI models in Control Center. After configuring external models, your organization can use models from providers like AWS Bedrock and OpenRouter alongside Writer's Palmyra models when building agents. > [!NOTE] > > External models are available on enterprise plans. Org admins, IT admins, and > users with Control Center full access roles can add and manage models. For billing, > see [Understand external model billing](#understand-external-model-billing). > [!WARNING] > > Control Center supports **text generation** and **embedding** models from external > providers. Video, audio, and image generation models are not supported. ## Choose how to add models Beyond Writer's Palmyra models, you can add third-party models to your organization in two ways: * **WRITER-managed models**: Select from an array of third-party models that WRITER hosts and manages, such as models from Anthropic, DeepSeek, and Google. You don't bring your own credentials—WRITER meters usage and bills you directly at the rates shown in the [WRITER catalog](/home/pricing#writer-managed-third-party-models). Enable the models you want from the WRITER catalog on the Models page. * **Bring your own model (BYOM) through bring your own key (BYOK)**: Connect models from a provider like [AWS Bedrock](/providers/aws-bedrock) or [OpenRouter](/providers/openrouter) using your own provider credentials. Your provider bills usage directly, and WRITER adds a [10% pass-through fee](#understand-external-model-billing), paid via credits. > [!NOTE] > > WRITER-managed third-party models are available in [WRITER > Agent](/home/pricing#writer-agent) only. They are not yet available through the > API or SDK. BYOM models connected with your own credentials are available > across WRITER Agent and the API. ### Enable WRITER-managed models Use the Models page catalog when you want WRITER to host and bill the model. Provider groups such as Anthropic, DeepSeek, and Google appear with per-model toggles, an **Enable all** / **Disable all** control, and an **Always enable new models** option. 1. Navigate to **Build > Models** in [Control Center](https://app.writer.com/controlcenter) 2. Expand the provider group for the model you want 3. Enable the individual model, or use **Enable all** for that provider 4. Optionally select **Always enable new models** so future catalog models from that provider turn on automatically The rest of this guide covers adding and managing BYOM models with your own credentials. ## How external models work The [Models page in Control Center](https://app.writer.com/controlcenter) provides a unified governance layer for managing AI models across your organization. You can add models from external providers and control which teams have access to use them when building agents. > [!TIP] > > The Models page also displays Writer's Palmyra models. Palmyra models are > always available to all teams and don't require configuration. Select any > Palmyra model to view its details. ![](https://mintcdn.com/writer/iljD9sjySSSg4wwQ/images/home/models-list.png?fit=max\&auto=format\&n=iljD9sjySSSg4wwQ\&q=85\&s=c336ccd96c70cb5ef137cf02d2175f59) External model requests flow through the following steps: 1. **Credential configuration**: Administrators add provider credentials (API keys, access keys, or assume-role settings) to Control Center 2. **Model selection**: Administrators choose which models from the provider to enable 3. **Access control**: Administrators assign model access to all teams or specific teams 4. **Agent building**: Developers with access can select the model when building agents 5. **Request routing**: When agents run, requests route through the configured provider credentials ```mermaid theme={null} sequenceDiagram participant Builder as Agent Builder participant AIS as Control Center participant Creds as Credential Store participant Provider as External Provider
(AWS Bedrock, OpenRouter, etc.) Builder->>AIS: Select model for agent AIS->>Creds: Retrieve provider credentials Creds-->>AIS: Return credentials AIS->>Provider: Forward request with auth Provider-->>AIS: Return model response AIS-->>Builder: Deliver response to agent ``` ## Understand external model billing External models use bring your own model (BYOM) billing. Your provider bills usage directly at its rate card, and WRITER adds a 10% pass-through fee on that usage, paid via credits. This differs from WRITER-managed models, which are metered entirely through WRITER. For rates and details, see [External models (BYOM)](/home/pricing#external-models-byom) on the pricing page. To track spend, see the **Monitor costs** section on each provider page, such as [AWS Bedrock](/providers/aws-bedrock#monitor-costs) or [OpenRouter](/providers/openrouter#monitor-costs). ## Available providers Control Center supports external models from the following providers. Select a provider to view detailed configuration instructions. | Provider | Status | Auth type | Provider docs | | - | - | - | - | | [AWS Bedrock](/providers/aws-bedrock) | Available | Bedrock API key, AWS access keys, or AWS assume role | [View docs](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html) | | [OpenRouter](/providers/openrouter) | Available | API key | [View docs](https://openrouter.ai/docs/quickstart) | > [!NOTE] > > AWS Bedrock models are currently supported in the following regions: > `us-east-1`, `us-west-1`, `us-west-2`, and `eu-west-1`. Additional regions may > be added in future releases. ## Add an external model Add external models in [Control Center](https://app.writer.com/controlcenter) under **Build > Models**. ### Add a model in Control Center For reusability and easier rotation, [create named credentials](#create-credentials-from-the-llm-credentials-page) before adding a model. You can also enter credentials inline during the Add model flow (see [Enter credentials directly](#enter-credentials-directly-when-adding-a-model)). 1. Navigate to **Build > Models** in [Control Center](https://app.writer.com/controlcenter) 2. Under **Bring your own model**, select **+ Add model** 3. Choose your provider (for example, Amazon Bedrock or OpenRouter), then select **Next** 4. Select the model from the **Model name** dropdown 5. Enter a unique **Display name** for the model 6. Provide credentials using one of the following options (not both): * Select an existing credential set from the **Credentials name** dropdown * Enter a new **Credential name** and the provider-specific authentication fields 7. Configure team access (all teams or specific teams) 8. Select **Save** > [!WARNING] > > Use either an existing credential set or new credential fields. Filling both > sides of the credentials section can prevent the form from saving. ![](https://mintcdn.com/writer/iljD9sjySSSg4wwQ/images/home/add-model-provider-select.png?fit=max\&auto=format\&n=iljD9sjySSSg4wwQ\&q=85\&s=73bf2c7ea742c366c0b44e1ebb859f76) ## Manage team access Control which teams can use external models when building agents. ### Configure model availability When adding a model, you can set access to: * **All teams**: The model is immediately available to everyone with builder access * **Specific teams**: Restrict the model to selected teams ### Update team access To view or update which teams can access a model: 1. Navigate to **Build > Models** in Control Center 2. View the current team access in the **Team Access** column 3. Select the menu icon and choose **Edit** to update team access > [!NOTE] > > Credentials are configured at the model level, not the team level. Team access > controls who can use the model, but all authorized users share the same > underlying provider credentials. Team members with access can use the models > but cannot view the credentials. ## Manage credentials Control Center stores provider credentials as named credential sets that you can reuse across multiple models. You can manage credentials from the dedicated **LLM Credentials** page or create them when adding a model. ![](https://mintcdn.com/writer/8JDfj9fvUuSVUhcJ/images/home/llm-credentials-list.png?fit=max\&auto=format\&n=8JDfj9fvUuSVUhcJ\&q=85\&s=a681b20497589a54f83c82af21184a87) ### Create credentials from the LLM Credentials page To create credentials before adding models: 1. Navigate to **Security & compliance > LLM credentials** in [Control Center](https://app.writer.com/controlcenter) 2. Select **Add credentials** 3. Enter a **Credential name** (for example, `dev-aws-credentials` or `prod-openrouter`) 4. Select the **Provider** (for example, Bedrock or OpenRouter) 5. Enter the [provider-specific authentication details](#available-providers) 6. Select **Save** ![](https://mintcdn.com/writer/8JDfj9fvUuSVUhcJ/images/home/add-credentials-modal.png?fit=max\&auto=format\&n=8JDfj9fvUuSVUhcJ\&q=85\&s=67e57f03aaa5de07510982346e259a81) ### Enter credentials directly when adding a model When adding a model, you can enter credentials directly in the Add Model form instead of selecting existing credentials. Credentials entered this way are stored with the model but are not saved as a named credential set for reuse with other models. To create reusable credentials that you can share across multiple models, use the [LLM Credentials page](#create-credentials-from-the-llm-credentials-page) instead. ### Reuse credentials across models When adding additional models from the same provider: 1. Select your existing credentials from the **Credentials name** dropdown 2. The stored authentication details are automatically applied 3. You don't need to re-enter access keys or other sensitive values This approach simplifies management when you have multiple models from the same provider—update credentials in one place and all associated models use the updated values. ### Update credentials How you update expired or rotated credentials depends on how you originally configured them: **Named credentials** (created on the LLM Credentials page): 1. Navigate to **Security & compliance > LLM credentials** in Control Center 2. Locate the credential in the list 3. Select the menu icon and choose **Edit credentials** 4. Update the authentication details and save All models using this credential automatically use the updated values. **Inline credentials** (entered directly when adding a model): 1. Navigate to **Build > Models** in Control Center 2. Locate the model in the list 3. Select the menu icon and choose **Edit** 4. Update the credential values and save > [!TIP] > > For easier credential management, use named credentials from the LLM > Credentials page. Named credentials can be updated in one place and > automatically apply to all models using them. ### Delete credentials To delete a named credential: 1. Navigate to **Security & compliance > LLM credentials** in Control Center 2. Locate the credential in the list 3. Select the menu icon and choose **Delete** > [!WARNING] > > Before deleting credentials, verify that no models are using them. Models > using deleted credentials will fail to authenticate with the provider. ### Security best practices Follow these practices when managing provider credentials: * Use dedicated service accounts rather than personal credentials * Rotate credentials on a regular schedule (for example, every 90 days) * Use descriptive credential names that indicate environment or purpose (for example, `prod-bedrock-us-east`) * For AWS Bedrock, use **AWS assume role** for cross-account access; otherwise use a long-term Bedrock API key or access keys based on your organization's security requirements ### Edit a model To update an external model's configuration, including credentials and team access: 1. Navigate to **Build > Models** in Control Center 2. Locate the model in the list 3. Select the menu icon and choose **Edit** 4. Update the configuration and save ### Delete a model To remove an external model from Control Center: 1. Navigate to **Build > Models** in Control Center 2. Locate the model in the list 3. Select the menu icon and choose **Delete** > [!WARNING] > > Before deleting a model, verify that no active agents depend on it. Agents > that reference a deleted model will return a "model not found" error when they > run. You'll need to update the agent to use a different model before it can > run successfully. ## Troubleshoot model configuration ### Form will not save If the Add model form does not save: * Confirm all required fields for the selected provider and authentication method are complete * Verify the **Model name** comes from the approved dropdown list ### Duplicate model in WRITER Agent If the model dropdown shows a confusing duplicate: * Check whether the same model is already enabled as a WRITER-managed catalog model * Use a distinct **Display name** for the BYOM entry, or delete the extra BYOM model if you intended to use the WRITER-managed version * Do not add a model as BYOM when it is already enabled in the WRITER catalog unless you intentionally want a separate BYOM connection ## Use external models Once you add an external model, it's available to use the same way as Palmyra models. ### Agent Builder In [Agent Builder](/home/agent-builder/overview), external models appear in the **Model** dropdown alongside Palmyra models. Select any model your team has access to. ### API usage External models use the same Writer API as Palmyra models. Use the [List models](/api-reference/completion-api/list-models) endpoint to see all available models and their IDs, then pass the model ID to any endpoint that supports the `model` parameter. ```bash cURL theme={null} curl https://api.writer.com/v1/chat/completions \ -H "Authorization: Bearer $WRITER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "anthropic.claude-3-sonnet-20240229-v1:0", "messages": [{"role": "user", "content": "Hello!"}] }' ``` ```python Python theme={null} from writerai import Writer client = Writer() response = client.chat.chat( model="anthropic.claude-3-sonnet-20240229-v1:0", messages=[{"role": "user", "content": "Hello!"}] ) print(response.choices[0].message.content) ``` ```javascript JavaScript theme={null} import Writer from "writer-sdk"; const client = new Writer(); const response = await client.chat.chat({ model: "anthropic.claude-3-sonnet-20240229-v1:0", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` ## Next steps * [Configure AWS Bedrock](/providers/aws-bedrock): Set up AWS credentials and add Bedrock models * [Configure OpenRouter](/providers/openrouter): Set up an OpenRouter API key and add OpenRouter models * [Choose a model](/home/models-overview): Compare Palmyra models with external provider models * [Palmyra models](/home/models): Explore Writer's Palmyra model capabilities # Manage files Source: https://dev.writer.com/home/files Upload, download, list, and delete files with the File API. Use files in Knowledge Graphs and no-code agents. The File API allows you to manage files in your account. You can upload, download, list, and delete files. After you upload a file, you can use it to perform actions such as attaching it to a [Knowledge Graph](/home/knowledge-graph) or using it as an input in a [no-code agent](/home/applications). This guide shows you how to perform the following actions: * [Upload a file](#upload-a-file) * [Get a file](#get-a-file) * [List all files](#list-all-files) * [Delete a file](#delete-a-file) > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Upload a file **Endpoint**: `POST /v1/files` > [!NOTE] > > A file persists in your account until you [delete it](#delete-a-file). You can optionally provide a `graphId` query parameter to associate the uploaded file with a Knowledge Graph during upload. ```bash cURL theme={null} curl --location --request POST "https://api.writer.com/v1/files?graphId=" \ --header "Content-Type: text/plain" \ --header "Content-Disposition: attachment; filename=" \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data-binary "@" # Example: # = test.txt # = /path/to/test.txt # = 6029b226-1ee0-4239-a1b0-cdeebfa3ad5a (optional) ``` ```python Python theme={null} from pathlib import Path from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() # Read the file contents file_path = Path("") # Replace with your file path, for example: /path/to/test.txt file_name = file_path.name # Get the filename from the path file_ = client.files.upload( content=file_path.read_bytes(), # Read the actual file contents content_disposition=f"attachment; filename={file_name}", content_type="text/plain" ) print(file_.id) ``` ```javascript JavaScript theme={null} import fs from 'fs'; import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const file = await client.files.upload({ content: fs.createReadStream(""), // Replace with your file path, for example: /path/to/test.txt "Content-Disposition": "attachment; filename=", // Replace with your file name, for example: test.txt "Content-Type": "text/plain" }); console.log(file.id) ``` ### Query parameters | Parameter | Type | Description | | - | - | - | | `graphId` | `string` | Optional. The UUID of the Knowledge Graph to associate the uploaded file with. | ### Request body | Parameter | Type | Description | | - | - | - | | `content` | `string` | The content of the file. See the [Python SDK](https://github.com/writer/writer-python?tab=readme-ov-file#file-uploads) and the [JavaScript SDK](https://github.com/writer/writer-node?tab=readme-ov-file#file-uploads) for more details about how to pass the file contents. | | `content_disposition` | `string` | The [content disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) of the file. | | `content_type` | `string` | The [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types) of the file. The file upload supports `txt`, `doc`, `docx`, `ppt`, `pptx`, `jpg`, `png`, `eml`, `html`, `pdf`, `srt`, `csv`, `xls`, and `xlsx` file extensions. | ### Response format | Field | Type | Description | | - | - | - | | `id` | `string` | The ID of the file. | | `created_at` | `string` | The date and time the file was created in ISO 8601 format. | | `name` | `string` | The name of the file. | | `graph_ids` | `array[string]` | The IDs of the Knowledge Graphs the file is attached to. | | `status` | `string` | The processing status of the file. | > [!NOTE] > > If you provide a `graphId` during upload, the file is associated with that Knowledge Graph. However, the `graph_ids` field in the upload response is an empty list. The association is visible in the `graph_ids` list when you retrieve the file using the [Get a file](#get-a-file) endpoint. ```json theme={null} { "id": "1862f090-a281-48f3-8838-26c1e78b605e", "created_at": "2024-06-24T12:34:56Z", "name": "test.txt", "graph_ids": [], "status": "in_progress" } ``` ## List all files **Endpoint**: `GET /v1/files` ```bash cURL theme={null} curl --location --request GET "https://api.writer.com/v1/files" \ --header "Authorization: Bearer $WRITER_API_KEY" ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() page = client.files.list() for file in page.data: print(file.id, file.name, file.graph_ids, file.status) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const files = await client.files.list(); for (const file of files.data) { console.log(file.id, file.name, file.graph_ids, file.status); } ``` ### Query parameters In addition to the [pagination parameters](/api-reference/file-api/get-all-files), this endpoint supports the following query parameters: | Parameter | Type | Description | | - | - | - | | `graph_id` | `string` | Filter files by the graph they are attached to. | | `status` | `string` | Filter files by status. | | `file_types` | `string` | Filter files by extension type. Separate multiple values by commas. For example, `txt,pdf,docx`. | > [!WARNING] > > The `file_types` parameter is not yet available in the Python and Node SDKs. It will be available in version 2.3.0. ### Response format The response has the following structure: | Field | Type | Description | | - | - | - | | `data` | `array[object]` | An array of file objects. | | `data[].id` | `string` | The ID of the file. | | `data[].created_at` | `string` | The date and time the file was created in ISO 8601 format. | | `data[].name` | `string` | The name of the file. | | `data[].graph_ids` | `array[string]` | The IDs of the Knowledge Graphs the file is attached to. | | `data[].status` | `string` | The status of the file. | | `has_more` | `boolean` | Whether there are more files to fetch. | | `first_id` | `string` | The ID of the first file in the response. | | `last_id` | `string` | The ID of the last file in the response. | ```json theme={null} { "data": [ { "id": "f1234-abcd-1234", "created_at": "2025-03-07T23:20:50.978908Z", "name": "my_file.pdf", "graph_ids": [], "status": "completed" }, { "id": "1234-abcd-5678", "created_at": "2025-03-07T23:20:44.047604Z", "name": "my_second_file.pdf", "graph_ids": [], "status": "completed" } ], "has_more": false, "first_id": "f1234-abcd-1234", "last_id": "1234-abcd-5678" } ``` ## Get a file **Endpoint**: `GET /v1/files/{fileId}` ```bash cURL theme={null} curl --location --request GET "https://api.writer.com/v1/files/" \ --header "Authorization: Bearer $WRITER_API_KEY" ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() file = client.files.retrieve("") print(file.id, file.name, file.graph_ids, file.status) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const file = await client.files.retrieve(''); console.log(file.id, file.name, file.graph_ids, file.status) ``` ### Response format ```json theme={null} { "id": "f1234-abcd-1234", "created_at": "2025-03-07T23:20:50.978908Z", "name": "test.txt", "graph_ids": [], "status": "completed" } ``` ## Delete a file **Endpoint**: `DELETE /v1/files/{fileId}` ```bash cURL theme={null} curl --location --request DELETE "https://api.writer.com/v1/files/" \ --header "Authorization: Bearer $WRITER_API_KEY" ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() file = client.files.delete("") ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const fileDeleteResponse = await client.files.delete(''); ``` ### Response format The response has the following structure: ```json theme={null} { "id": "f1234-abcd-1234", "deleted": true } ``` # Understand generative AI Source: https://dev.writer.com/home/generative-ai-overview Learn how generative AI works and how to leverage Writer's models, safety, and best practices for building AI-powered applications. This guide explains how generative AI works and how to use it effectively with Writer's platform. Writer's generative AI enables applications to create text, images, and other content based on patterns learned from training data. Unlike traditional programming where you write explicit instructions, Writer's AI learns to generate appropriate responses by understanding context, patterns, and relationships in data. ## How generative AI works Generative AI operates through a multi-step process that transforms your input into meaningful output: ![Generative AI Overview](https://files.readme.io/265b781-Overview_of_the_generative_AI_workflow.png) ### Core components **Prompts** are the instructions you give to the AI model. They can be short questions, detailed instructions, or examples of the desired output format. Learn effective [prompting techniques](/home/prompting) to get the results you want. **Foundation models** are large neural networks trained on vast amounts of text data. Writer offers [multiple Palmyra models](/home/models) with different capabilities, from fast text generation to advanced reasoning and tool calling. **Tokenization** breaks down your input into smaller units (tokens) that the model can process. Understanding [tokens and pricing](/home/tokens) helps you improve costs and performance. **Neural network processing** is where the model analyzes patterns, context, and relationships to determine the most appropriate response based on its training. **Safety filtering** checks generated content for harmful, biased, or inappropriate material. Writer includes [built-in safety features](/home/toxic-check) to ensure responsible AI usage. ## Writer's model capabilities ### Palmyra models Writer's [Palmyra models](/home/models) provide different capabilities optimized for various use cases. [Palmyra X6](/home/models#palmyra-x6) is the default model for WRITER Agent and is built for long-horizon agentic work: sub-agents, grounding and retrieval, MCP tool use, playbooks, and multi-hour objectives without supervision. [Palmyra X5](/home/models#palmyra-x5) has a 1M token context window, adaptive reasoning, and speed and cost efficiency. It covers general-purpose, financial, medical, and creative use cases. [Palmyra X4](/home/models#palmyra-x4) is also available for complex tasks that require extended context. ### Specialized features * **Tool calling**: Enable models to use [external tools and APIs](/home/tool-calling) for enhanced functionality * **Vision capabilities**: Process and analyze images alongside text using [chat with images](/home/chat-with-images) * **Knowledge Graph integration**: Connect to your data sources for accurate, contextual responses using [Knowledge Graph](/home/knowledge-graph-concepts) * **Streaming**: Get responses in real-time for better user experience with [streaming](/home/streaming) ## Best practices ### Prompt engineering * **Be specific**: Provide clear, detailed instructions for what you want * **Use examples**: Show the model the format or style you're looking for * **Provide context**: Give relevant background information * **Iterate and refine**: Test different approaches to improve results * **Learn more**: Explore [prompting techniques](/home/prompting) for advanced strategies ### Safety and reliability * **Review outputs**: Always check generated content before using it * **Set boundaries**: Define what the AI should and shouldn't do * **Monitor performance**: Track quality and adjust as needed * **Handle errors gracefully**: Plan for cases where the AI doesn't perform as expected ### Performance optimization * **Choose appropriate models**: Select the right [Palmyra model](/home/models) for your use case * **Optimize prompts**: Use clear, concise language and follow [common prompting strategies](/home/prompting) * **Manage context length**: Stay within [token limits](/home/tokens) for best performance * **Use streaming**: Enable [streaming responses](/home/streaming) for real-time delivery * **Fine-tune parameters**: Adjust [model parameters](/home/model-parameters) for optimal results ## Getting started with Writer To begin using Writer's generative AI in your applications: 1. **Choose a model** from [Writer's available models](/home/models) that fits your needs 2. **Design effective prompts** using [prompting techniques](/home/prompting) 3. **Test and iterate** to improve performance 4. **Implement safety measures** using Writer's [built-in safety features](/home/toxic-check) 5. **Monitor and optimize** for ongoing success ## Next steps * Start with the [API quickstart](/home/quickstart) to get up and running * Explore [Writer's models](/home/models) to find the right fit for your use case * Learn [prompting techniques](/home/prompting) for better results * Understand [model parameters](/home/model-parameters) for fine-tuning * See how to [integrate with your applications](/home/integrations-overview) * Build [no-code agents](/home/applications) for rapid prototyping * Connect your data with [Knowledge Graph](/home/knowledge-graph-concepts) for accurate responses # Configure guardrails Source: https://dev.writer.com/home/guardrails Configure guardrails to monitor and filter AI agent inputs and outputs for safety and compliance This page covers the technical architecture and configuration options for guardrails in Control Center. Guardrails enable organizations to enforce content safety, PII protection, and compliance policies across AI agents. You can use Writer's [built-in DLP guardrail](/home/guardrails-dlp) or integrate with external providers like [AWS Bedrock Guardrails](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html) and [Azure AI Content Safety](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/overview). For step-by-step instructions on configuring guardrails in the Control Center interface, see [Setting up guardrails](https://support.writer.com/article/312-guardrails) in the Writer Help Center. > [!NOTE] > > Guardrails are available on Enterprise plans. Org admins and IT admins can > configure guardrails in Control Center. ## How guardrails work Control Center's guardrail system sits between your agents and LLM calls, intercepting requests at configurable points to check content against your configured guardrail providers. This architecture provides centralized safety controls and compliance enforcement for all AI interactions. > [!NOTE] > > For now, guardrails used with the API, SDK, and Agent Builder will only apply > to external provider models. Guardrails can check content at three points in the request lifecycle: * **Pre-call check**: Checks **user input** before the LLM call. Use this to block sensitive data users might accidentally submit (credit cards, Social Security numbers), stop prompt injection attacks, or filter inappropriate prompts. If content is blocked, the LLM is never called, saving costs. * **Post-call check**: Checks **LLM output** before returning it to the user. Use this to catch sensitive data the LLM might generate in its response, filter inappropriate or off-topic content, or verify compliance of generated text. Even if user input is clean, the LLM might hallucinate PII or generate policy-violating content. * **During-call check**: Checks content **in parallel** with the LLM call. Use this when you want to check input but can't afford the latency of waiting for a pre-call check to complete before starting the LLM call. The check runs concurrently, and the response is held until both the LLM and guardrail finish. When a guardrail detects a violation, the request is halted and an error is returned to the agent. > [!NOTE] > > For no-code chat apps, guardrails evaluate only the last message in the > conversation, not the full conversation history. ```mermaid theme={null} sequenceDiagram participant Agent as AI Agent participant Gateway as Control Center Gateway participant Guardrail as Guardrail Provider
(AWS Bedrock, Azure Content Safety) participant LLM as LLM Agent->>Gateway: Send request Note over Gateway,Guardrail: Pre-call check (optional) Gateway->>Guardrail: Check input Guardrail-->>Gateway: Allow / Block Gateway->>LLM: Forward request Note over Gateway,Guardrail: During-call check (optional) Gateway->>Guardrail: Check in parallel LLM-->>Gateway: Return response Guardrail-->>Gateway: Allow / Block Note over Gateway,Guardrail: Post-call check (optional) Gateway->>Guardrail: Check output Guardrail-->>Gateway: Allow / Block Gateway-->>Agent: Return response ``` ## Supported guardrail providers Control Center includes a built-in DLP guardrail and integrates with the following external providers. ### Built-in DLP guardrail The [built-in Data Loss Prevention (DLP) guardrail](/home/guardrails-dlp) blocks personal information, financial data, government IDs, healthcare identifiers, and secrets before they reach a model. There is no third-party provider to configure and no additional credentials to manage. For detailed behavior and limitations, see [Built-in DLP guardrail](/home/guardrails-dlp). For step-by-step UI setup, see [Built-in Data Loss Prevention (DLP) guardrail](https://support.writer.com/articles/9477002647-built-in-data-loss-prevention-dlp-guardrail) in the Writer Help Center. ### AWS Bedrock Guardrails [AWS Bedrock Guardrails](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html) is Amazon's content filtering and PII detection service. It provides content filters, denied topic detection, word filters, sensitive information filters, and contextual grounding checks. For detailed setup instructions, see [Set up Bedrock guardrails](/home/guardrails-bedrock). ### Azure AI Content Safety [Azure AI Content Safety](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/overview) is Microsoft's content moderation service. Control Center supports two Azure Content Safety guardrail types: * **Text Moderation**: Analyzes text for harmful content categories (Hate, Sexual, SelfHarm, Violence) with configurable severity thresholds. * **Prompt Shields**: Detects prompt injection attacks in user inputs and malicious content embedded in documents. For detailed setup instructions, see [Set up Azure Content Safety guardrails](/home/guardrails-azure). ## Guardrail modes Select one or more modes when configuring a guardrail. You can combine modes; for example, use `pre_call` to check user input AND `post_call` to check LLM output for comprehensive protection. | Mode | What it checks | When to use | | - | - | - | | `pre_call` | User input | Block PII users submit, prevent [prompt injection](/home/prompt_injections), filter harmful prompts | | `post_call` | LLM output | Catch PII the LLM generates, filter inappropriate responses, verify compliance | | `during_call` | Input (parallel) | Same as pre-call but with lower latency for time-sensitive apps | ### Pre-call mode Executes synchronously **before** the LLM call. If content is blocked, the LLM is never called. * Checks user input only * Saves LLM costs when blocking bad requests * Adds latency before the LLM call starts ### Post-call mode Executes synchronously **after** the LLM generates a response. * Checks LLM output only * Required for catching issues in LLM-generated content (the LLM might generate PII even if the input was clean) * Adds latency after LLM processing ### During-call mode Executes **in parallel** with the LLM call. The response is held until both the LLM and guardrail check complete. * Checks input while the LLM processes the request * Lower latency than pre-call if the guardrail check finishes before the LLM * Useful for [streaming](/home/streaming) responses where latency matters ## Team scoping By default, a guardrail applies to all teams in your organization. You can restrict a guardrail to specific teams if different teams have different compliance requirements. For example: * A **healthcare team** might need strict HIPAA-compliant PII blocking * A **marketing team** might only need basic content moderation * An **internal tools team** might not need guardrails at all When a guardrail is scoped to specific teams, requests from users on other teams skip that guardrail entirely. | Scope setting | Behavior | | - | - | | All teams (default) | Guardrail runs for all requests in the organization | | Selected teams | Guardrail only runs for requests from users on those teams | When you create a new guardrail, it automatically applies to all agents within its configured scope—no agent reconfiguration is needed. If you delete a guardrail, agents continue to function normally but without that guardrail's protections. ## Error handling When a guardrail blocks content, the system returns an error to the agent. The error includes: * The guardrail name that triggered the block * The type of violation detected (for example, `CREDIT_CARD` or `US_SSN` for PII blocks) * A message indicating content was blocked ```json theme={null} { "tpe": "BadRequest", "errors": [ { "description": "Content blocked by guardrail: PII detected", "key": "fail.guardrail.blocked", "extras": { "guardrail_name": "pii-filter", "entity_type": "CREDIT_CARD" } } ], "extras": {} } ``` Agents should handle guardrail errors gracefully and provide appropriate feedback to users. For PII blocks, consider prompting users to remove sensitive information and retry. For a complete list of guardrail error codes, see [Error codes](/api-reference/error-codes#guardrails). ## Best practices ### Defense in depth Layer multiple guardrails for comprehensive protection: 1. **Built-in DLP** (Pre-call): Block sensitive data with Writer's native guardrail before LLM processing 2. **Input filtering** (Pre-call): Block malicious prompts and additional PII with Bedrock or Azure before LLM processing 3. **Output filtering** (Post-call): Catch issues in LLM-generated content You can layer the [built-in DLP guardrail](/home/guardrails-dlp) with Bedrock or Azure guardrails. When DLP blocks a request, later guardrails in the execution order do not run. If DLP must inspect data before an external pre-call guardrail, assign DLP the lowest priority number. ### Performance considerations Guardrails add processing time to each request, so consider the latency impact when designing your guardrail strategy. This is especially important for real-time applications like chat interfaces where response time affects user experience. * **Pre-call guardrails** add latency before the LLM call. However, when content is blocked, pre-call mode is actually faster overall because it prevents the LLM call entirely. * **Post-call guardrails** add latency after the LLM response is received. The total request time is the LLM processing time plus the guardrail check time. * **During-call guardrails** run in parallel with the LLM call but buffer (hold) the response until the guardrail check completes. This means if the guardrail check takes longer than the LLM call, the response is delayed until the check finishes. If the LLM call takes longer, there's minimal added latency since the check completes while waiting. For latency-sensitive applications, consider using pre-call mode for input validation to block bad requests early and avoid unnecessary LLM calls. ### Streaming responses Guardrail modes behave differently with streaming responses: * **During-call**: Checks input in parallel with the LLM. If the check finishes before the LLM starts outputting, streaming begins immediately. If the check takes longer, streaming is delayed until the check completes—but output chunks aren't buffered. * **Post-call**: Collects all response chunks, assembles the complete response, runs the guardrail check, then delivers the chunks. The user doesn't receive any chunks until the guardrail check completes, so streaming latency is higher than non-streaming. For latency-sensitive streaming applications, prefer during-call mode for input validation over post-call output checking when possible. ### Provider rate limits Rate limits depend on your guardrail provider: * **AWS Bedrock Guardrails**: See [Bedrock quotas](https://docs.aws.amazon.com/bedrock/latest/userguide/quotas.html) for current limits. You can request quota increases through the AWS Service Quotas console. * **Azure AI Content Safety**: See [Content Safety service limits](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/overview#service-limits) for current limits. To request a rate increase, [contact Microsoft](mailto:contentsafetysupport@microsoft.com). ## Next steps * [Built-in DLP guardrail](/home/guardrails-dlp): Block sensitive data with Writer's native pre-call guardrail * [Set up Bedrock guardrails](/home/guardrails-bedrock): Configure AWS Bedrock for content filtering and PII detection * [Set up Azure Content Safety guardrails](/home/guardrails-azure): Configure Azure Content Safety for text moderation and prompt injection detection * [Prevent prompt injections](/home/prompt_injections): Learn about prompt injection attacks and mitigation * [Setting up guardrails](https://support.writer.com/article/312-guardrails): Step-by-step UI configuration in the Help Center # Set up Azure Content Safety guardrails Source: https://dev.writer.com/home/guardrails-azure Configure Azure AI Content Safety for text moderation and prompt injection detection This guide shows you how to configure [Azure AI Content Safety](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/overview) guardrails with Control Center. After completing this setup, Control Center can use Azure Content Safety to moderate harmful content and detect prompt injection attacks across your AI agents. Control Center supports two Azure Content Safety guardrail types: * **Text Moderation**: Analyzes text for harmful content categories with configurable severity thresholds * **Prompt Shields**: Detects prompt injection attacks in user inputs and malicious content embedded in documents Configure these as separate guardrails in Control Center, allowing you to enable one or both depending on your safety requirements. For an overview of how guardrails work in Control Center, see [Configure guardrails](/home/guardrails). ## Prerequisites Before configuring Azure Content Safety guardrails in Control Center, prepare the following: * An Azure account with an active subscription * An Azure AI Content Safety resource deployed in a [supported region](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/overview#region-availability) * The API key and endpoint for your Content Safety resource * Enterprise plan access to Control Center ## Create a content safety resource and get credentials If you haven't created an Azure AI Content Safety resource yet, follow these steps: 1. Sign in to the [Azure portal](https://portal.azure.com) 2. Select **Create a resource** and search for **Content Safety** 3. Select **Azure AI Content Safety** and select **Create** 4. Configure your resource: * Select your **Subscription** and **Resource group** * Choose a [supported region](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/overview#region-availability) * Enter a unique **Name** for your resource * Select a **Pricing tier** 5. Select **Review + create**, then **Create** 6. After deployment completes, navigate to your resource and go to **Resource Management > Keys and Endpoint** 7. Copy one of the **Keys** (either KEY 1 or KEY 2) and the **Endpoint** URL (for example, `https://your-resource-name.cognitiveservices.azure.com/`) for use in [Control Center](#configure-in-control-center) For more information on creating and managing Azure Content Safety resources, see the [Azure Content Safety documentation](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/overview). ## Configure in Control Center When adding an Azure Content Safety guardrail in Control Center, provide these parameters: | Parameter | Description | | - | - | | API key | Your Azure Content Safety API key (from the Azure portal) | | API base | Your Content Safety endpoint URL (for example, `https://your-resource-name.cognitiveservices.azure.com/`) | **Text Moderation** guardrails also accept the following optional parameters: | Parameter | Description | Default | | - | - | - | | Categories | The content categories to evaluate. Select one or more: **Hate**, **SelfHarm**, **Sexual**, **Violence**. | All categories selected | | Severity threshold | The minimum severity level (0–6) that triggers a block. Lower values are more strict. For example, a threshold of `2` blocks content with a severity score of 2 or higher. | `2` | > [!NOTE] > > By default, a guardrail applies to all teams in your organization. You can restrict it to specific teams during configuration. See [Team scoping](/home/guardrails#team-scoping) for details. ## Text Moderation Azure Content Safety Text Moderation analyzes text for harmful content across four categories: | Category | Description | | - | - | | Hate | Discriminatory or prejudiced content targeting identity groups | | Sexual | Sexually explicit or suggestive content | | Self-Harm | Content related to self-harm or suicide | | Violence | Violent, threatening, or graphic content | ### How Text Moderation works with Control Center When configured as a guardrail, Text Moderation checks text content against each category and blocks the request if any category's severity score meets or exceeds the configured threshold. Text Moderation supports the following guardrail modes: * **Pre-call**: Check user input before the LLM processes it. Blocks harmful prompts and saves LLM costs. * **Post-call**: Check LLM output before returning it to the user. Catches harmful content the LLM might generate. For more information on severity levels and content categories, see [Harm categories](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/concepts/harm-categories) in the Azure documentation. ## Prompt Shields Azure Content Safety Prompt Shields detects prompt injection attacks—attempts by users or embedded documents to manipulate an AI model into bypassing its safety rules or instructions. Prompt Shields detects two types of attacks: | Attack type | Description | | - | - | | User Prompt attacks | Malicious instructions in user input designed to override the model's system prompt or safety behaviors | | Document attacks | Harmful commands embedded in documents or external content that the model processes | ### How Prompt Shields works with Control Center When configured as a guardrail, Prompt Shields analyzes user prompts and any associated documents for injection attacks. If an attack is detected, Control Center blocks the request. Prompt Shields supports the following guardrail modes: * **Pre-call**: Check user input and documents before the LLM call. Blocks prompt injection attempts and prevents the LLM from processing malicious content. * **During-call**: Check input in parallel with the LLM call for lower latency. For more information on prompt injection detection, see [Prompt Shields](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/concepts/jailbreak-detection) in the Azure documentation. ## Verify your setup Before configuring Azure Content Safety in Control Center, test your resource directly to confirm your API key and endpoint work. ### Test Text Moderation Run this cURL command, replacing `` and `` with your values: ```shell theme={null} curl --location --request POST '/contentsafety/text:analyze?api-version=2024-09-01' \ --header 'Ocp-Apim-Subscription-Key: ' \ --header 'Content-Type: application/json' \ --data-raw '{ "text": "This is a test message", "categories": ["Hate", "Sexual", "SelfHarm", "Violence"] }' ``` A successful response returns severity scores for each category: ```json theme={null} { "categoriesAnalysis": [ { "category": "Hate", "severity": 0 }, { "category": "SelfHarm", "severity": 0 }, { "category": "Sexual", "severity": 0 }, { "category": "Violence", "severity": 0 } ] } ``` ### Test Prompt Shields Run this cURL command, replacing `` and `` with your values: ```shell theme={null} curl --location --request POST '/contentsafety/text:shieldPrompt?api-version=2024-09-01' \ --header 'Ocp-Apim-Subscription-Key: ' \ --header 'Content-Type: application/json' \ --data-raw '{ "userPrompt": "This is a test message", "documents": ["This is a test document"] }' ``` A successful response indicates whether an attack was detected: ```json theme={null} { "userPromptAnalysis": { "attackDetected": false }, "documentsAnalysis": [{ "attackDetected": false }] } ``` If either command returns an error, check that your API key and endpoint are correct and that your Content Safety resource is deployed in a supported region. ## Next steps * [Configure guardrails](/home/guardrails): Learn about guardrail modes, team scoping, and error handling * [Track usage and spend](/home/observability): Monitor guardrail activity and usage * [Azure AI Content Safety documentation](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/overview): Detailed Azure documentation * [Azure Content Safety pricing](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/content-safety/): Understand Azure Content Safety costs # Set up Bedrock guardrails Source: https://dev.writer.com/home/guardrails-bedrock Configure AWS Bedrock Guardrails for content filtering and sensitive data protection This guide shows you how to configure [AWS Bedrock Guardrails](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html) with Control Center. After completing this setup, Control Center can use your Bedrock guardrails to filter content, detect PII, and enforce topic policies across your AI agents. For an overview of how guardrails work in Control Center, see [Configure guardrails](/home/guardrails). ## Prerequisites Before configuring Bedrock guardrails in Control Center, prepare the following: * An AWS account with access to Amazon Bedrock * A Bedrock guardrail created in the AWS console * AWS credentials with permission to invoke the guardrail * Enterprise plan access to Control Center ## Create a Bedrock guardrail in AWS If you haven't created a Bedrock guardrail yet, follow these steps in the AWS console: 1. Navigate to **Amazon Bedrock > Guardrails** in the AWS console 2. Select **Create guardrail** 3. Configure your guardrail policies: * **Content filters**: Block harmful content categories (hate, insults, sexual, violence) * **Denied topics**: Define custom topics to block * **Word filters**: Block specific words or phrases * **Sensitive information filters**: Detect and block PII types * **Contextual grounding**: Check for hallucinations and relevance 4. Save your guardrail and note the **Guardrail ID** and **Version** For detailed instructions, see [Create a guardrail](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-create.html) in the AWS documentation. ## Configuration parameters Configure these parameters when adding a Bedrock guardrail in Control Center: ### Required parameters | Parameter | Description | | - | - | | `guardrailIdentifier` | The unique ID of your Bedrock guardrail (found in the AWS console) | | `guardrailVersion` | The version of your guardrail (`DRAFT` or a version number like `1`, `2`) | | `aws_region_name` | AWS region where your guardrail is deployed. Define the guardrail in the same region where your inference requests are made. See [supported regions](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-cross-region-support.html) in the AWS documentation. | | `aws_access_key_id` | AWS access key ID for authentication | | `aws_secret_access_key` | AWS secret access key for authentication | ### Optional parameters | Parameter | Description | | - | - | | `disable_exception_on_block` | When `true`, returns a modified response instead of raising an exception when content is blocked. Useful for chat interfaces where exceptions may disrupt the conversation flow. Default: `false` | | `aws_session_token` | Session token for temporary AWS credentials (required when using STS) | | `aws_session_name` | Name for the AWS session | | `aws_profile_name` | AWS profile name for credential retrieval from `~/.aws/credentials` | | `aws_role_name` | IAM role name for cross-account access or role assumption | | `aws_web_identity_token` | Web identity token for OIDC-based authentication | | `aws_sts_endpoint` | Custom AWS STS endpoint URL | | `aws_bedrock_runtime_endpoint` | Custom Bedrock runtime endpoint URL | ## AWS authentication options Control Center supports multiple [AWS authentication methods](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) for Bedrock guardrails. ### Access keys (recommended for getting started) Use IAM user access keys for straightforward authentication: ``` aws_access_key_id: AKIAIOSFODNN7EXAMPLE aws_secret_access_key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY aws_region_name: us-east-1 ``` ### Temporary credentials (STS) Use temporary credentials from [AWS Security Token Service](https://docs.aws.amazon.com/STS/latest/APIReference/welcome.html): ``` aws_access_key_id: ASIAXXX... aws_secret_access_key: xxx... aws_session_token: FwoGZXIvYXdzEBY... aws_region_name: us-east-1 ``` ### IAM role assumption Assume an IAM role for cross-account access or elevated permissions: ``` aws_access_key_id: AKIAIOSFODNN7EXAMPLE aws_secret_access_key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY aws_role_name: bedrock-guardrail-role aws_region_name: us-east-1 ``` ### Web identity (OIDC) Use OIDC tokens for container-based or Kubernetes deployments: ``` aws_web_identity_token: eyJhbGciOiJSUzI1NiIs... aws_role_name: bedrock-guardrail-role aws_region_name: us-east-1 ``` ## Required IAM permissions The AWS credentials you provide must have permission to invoke your Bedrock guardrail. Create an IAM policy with the following permissions: ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["bedrock:ApplyGuardrail"], "Resource": "arn:aws:bedrock:*:*:guardrail/*" } ] } ``` For production environments, scope the resource ARN to your specific guardrail: ```json theme={null} { "Resource": "arn:aws:bedrock:us-east-1:123456789012:guardrail/abc123def456" } ``` ## Guardrail versioning Bedrock guardrails support versioning, allowing you to test changes before applying them to production: | Version value | Behavior | | - | - | | `DRAFT` | Uses the current draft version (for testing) | | `1`, `2`, etc. | Uses a specific published version | **Recommended workflow:** 1. Test guardrail changes using `DRAFT` version in a development environment 2. Publish a new version in the AWS console when satisfied 3. Update production Control Center configuration to use the new version number ## Bedrock guardrail capabilities AWS Bedrock Guardrails provide several content filtering capabilities: ### Content filters Block content based on harmful categories with configurable thresholds: * **Hate**: Discriminatory or prejudiced content * **Insults**: Demeaning or offensive language * **Sexual**: Sexually explicit content * **Violence**: Violent or threatening content * **Misconduct**: Content promoting illegal activities * **Prompt attacks**: Attempts to manipulate the model ### Denied topics Define custom topics that should be blocked. Useful for: * Preventing discussion of competitors * Blocking off-topic conversations * Enforcing industry-specific restrictions ### Sensitive information filters Detect and block PII types including: * Names, addresses, phone numbers * Email addresses, URLs * Credit card numbers, bank accounts * Social Security numbers (US) * Driver's license numbers * Passport numbers ### Word filters Block specific words, phrases, or patterns. Supports: * Exact word matching * Profanity filters * Custom blocked terms ## Error handling When Bedrock blocks content, Control Center returns an error to the agent. The default behavior raises an exception that halts the request. Set `disable_exception_on_block: true` to return a modified response instead of raising an exception. This is useful for: * Chat interfaces where exceptions disrupt the conversation * Applications that need to handle blocks gracefully * Scenarios where you want to show a custom message to users ## Troubleshooting ### Common errors | Error | Cause | Solution | | - | - | - | | `AccessDeniedException` | Missing IAM permissions | Verify your IAM policy includes `bedrock:ApplyGuardrail` | | `ResourceNotFoundException` | Invalid guardrail ID or version | Check the guardrail ID and version in the AWS console | | `ValidationException` | Invalid parameters | Verify region name and other parameters are correct | | `ThrottlingException` | Rate limit exceeded | Implement retry logic or request a quota increase | ### Verify your guardrail Test your guardrail directly in the AWS console before configuring it in Control Center: 1. Navigate to your guardrail in the AWS Bedrock console 2. Select **Test** to open the testing interface 3. Enter sample content that should trigger the guardrail 4. Verify the guardrail blocks or allows content as expected ## Next steps * [Configure guardrails](/home/guardrails): Learn about guardrail modes and scoping * [Usage and spend](/home/usage-and-spend): Monitor guardrail activity and usage * [AWS Bedrock Guardrails documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html): Detailed AWS documentation * [Create a guardrail in AWS](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-create.html): Step-by-step AWS console instructions * [AWS Bedrock pricing](https://aws.amazon.com/bedrock/pricing/): Understand Bedrock guardrail costs # Built-in DLP guardrail Source: https://dev.writer.com/home/guardrails-dlp Use Writer's built-in Data Loss Prevention guardrail to block sensitive data before it reaches a model This page covers how the built-in Data Loss Prevention (DLP) guardrail works and how to enable it in Control Center. After you enable it, Writer blocks prompts that contain selected categories of sensitive data before the model is invoked. There is no third-party provider to configure and no additional credentials to manage. > [!NOTE] > > Only IT admins can enable and configure the DLP guardrail. Each organization > can have one DLP guardrail. ## What the guardrail detects The DLP guardrail scans for the following categories of sensitive data. You can enable or disable individual categories when you configure the guardrail. * **Personal information**—names, email addresses, phone numbers, street addresses, and other personally identifiable information * **Financial data**—credit card numbers, bank account numbers, and related financial identifiers * **Government IDs**—national identification numbers, Social Security numbers, passport numbers, and similar government-issued identifiers * **Healthcare identifiers**—medical record numbers, health insurance identifiers, and other protected health information identifiers * **Secrets and credentials**—API keys, access tokens, passwords, and other credentials that could grant unauthorized access When the guardrail detects sensitive data in an enabled category, it blocks the entire request. The model never receives the content. The guardrail does not redact or mask sensitive content and continue. ## How the guardrail runs The DLP guardrail runs a pre-call check on prompt text and files uploaded to a session. When it blocks a request, later guardrails in the execution order do not run. Execution order follows each guardrail's priority number. If multiple guardrails share the same priority, the one created earlier runs first. You can configure DLP to fail closed or fail open when the DLP service is unavailable: * **Fail closed**—block all requests until the service recovers * **Fail open**—allow requests through until the service recovers You can also scope the guardrail to specific teams and models. If you select both specific teams and specific models, the guardrail applies only where they overlap—not to all selected teams or all selected models independently. > [!NOTE] > > The current release does not inspect model output (post-call), data retrieved > through connectors, tool calls, or Knowledge Graph. Post-call detection is > planned for a later release. ## Enable the DLP guardrail IT admins enable the DLP guardrail in Control Center so it applies across the teams and models you select. **1. Open Guardrails in Control Center** Log in to [Control Center](https://app.writer.com/controlcenter), then go to **Security & compliance** > **Guardrails**. Find the Writer-provided Data Loss Prevention guardrail and turn it on to open the setup modal. ![](https://mintcdn.com/writer/k1o6BZPBocVOQSKr/images/home/guardrails-dlp/guardrails-list.png?fit=max\&auto=format\&n=k1o6BZPBocVOQSKr\&q=85\&s=6f719da26fa74f2ba7b96697e91740d7) The modal opens on **Basic info**. Mode is **Pre-call only**. Set a priority. Lower numbers run first. If two guardrails share a priority, the one created earlier runs first. Select **Next**. ![](https://mintcdn.com/writer/k1o6BZPBocVOQSKr/images/home/guardrails-dlp/configure-basic-info.png?fit=max\&auto=format\&n=k1o6BZPBocVOQSKr\&q=85\&s=13be141db2bc51b42a1745b95647973f) **2. Select categories to block** On **Detection**, choose the categories of sensitive data to block, or accept the default set: Personal information, Financial, Government IDs, Healthcare, and Secrets & credentials. You can change these later. ![](https://mintcdn.com/writer/k1o6BZPBocVOQSKr/images/home/guardrails-dlp/configure-detection.png?fit=max\&auto=format\&n=k1o6BZPBocVOQSKr\&q=85\&s=213090fd030f1c46bac0402f95301951) **3. Choose fail behavior** Under **If the guardrail is unable to run**, choose what happens if the detection service is unavailable: * **Block the request** (fail closed)—block all requests until the service recovers * **Allow the request** (fail open)—allow requests through until the service recovers ![](https://mintcdn.com/writer/k1o6BZPBocVOQSKr/images/home/guardrails-dlp/fail-behavior.png?fit=max\&auto=format\&n=k1o6BZPBocVOQSKr\&q=85\&s=cbe768f34239543519599adf7edaa859) **4. Scope teams and models** Under **Apply to** and **Apply to models**, select all teams and models, or limit the guardrail to specific ones. If you select both specific teams and specific models, the guardrail applies only where they overlap—not to all selected teams or all selected models independently. **All models** includes current and future models. Select **Next**. ![](https://mintcdn.com/writer/k1o6BZPBocVOQSKr/images/home/guardrails-dlp/scope-teams-models.png?fit=max\&auto=format\&n=k1o6BZPBocVOQSKr\&q=85\&s=a486b0c66e46c3cfa5bdd0a368a65af5) **5. Test and save** On **Preview**, enter sample input and select **Preview**. Confirm the guardrail blocks sensitive content, then select **Save changes**. ![](https://mintcdn.com/writer/k1o6BZPBocVOQSKr/images/home/guardrails-dlp/preview-blocked.png?fit=max\&auto=format\&n=k1o6BZPBocVOQSKr\&q=85\&s=e5be723f0c311371ee379baeb578e894) If you have multiple guardrails enabled (for example Bedrock and Azure), the one with the lower priority number runs first. If multiple share the same priority, the one created earlier runs first. When DLP blocks a request, later guardrails do not run and the model is not invoked. > [!TIP] > > Start by blocking only the most sensitive categories, test on the next screen, > and consider scoping the guardrail to one team before rolling it out more > widely. You can disable the guardrail at any time by turning the toggle off on the Guardrails page. ## How users experience a blocked request When a user submits a prompt that contains sensitive data matching an enabled category, the guardrail blocks the request before the model call. The user receives a message indicating that the request was blocked to protect sensitive information, and no content is sent to the model. The original session remains intact. The user can revise the prompt to remove the sensitive data and resubmit, or continue working in the same session. ## Monitor guardrail decisions Allow and block decisions, including which categories triggered a block, appear in [event logs](/home/event-logs) and traces. You can also filter for them with the `guardrail_outcome` parameter on the [Logs Export API](/home/logs-export). ## Next steps After you enable DLP, review related guardrail and logging guides. * [Configure guardrails](/home/guardrails): Learn about guardrail modes, team scoping, and provider integrations * [Event logs](/home/event-logs): View guardrail allow and block decisions in Control Center * [Export logs](/home/logs-export): Stream logs and filter by `guardrail_outcome` # Help Center Source: https://dev.writer.com/home/help-center # Work with inline citations in Knowledge Graph responses Source: https://dev.writer.com/home/inline-citations This guide shows you how to work with inline citations in Knowledge Graph responses. Inline citations show which specific sources support each part of the response, enabling you to verify information and trace claims back to their origins. > [card] Response with inline citations > > Below is an example of a response from a Knowledge Graph that includes inline citations: > > ``` > Acme Corp's flagship product line includes three > main categories: industrial tools, consumer > electronics, and automotive parts. The industrial > tools division offers precision manufacturing > equipment with advanced automation capabilities > [Acme-Product-Catalog.pdf](a1b2c3d4-e5f6-7890-abcd-ef1234567890). > ``` > [card] Corresponding references array > > Below is the corresponding `references` object that contains a direct snippet from the source file that was used to support the response: > > ```json theme={null} > {"files": [ > { > "text": "Industrial Tools Division: Our precision manufacturing equipment features advanced automation capabilities with real-time monitoring systems that reduce operational downtime by up to 40% through predictive maintenance algorithms.", > "fileId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", > "score": 0.95, > "page": 12, > "cite": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" > } > ]} > ``` ## Enable inline citations To enable inline citations in Knowledge Graph responses, set `inline_citations: true` in your `query_config` parameter when making direct Knowledge Graph queries via the `/v1/graphs/question` endpoint. ```bash cURL highlight={7-9} theme={null} curl --location --request POST 'https://api.writer.com/v1/graphs/question' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header 'Content-Type: application/json' \ --data-raw '{ "graph_ids": [""], "question": "What are the key features of our product?", "query_config": { "inline_citations": true } }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client client = Writer() # Query Knowledge Graph with inline citations enabled response = client.graphs.question( graph_ids=[""], question="What are the key features of our product?", query_config={ "inline_citations": True } ) print(f"Answer: {response.answer}") print(f"\nFile references: {response.references.files}") print(f"\nWeb references: {response.references.web}") ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the Writer client const client = new Writer(); // Query Knowledge Graph with inline citations enabled const response = await client.graphs.question({ graph_ids: [""], question: "What are the key features of our product?", query_config: { inline_citations: true } }); console.log(`Answer: ${response.answer}`); console.log(`\nFile references: ${response.references.files}`); console.log(`\nWeb references: ${response.references.web}`); ``` ## Citation format and correlation ### Citation format Inline citations appear in the answer from the LLM as `[source_name](identifier)`, where: * `source_name` is the display name of the source: either the filename for files, or the page title for web sources * `identifier` is the unique identifier used to correlate with the references array The identifier format depends on the source type: * **File sources**: Uses the `cite` field value, for example, `[document.pdf](a1b2c3d4-e5f6-7890-abcd-ef1234567890)` * **Web sources**: Uses the `url` field value, for example, `[Web Page Title](https://example.com/page)` ### Correlate citations with references Inline citations correspond to entries in the `references` object. Correlation differs by source type: * **File sources**: Citations use the `cite` field from the file reference object as their identifier * **Web sources**: Citations use the `url` field from the web reference object as their identifier **Example correlation**: Here's an example showing how inline citations correlate with the references array for both file and web sources: **Response text**: ``` Acme Corp's flagship product line includes three main categories: industrial tools, consumer electronics, and automotive parts. The industrial tools division offers precision manufacturing equipment with advanced automation capabilities [Acme-Product-Catalog.pdf](a1b2c3d4-e5f6-7890-abcd-ef1234567890). According to recent industry analysis, smart manufacturing adoption has increased by 40% across similar companies [Industry Trends Report](https://example.com/industry-trends). ``` **References object**: ```json theme={null} { "files": [ { "text": "Industrial Tools Division: Our precision manufacturing equipment features advanced automation capabilities with real-time monitoring systems that reduce operational downtime by up to 40% through predictive maintenance algorithms.", "fileId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "score": 0.95, "page": 12, "cite": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } ], "web": [ { "text": "Smart manufacturing adoption rates have increased by 40% across mid-size manufacturing companies, driven by automation and IoT integration.", "url": "https://example.com/industry-trends", "title": "Industry Trends Report", "score": 0.88 } ] } ``` **Citation mapping**: * Citation `[Acme-Product-Catalog.pdf](a1b2c3d4-e5f6-7890-abcd-ef1234567890)` uses the `cite` field from the file reference object * Citation `[Industry Trends Report](https://example.com/industry-trends)` uses the `url` field from the web reference object ## Link citations to source text with SDKs When working with inline citations in SDK responses, you can programmatically link citation IDs to their corresponding source text. This enables you to build applications that display citations with their source material. ### Extract and correlate citations These code samples demonstrate how to extract inline citations from Knowledge Graph responses and correlate them with their source material. The code parses citation markers in the answer text (like `[filename](citation-id)`) and matches them to the corresponding source text in the references object. Using similar patterns, you can extract citations and build applications that display citations with their source material. ```python Python theme={null} from writerai import Writer import re # Initialize the Writer client client = Writer() # Query Knowledge Graph with inline citations response = client.graphs.question( graph_ids=[""], question="What are the key features of our product?", query_config={ "inline_citations": True } ) def extract_citations_with_sources(answer_text, references): '''Extract citations from answer text and link them to source material. This function parses inline citations from Knowledge Graph responses and correlates them with their source material from the references object. Args: answer_text (str): The response text containing inline citations references (object): The references object containing files and web sources Returns: list: Array of citation objects with source text and metadata ''' # Use regex to find all citations in the format [display_text](identifier) # This pattern matches markdown-style links like [filename](citation-id) citation_pattern = r'\[([^\]]+)\]\(([^)]+)\)' citations = re.findall(citation_pattern, answer_text) citation_data = [] # Process each citation found in the answer text for display_text, identifier in citations: # Initialize citation info structure citation_info = { "display_text": display_text, # The text shown in the citation (e.g., filename) "identifier": identifier, # The unique citation ID "source_text": None, # The actual source text "source_type": None # The source type: "file" or "web" } # Search through file references to find matching citation if references and hasattr(references, 'files') and references.files: for file_ref in references.files: # Match citation ID with the 'cite' field in file references if hasattr(file_ref, 'cite') and file_ref.cite == identifier: citation_info["source_text"] = file_ref.text # Extract source text snippet citation_info["source_type"] = "file" # Mark as file source citation_info["file_id"] = file_ref.file_id # Store file ID for reference citation_info["page"] = file_ref.page # Store page number if available break # Search through web references to find matching citation if references and hasattr(references, 'web') and references.web: for web_ref in references.web: # Match citation ID with the 'url' field in web references if hasattr(web_ref, 'url') and web_ref.url == identifier: citation_info["source_text"] = web_ref.text # Extract source text snippet citation_info["source_type"] = "web" # Mark as web source citation_info["url"] = web_ref.url # Store URL for reference citation_info["title"] = web_ref.title # Store page title break citation_data.append(citation_info) return citation_data # Extract citations with their source text # This processes the response and creates a structured list of citations with their source material citations = extract_citations_with_sources(response.answer, response.references) # Display citations with source material # Loop through each citation and print its details along with the source text for citation in citations: print(f"Citation: [{citation['display_text']}]({citation['identifier']})") print(f"Source type: {citation['source_type']}") print(f"Source text: {citation['source_text']}") # Show additional metadata based on source type if citation['source_type'] == 'file': print(f"File ID: {citation['file_id']}, Page: {citation['page']}") elif citation['source_type'] == 'web': print(f"URL: {citation['url']}, Title: {citation['title']}") print("-" * 50) # Separator between citations ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the Writer client const client = new Writer(); // Query Knowledge Graph with inline citations const response = await client.graphs.question({ graph_ids: [""], question: "What are the key features of our product?", query_config: { inline_citations: true } }); function extractCitationsWithSources(answerText, references) { /** * Extract citations from answer text and link them to source material. * * This function parses inline citations from Knowledge Graph responses and correlates * them with their source material from the references object. * * @param {string} answerText - The response text containing inline citations * @param {object} references - The references object containing files and web sources * @returns {Array} Array of citation objects with source text and metadata */ // Use regex to find all citations in the format [display_text](identifier) // This pattern matches markdown-style links like [filename](citation-id) const citationPattern = /\[([^\]]+)\]\(([^)]+)\)/g; const citations = []; let match; // Process each citation found in the answer text while ((match = citationPattern.exec(answerText)) !== null) { const [fullMatch, displayText, identifier] = match; // Initialize citation info structure const citationInfo = { displayText: displayText, // The text shown in the citation (e.g., filename) identifier: identifier, // The unique citation ID sourceText: null, // The actual source text sourceType: null // The source type: "file" or "web" }; // Search through file references to find matching citation if (references?.files) { for (const fileRef of references.files) { // Match citation ID with the 'cite' field in file references if (fileRef.cite === identifier) { citationInfo.sourceText = fileRef.text; // Extract source text snippet citationInfo.sourceType = "file"; // Mark as file source citationInfo.fileId = fileRef.fileId; // Store file ID for reference citationInfo.page = fileRef.page; // Store page number if available break; } } } // Search through web references to find matching citation if (references?.web) { for (const webRef of references.web) { // Match citation ID with the 'url' field in web references if (webRef.url === identifier) { citationInfo.sourceText = webRef.text; // Extract source text snippet citationInfo.sourceType = "web"; // Mark as web source citationInfo.url = webRef.url; // Store URL for reference citationInfo.title = webRef.title; // Store page title break; } } } citations.push(citationInfo); } return citations; } // Extract citations with their source text // This processes the response and creates a structured list of citations with their source material const citations = extractCitationsWithSources(response.answer, response.references); // Display citations with source material // Loop through each citation and print its details along with the source text citations.forEach(citation => { console.log(`Citation: [${citation.displayText}](${citation.identifier})`); console.log(`Source type: ${citation.sourceType}`); console.log(`Source text: ${citation.sourceText}`); // Show additional metadata based on source type if (citation.sourceType === 'file') { console.log(`File ID: ${citation.fileId}, Page: ${citation.page}`); } else if (citation.sourceType === 'web') { console.log(`URL: ${citation.url}, Title: ${citation.title}`); } console.log("-".repeat(50)); // Separator between citations }); ``` ## Response format Knowledge Graph responses include a `references` object with `files` and `web` arrays. The `files` array contains file reference objects for file-based sources, and the `web` array contains web reference objects for web-based sources. ### File sources File sources appear in the `references.files` array. | Field | Type | Description | | - | - | - | | `text` | `string` | The actual text snippet from the source document that supports the response | | `fileId` | `string` | Unique identifier for the source file | | `score` | `number` | Internal score used during the retrieval process for ranking and selecting relevant snippets | | `page` | `integer` | Page number where the snippet was found in the source document | | `cite` | `string` | Unique identifier used in inline citations within the response text | ### Web sources Web sources appear in the `references.web` array. | Field | Type | Description | | - | - | - | | `text` | `string` | The exact text snippet from the web source that was used to support the response | | `url` | `string` | The URL of the web page where this content was found | | `title` | `string` | The title of the web page where this content was found | | `score` | `number` | Internal score used during the retrieval process for ranking and selecting relevant snippets | ## Streaming responses When using streaming responses with Knowledge Graph tools, the `references` object containing sources and citations appears in the last chunk of the stream. This means: * **Content chunks**: The response text with inline citations is streamed progressively * **Final chunk**: Contains the graph data with the complete `references` object * **Citation processing**: You need to collect all chunks and process the final one to access source text ### Stream responses with SDKs ```python Python theme={null} from writerai import Writer # Initialize the Writer client client = Writer() # Configure Knowledge Graph tool with inline citations tools = [{ "type": "graph", "function": { "description": "Search company knowledge base", "graph_ids": [""], "subqueries": True, "query_config": { "inline_citations": True } } }] messages = [{'role': 'user', 'content': 'What are the key features of our product?'}] # Stream the response stream = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto", stream=True ) # Collect streaming content and references references = None for chunk in stream: if chunk.choices[0].delta.content is not None: # Stream content progressively content = chunk.choices[0].delta.content print(content, end='', flush=True) # Check for graph data in the message if hasattr(chunk.choices[0], 'message') and chunk.choices[0].message: if hasattr(chunk.choices[0].message, 'graph_data') and chunk.choices[0].message.graph_data: # References are in the graph_data.references object references = chunk.choices[0].message.graph_data.references print("\nFile references:", references.files) print("\nWeb references:", references.web) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the Writer client const client = new Writer(); // Configure Knowledge Graph tool with inline citations const tools = [{ type: "graph", function: { description: "Search company knowledge base", graph_ids: [""], subqueries: true, query_config: { inline_citations: true } } }]; const messages = [{ role: "user", content: "What are the key features of our product?" }]; // Stream the response const stream = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, tool_choice: "auto", stream: true }); // Collect streaming content and references let references = null; for await (const chunk of stream) { if (chunk.choices[0].delta.content) { // Stream content progressively const content = chunk.choices[0].delta.content; process.stdout.write(content); } // Check for graph data in the message if (chunk.choices[0].message && chunk.choices[0].message.graph_data) { // References are in the graph_data.references object references = chunk.choices[0].message.graph_data.references; } } console.log(`\nFile references: ${references.files}`); console.log(`\nWeb references: ${references.web}`); ``` ## Next steps * Learn about [Knowledge Graph query configuration](/home/knowledge-graph-query-config) for tuning search parameters * Explore [Knowledge Graph tools](/home/kg-chat) for chat completions * Check out [direct Knowledge Graph queries](/home/kg-query) for programmatic access # Explore integrations Source: https://dev.writer.com/home/integrations-overview This guide provides an overview of Writer's integrations with popular AI frameworks and platforms. After reading this guide, you can choose the right integration for your specific use case and development needs. Writer integrates with several leading AI frameworks and cloud platforms to provide flexible deployment options and enhanced capabilities. Each integration offers unique benefits depending on your infrastructure, development preferences, and specific requirements. ## Compare integrations | Integration | Best for | Key benefits | | - | - | - | | **Amazon Bedrock** | Enterprise AWS environments | Serverless scaling, AWS ecosystem integration | | **Amazon Strands Agents** | Multi-agent AI applications | Agent orchestration, durable sessions | | **LangChain** | Complex AI workflows | Tool integration, data source connections | | **Traceloop/OpenLLMetry** | Production monitoring | Observability, debugging, performance tracking | | **Instructor** | Structured data extraction | Pydantic validation, retry mechanisms | ## Amazon Bedrock [Amazon Bedrock](https://aws.amazon.com/bedrock/) is a fully managed service for building and scaling generative AI applications. Writer's Palmyra X5 and X4 models are available on Bedrock, enabling you to use AWS's infrastructure and ecosystem to build and scale your applications. > [tab] Key benefits > > * **Serverless scaling**: automatic scaling based on demand > * **AWS ecosystem integration**: integration with other AWS services > * **Enterprise security**: built-in security and compliance features > * **Cross-region inference**: distribute traffic across multiple AWS regions > [tab] Ideal use cases > > * Large-scale enterprise applications > * AWS-native development workflows > * Applications requiring automatic scaling > * Organizations with existing AWS infrastructure > [card] Get started > > [Learn how to use Writer with Amazon Bedrock](/home/integrations/bedrock) ## Amazon Strands Agents [Amazon Strands Agents](https://strandsagents.com/latest/) is a platform for building sophisticated multi-agent AI applications that require orchestration and collaboration. Strands Agents SDK enables you to create AI applications using a model-driven approach with multiple agents working together. Writer models integrate with the Strands ecosystem. > [tab] Key benefits > > * **Multi-agent orchestration**: coordinate multiple AI agents in complex workflows > * **Durable session management**: maintain state across agent interactions > * **Asynchronous support**: handle concurrent operations efficiently > * **Model-driven approach**: define agent behavior through configuration > [tab] Ideal use cases > > * Research and content creation pipelines > * Customer service automation with multiple specialized agents > * Complex decision-making workflows > * Applications requiring agent collaboration > [card] Get started > > [Learn how to use Writer with Amazon Strands Agents](/home/integrations/strands) ## LangChain [LangChain](https://www.langchain.com/) provides a framework for developing applications powered by language models. Writer's integration allows you to use Writer's capabilities within the LangChain ecosystem alongside other tools and data sources. > [tab] Key benefits > > * **Tool integration**: connect Writer with external tools and APIs > * **Data source connections**: integrate with databases, files, and web sources > * **Chain composition**: build complex workflows with multiple components > * **Ecosystem compatibility**: works with the broader LangChain tool ecosystem > [tab] Ideal use cases > > * Research assistants with web search capabilities > * Document processing pipelines > * Custom AI applications with multiple data sources > * Applications requiring extensive tool integration > [card] Get started > > [Learn how to use Writer with LangChain](/home/integrations/langchain) ## Traceloop/OpenLLMetry [OpenLLMetry](https://openllmetry.com/) provides observability for LLM applications through OpenTelemetry-compatible tracing. It offers detailed insights into your Writer API usage, performance characteristics, and debugging capabilities. > [tab] Key benefits > > * **Comprehensive observability**: track prompts, completions, and token usage > * **OpenTelemetry compatibility**: works with any OpenTelemetry-compatible backend > * **Performance insights**: monitor latency, throughput, and error rates > * **Debugging capabilities**: trace issues across complex AI workflows > [tab] Ideal use cases > > * Production AI applications > * Applications requiring performance monitoring > * Complex AI workflows needing debugging > * Organizations with existing observability stacks > [card] Get started > > [Learn how to use Writer with OpenLLMetry](/home/integrations/openllmetry) ## Instructor [Instructor](https://github.com/instructor-ai/instructor) provides a high-level framework for getting structured outputs from language models. It offers built-in retry mechanisms, Pydantic validation, and prompt optimization specifically designed for structured data extraction. > [tab] Key benefits > > * **Structured data extraction**: convert unstructured text into validated data structures > * **Built-in retry logic**: automatic error handling and retry mechanisms > * **Pydantic validation**: type-safe data validation and parsing > * **Prompt optimization**: automatic prompt minimization and optimization > [tab] Ideal use cases > > * Data extraction from documents and text > * API response parsing and validation > * Content analysis and classification > * Data repair and cleaning workflows > [card] Get started > > [Learn how to use Writer with Instructor](/home/integrations/instructor) ## Next steps Once you've chosen an integration: 1. **Set up your development environment** with the required dependencies 2. **Follow the integration-specific guide** to implement Writer in your application 3. **Test your implementation** with sample data and workflows 4. **Deploy to production** following best practices for your chosen platform For additional help, see the [API Quickstart](/home/quickstart) or explore the [SDKs documentation](/home/sdks) for language-specific implementation details. # Invoke Palmyra models on Amazon Bedrock Source: https://dev.writer.com/home/integrations/bedrock > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. Palmyra X5 and Palmyra X4 are available on [Amazon Bedrock](https://aws.amazon.com/bedrock/). Amazon Bedrock is a fully managed service from AWS that enables developers to build and scale generative AI applications using foundation models from leading AI companies. This integration allows you to use Palmyra X5 and X4 in Amazon's serverless environment. This guide covers how to: * Install and configure the AWS CLI, which you need to connect to Bedrock * List available Writer models on Bedrock * Use the AWS `boto3` Python SDK to invoke Palmyra models on Bedrock ## Prerequisites Before interacting with Palmyra models on Bedrock, you need an [AWS account](https://aws.amazon.com/) with access to Bedrock. ## Install and configure the AWS CLI 1. [Install the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html). 2. Configure the AWS CLI with your AWS credentials. You can configure the CLI using the following command and providing your AWS account credentials: ```bash theme={null} aws configure sso ``` Alternatively, you can configure the CLI with environment variables or a credentials file. See the [AWS CLI documentation](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-quickstart.html#getting-started-quickstart-config) for more details. 3. Test that your AWS CLI is configured correctly by running the following command: ```bash theme={null} aws sts get-caller-identity ``` You should see output similar to the following: ```bash theme={null} { "UserId": "A123456789012", "Account": "123456789012", "Arn": "arn:aws:iam::123456789012:user/your-username" } ``` ## Install the AWS boto3 SDK for Python To invoke Palmyra models on Bedrock using Python, you can use the AWS `boto3` SDK. Install the `boto3` SDK using the following command: ```bash theme={null} pip install boto3 ``` ## Subscribe to Bedrock Models > [!WARNING] > > Writer Palmyra X5 and X4 models are available in Amazon Bedrock in the US West (Oregon) AWS Region with [cross-Region inference](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference.html). For the most up-to-date information on model support by Region, refer to the [Amazon Bedrock documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html). To subscribe to the Palmyra X5 and Palmyra X4 models on Bedrock, go to the [Bedrock console](https://console.aws.amazon.com/bedrock/home?region=us-west-2#/modelaccess) and request access to the Writer models you want to use. You can also list the available models from Writer using the following command: ```bash AWS CLI theme={null} aws bedrock list-foundation-models --region=us-west-2 --by-provider writer --query "modelSummaries[*].modelId" ``` ```python boto3 (Python SDK) theme={null} import boto3 bedrock = boto3.client(service_name="bedrock", region_name="us-west-2") response = bedrock.list_foundation_models(byProvider="writer") for summary in response["modelSummaries"]: print(summary["modelId"]) ``` ## Use Palmyra X5 and Palmyra X4 on with the AWS Python SDK > [!WARNING] > > Palmyra X5 and Palmyra X4 are only available in the US West (Oregon) region but can be accessed through cross-Region inference. Cross-Region inference allows you to distribute traffic across multiple AWS Regions. To learn more about cross-Region inference for Bedrock, see [Increase throughput with cross-Region inference](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference.html) and [Supported Regions and models for inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html). The following example uses the `boto3` Python SDK to create a chat completion with the Palmyra X5 model on Bedrock. The `modelId` is `us.writer.palmyra-x5-v1:0`, which is the ID for the [cross-region inference profile for Palmyra X5](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html). ```python boto3 (Python SDK) theme={null} import boto3 client = boto3.client(service_name="bedrock-runtime", region_name="us-west-2") response = client.converse( modelId="us.writer.palmyra-x5-v1:0", messages=[ { "role": "user", "content": [ { "text": "Write a one sentence product description for a cozy, stylish sweater suitable for both casual and formal occasions" } ], } ], ) print(response["output"]["message"]["content"][0]["text"]) ``` Learn more about the `converse` method in the [boto3 Python SDK documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-runtime/client/converse.html). ## Example: Summarize a meeting transcript The following example uses Palmyra X5 to summarize a meeting transcript and provide a list of action items from the transcript. It takes a meeting transcript text file, passes it to Palmyra X5 with instructions to provide a summary of the meeting and a list of action items, and prints the response. ```python boto3 (Python SDK) theme={null} import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-west-2") # Set the model ID, e.g. Palmyra X5. # This is the ID for the cross-region inference profile for Palmyra X5. # See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html. model_id = "us.writer.palmyra-x5-v1:0" transcript_file_path = "call-transcript.txt" transcript_format = "txt" # Load the document with open(transcript_file_path, "rb") as file: document_bytes = file.read() # Start a conversation with a user message and the document conversation = [ { "role": "user", "content": [ { "text": "Create a summary of the meeting notes and provide a list of action items." }, { "document": { # Available formats: html, md, pdf, doc/docx, xls/xlsx, csv, and txt "format": transcript_format, "name": "Meeting Notes", "source": {"bytes": document_bytes}, } }, ], } ] try: # Send the message to the model. response = client.converse( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 500, "temperature": 0.3}, ) # Extract and print the response text. response_text = response["output"]["message"]["content"][0]["text"] print(response_text) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1) ``` ## Additional resources See more information and examples below: * [AWS blog post](https://aws.amazon.com/blogs/aws/writer-palmyra-x5-and-x4-foundation-models-are-now-available-in-amazon-bedrock/) about Palmyra X5 and X4 on Bedrock * [Additional code examples for Amazon Bedrock](https://github.com/writer/aws-examples/tree/main/bedrock-examples) # Structured output with Instructor Source: https://dev.writer.com/home/integrations/instructor This tutorial will guide you through using Writer with [Instructor](https://useinstructor.com/), a Python library that makes it easy to get structured data like JSON from LLMs. ## Prerequisites * Python 3.8 or higher installed * [Poetry](https://pypi.org/project/poetry/) installed (see their [installation guide](https://python-poetry.org/docs/#installation)) * A Writer API key (follow the [Quickstart](/home/quickstart) to obtain an API key) ## Getting started To get started with Instructor, you'll need to install the library and set up your environment. **1. Obtain an API key** First, make sure that you've signed up for a Writer Control Center account and obtained an API key. You can follow the [Quickstart](/home/quickstart) to obtain an API key. **2. Install instructor** Once you've done so, install `instructor` with Writer support by running: ```bash theme={null} pip install instructor[writer] ``` **3. Set the `WRITER_API_KEY` environment variable** Make sure to set the `WRITER_API_KEY` environment variable with your Writer API key or pass it as an argument to the Writer constructor. ## Basic usage Following is a simple example of how to use `instructor` with Writer: ```python theme={null} import instructor from writerai import Writer from pydantic import BaseModel # Initialize Writer client client = instructor.from_writer(Writer(api_key="your API key")) class User(BaseModel): name: str age: int # Extract structured data user = client.chat.completions.create( model="palmyra-x5", messages=[{"role": "user", "content": "Extract: John is 30 years old"}], response_model=User, ) print(user) #> name='John' age=30 ``` This code creates a simple data model with two fields: `name` and `age`. It then uses the `instructor.from_writer` function to create a `client` object that uses the Writer API to extract structured data from a text. ## Instructor modes Instructor supports two modes for structured output with Writer: * [JSON mode](#json-mode): Returns a response that strictly follows the provided JSON schema. * [Tools mode](#tools-mode): Returns a structured response using the `tool_calls` field, where it populates the defined tool and its arguments based on the input. Both modes use the [Writer chat completion endpoint](/api-reference/completion-api/chat-completion) to generate structured outputs. The key difference lies in how the model returns the data: either as a raw JSON object or via a structured tool call. ### JSON mode JSON mode uses Writer's native JSON schema support. When you use this mode: * Instructor converts your Pydantic model into a JSON schema and passes it as the `response_format` parameter * The model generates a response that strictly follows the provided JSON schema * Instructor then parses the JSON response and validates it against your original Pydantic model > [!TIP] > > For more details on structured outputs and JSON schema usage, see our [structured output documentation](/home/structured-output). ### Tools mode Tools mode uses Writer's tool calling capabilities. When you use this mode: * Instructor converts your Pydantic model into a tool definition * Instructor adds this tool definition to the API call using the `tools` parameter * The model returns a structured response using the `tool_calls` field, where it populates the defined tool and its arguments based on the input * Instructor extracts the arguments from the `tool_calls` field and validates them against the original Pydantic model > [!TIP] > > For more details on tool calling, see our [tool calling documentation](/home/tool-calling). ### Specifying the mode You can specify which mode to use when initializing the Instructor client: ```python theme={null} import instructor from writerai import Writer # Use JSON mode client = instructor.from_writer( Writer(api_key="your API key"), mode=instructor.Mode.WRITER_JSON ) # Use Tools mode client = instructor.from_writer( Writer(api_key="your API key"), mode=instructor.Mode.WRITER_TOOLS ) ``` If you don't specify a mode, Instructor will use `WRITER_TOOLS` by default. ## Instructor vs. Writer SDK When working with structured outputs, you can choose between two main approaches: using Instructor, a high-level framework built on top of LLM providers, or using the Writer SDK directly, which offers low-level access to the Writer LLMs. Each option comes with its own strengths and trade-offs, depending on your goals and level of control needed. | Feature | Instructor | Writer SDK | | - | - | - | | **Retry mechanism** | Built-in retry logic with error handling and prompt editing | Manual implementation required | | **Schema handling** | Auto-converts a wide range of Python types into JSON Schema via Pydantic | Manual schema conversion required | | **Validation & reliability** | Enhanced outcomes through Pydantic validation + retries | Same results possible with manual implementation | | **Prompt optimization** | Built-in prompt minimization and optimization | Manual prompt engineering required | | **Model access** | Limited to supported models (currently V4 + Tool Calls) | Full access to latest models (V4, V5) and all output modes | | **Update speed** | Requires updates/contributions for new features | Immediate support for latest Palmyra features | For more on Instructor’s advanced retry and error handling capabilities, see the [official Instructor retrying guide](https://python.useinstructor.com/concepts/retrying/). ## Building a data repair tool with Instructor and Writer You can also use Instructor to do advanced data extraction and repair. In this example, you'll build a Python application that extracts structured data from text, CSV, and PDF files using Instructor and Writer. This application will: * Parse text, CSV, and PDF files * Extract and validate structured data using Instructor and Writer * Output the results in CSV format The finished code for this tutorial is available in the [API tutorials](https://github.com/writer/api-tutorials/tree/main/instructor-and-writer-tutorial) GitHub repository. ### Setting up the project **1. Create a new project** First, create a new project and set up Poetry for dependency management: ```bash theme={null} mkdir instructor-and-writer-tutorial cd instructor-and-writer-tutorial poetry init -y ``` **2. Add dependencies** Add the required dependencies to your project: ```bash theme={null} poetry add instructor writer-sdk python-dotenv pydantic ``` **3. Set up your environment variables** Create a `.env` file in your project root and add your Writer API key: ``` WRITER_API_KEY=your_api_key_here ``` **4. Create `main.py` file and add imports** Create a `main.py` file and add the following imports: ```python theme={null} import asyncio import csv import json import os from typing import Annotated, Type, Iterable, List import instructor from dotenv import load_dotenv from pydantic import BaseModel, AfterValidator, Field from writerai import Writer, AsyncWriter load_dotenv() ``` Here's what each import is used for: * `asyncio`: This is used to run the application on multiple files concurrently. * `csv`: This is used to write the extracted data to a CSV file. * `json`: This is used to write the extracted data to a JSON file. * `os`: This is used to read the files. * `instructor`: The `instructor` library is used for structured output. * `writerai`: This is the Writer Python SDK, which is used to interact with the Writer API. * `typing` and `pydantic`: These modules are used to define the types for fields in the `UserExtract` class defined in the next step. * `dotenv`: The `dotenv` module is used to load the `.env` file that contains your Writer API key. **5. Setting up Writer client** Initialize the Writer client for both synchronous and asynchronous operations: ```python theme={null} writer_client = Writer() async_writer_client = AsyncWriter() ``` ### Defining the data model In order for Instructor to extract structured output, you need to define a data model using Pydantic. To define the data model, create a `UserExtract` class to represent the data you want to extract: ```python theme={null} class UserExtract(BaseModel): @staticmethod def first_last_name_validator(v): if v[0] != v[0].upper() or v[1:] != v[1:].lower() or not v.isalpha(): raise ValueError("Name must contain only letters and start with uppercase letter") return v first_name: Annotated[str, AfterValidator(first_last_name_validator)] = Field( ..., description="The name of the user" ) last_name: Annotated[str, AfterValidator(first_last_name_validator)] = Field( ..., description="The surname of the user" ) email: str ``` This data model defines the fields that you want to extract from the files. The `first_name` and `last_name` fields are validated to ensure they start with an uppercase letter and contain only letters. In this example, the `email` field is a simple string field, though you could also use a Pydantic field to validate the email format. ### Parsing the files With the data model defined, you can now implement file parsing. This involves creating functions to open the files and extract the text. **1. Create a function to handle file processing** Implement the main file handler function that orchestrates the entire process: ```python theme={null} async def handle_file(file_path: str, response_model: Type[BaseModel], output_path: str = None) -> None: extension = os.path.splitext(file_path)[1] name = os.path.splitext(os.path.basename(file_path))[0] file_text = await fetch_file_text(file_path, name, extension) repaired_entities = await repair_data(file_text, response_model) print(f"Number of entities extracted from {name}{extension}: {len(repaired_entities)}") return generate_csv(repaired_entities, response_model, output_path) ``` This function handles the file processing logic, including file type validation, text extraction, data repair, and CSV generation. **2. Create a function to read the files** Next, create a function to read the files based on the given path and extension: ```python theme={null} async def fetch_file_text(file_path: str, name: str, extension: str) -> str: allowed_extensions = [".txt", ".csv", ".pdf"] if extension not in allowed_extensions: raise ValueError(f"File extension {extension} is not allowed. Only {', '.join(allowed_extensions)}") print(f"Reading {name}{extension} content...") with open(file_path, 'rb') as file: file_contents = file.read() return await parse_file(file_contents, name, extension) ``` **3. Extract the file content** Next, create a function to extract the text from the files. For text files, this function simply reads the file contents. For PDFs, the function uploads the PDF using Writer's [file upload endpoint](/api-reference/file-api/upload-files), parses the text using [PDF parsing tool](/api-reference/tool-api/pdf-parser), and then deletes the file from Writer's servers using the [file delete endpoint](/api-reference/file-api/delete-file): ```python theme={null} async def parse_file(file_bytes_content: bytes, name: str, extension: str) -> str: file_text = "" if extension == ".pdf": print(f"Uploading {name}{extension} content to writer servers...") file = await async_writer_client.files.upload( content=file_bytes_content, content_disposition=f"attachment; filename={name + extension}", content_type="application/octet-stream", ) print(f"Converting {name}{extension} content from PDF to text...") file_text = await async_writer_client.tools.parse_pdf( file_id=file.id, format="text", ) print(f"Deleting {name}{extension} from writer servers...") await async_writer_client.files.delete(file.id) else: print(f"Converting {name}{extension} content...") file_text = file_bytes_content.decode("utf-8") return file_text ``` ### Extracting and repairing the data With the file content extracted, you can now implement data extraction and repair using Instructor and Writer. **1. Create a function to repair the data** Create a function to extract and repair data using Instructor: ```python theme={null} async def repair_data(file_text: str, response_model: Type[BaseModel]) -> List[BaseModel]: instructor_client = instructor.from_writer(client=async_writer_client) if not issubclass(response_model, BaseModel): raise ValueError("Response model must be subclass of pydantic BaseModel") print("Extracting data featuring Instructor tools...") return await instructor_client.chat.completions.create( model="palmyra-x5", response_model=Iterable[response_model], max_retries=5, messages=[ {"role": "user", "content": f"Extract entities from {file_text}"}, ], ) ``` **2. Implementing CSV generation** Add a function to save the extracted data to CSV: ```python theme={null} def generate_csv(entities: List[BaseModel], response_model: Type[BaseModel], output_path: str = None) -> None: fieldnames = list(response_model.model_json_schema()["properties"].keys()) file_path = f"{response_model.__name__}.csv" if output_path: file_path = output_path + file_path os.makedirs(os.path.dirname(file_path), exist_ok=True) with open(file_path, "w") as file: dict_writer = csv.DictWriter(file, fieldnames=fieldnames) dict_writer.writeheader() for entity in entities: dict_writer.writerow(json.loads(response_model(**entity.model_dump()).model_dump_json())) ``` ### Creating the main handler Finally, implement the main function to process multiple files concurrently: ```python theme={null} async def main(): data = [ ("example_data/ExampleFileTextFormat.txt", UserExtract, None), ("example_data/ExampleFilePDFFormat.pdf", UserExtract, "out/"), ] tasks = [] for row in data: tasks.append(handle_file(row[0], row[1], row[2])) await asyncio.gather(*tasks) if __name__ == "__main__": asyncio.run(main()) ``` In this example, the input paths are hardcoded, but you could modify the application to accept input paths from the command line or a web interface, or read from a directory or database. ### Testing the application Your data repair tool is now ready to use. To test it, follow these steps: **1. Create an `example_data` directory** Create an `example_data` directory and add some test files: * A text file with user information * A PDF file with user information You can use the [example data](https://github.com/writer/api-tutorials/tree/main/instructor-and-writer-tutorial/example_data) provided in the GitHub repository for this tutorial. If you provide your own, be sure to update the `main.py` file to point to the new files. **2. Run the application** Run the application: ```bash theme={null} poetry run python main.py ``` The application will process both files concurrently and generate CSV files containing the extracted user information. ## Conclusion You've now seen basic and advanced usage of Writer with Instructor. To learn more about Instructor, check out the [Instructor documentation](https://python.useinstructor.com/). Structured output is a powerful feature that can help you build more accurate and reliable applications, especially combined with [tool calling](/home/tool-calling). # Using Writer with LangChain Source: https://dev.writer.com/home/integrations/langchain The [Writer LangChain integration](https://github.com/writer/langchain-writer) allows you to leverage Writer's capabilities within the LangChain ecosystem, making it easy to build sophisticated AI applications. In this tutorial, you'll explore each component of the integration and understand how they work. ## Prerequisites Before you begin, make sure you have: * Python 3.9 or higher installed * A [Writer Control Center](https://app.writer.com/register) account * A Writer API key. See instructions in the [API Quickstart](/home/quickstart). * Basic familiarity with Python and [LangChain concepts](https://python.langchain.com/docs/concepts/) ## Installation and setup First, install the necessary packages: ```bash theme={null} pip install langchain-writer python-dotenv ``` Next, create a `.env` file with `WRITER_API_KEY` set to your Writer API key: ``` WRITER_API_KEY= ``` ## Components of the Writer LangChain integration The `langchain-writer` package provides several key components: 1. `ChatWriter` for text generation 2. Tool calling capabilities, including: * `GraphTool` for Knowledge Graph integration * `NoCodeAppTool` for no-code applications * `LLMTool` for model delegation 3. Additional tools like `PDFParser` for parsing PDFs ## ChatWriter `ChatWriter` is a LangChain chat model that provides access to Writer's AI capabilities for text generation. It supports streaming, non-streaming, batching, and asynchronous operations. You can use any of the [Palmyra chat models](/home/models) available in Control Center. See the [full documentation](https://github.com/writer/langchain-writer/blob/main/docs/chat_writer.md#parameters) for `ChatWriter` to learn more about the available parameters. ### Usage This example uses `ChatWriter` to ask the Palmyra X5 model to explain what LangChain is in plain terms. ```python theme={null} from langchain_writer import ChatWriter from dotenv import load_dotenv load_dotenv() # Initialize the chat model # These are optional parameters with default values listed here chat = ChatWriter( model="palmyra-x5", # default model temperature=0.7, # controls randomness (0-1) max_tokens=None, # maximum number of tokens to generate timeout=None, # request timeout max_retries=2 # number of retries on failure ) # Generate a response response = chat.invoke("Explain what LangChain is in simple terms.") print(response.content) ``` ### Streaming Streaming allows you to receive the generated text in chunks as it's being produced. This example shows how to stream a response from the Palmyra X5 model using synchronous streaming: ```python theme={null} from langchain_writer import ChatWriter import asyncio from dotenv import load_dotenv load_dotenv() chat = ChatWriter() # Streaming (synchronous) for chunk in chat.stream("Write a short poem about artificial intelligence."): print(chunk.content, end="") ``` You can also use asynchronous streaming with the `async for` loop and the `astream` method: ```python theme={null} from langchain_writer import ChatWriter import asyncio from dotenv import load_dotenv load_dotenv() chat = ChatWriter() # Streaming (asynchronous) async def async_stream(): async for chunk in chat.astream("Write a short poem about artificial intelligence."): print(chunk.content, end="") asyncio.run(async_stream()) ``` ### Batch processing You can batch process multiple prompts for efficient processing. The following example batches three individual LLM invocations and runs them in parallel: ```python theme={null} from langchain_writer import ChatWriter from dotenv import load_dotenv load_dotenv() chat = ChatWriter() questions = [ "What is a three-sentence definition of retrieval-augmented generation?", "When did transformer architecture first appear in the literature?", "What are 3 benefits of using AI to assist in software development?" ] # Process multiple prompts in parallel responses = chat.batch(questions) for question, response in zip(questions, responses): print(f"Q: {question}") print(f"A: {response.content}\n") ``` Note that `batch` returns results in the same order as the inputs. You can use `batch_as_completed` to return results as they complete. Results may arrive out of order, but each includes the input index for matching. You can also optionally set the `max_concurrency` parameter to control the number of concurrent requests, which can be useful when you want to limit the number of parallel calls to prevent overloading a server or API: ```python theme={null} responses = chat.batch(questions, config={"max_concurrency": 2} ) ``` See the LangChain documentation on [parallel execution](https://python.langchain.com/docs/concepts/runnables/#optimized-parallel-execution-batch) for more information. ## Tool calling `ChatWriter` supports tool calling, which allows the model to use external functions to enhance its capabilities. Tool calling is available with Palmyra X4 and later. > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. ### Tool calling basics To use tool calling, follow these steps: 1. Define a function that will be called by the model and decorate it with the `@tool` decorator. 2. Bind the tool to the chat model using the `bind_tools` method. 3. Use the tool in a chat and append the response to the messages list. 4. Execute the tool call with the arguments given by the model and append the response to the messages list. 5. Invoke the chat model with the updated messages list to receive the final response. Here's an example of how to use tool calling: ```python theme={null} from langchain_writer import ChatWriter from langchain_core.tools import tool from langchain_core.messages import HumanMessage from dotenv import load_dotenv load_dotenv() @tool def get_weather(location: str) -> str: """Get the current weather for a location.""" # In a real application, you would call a weather API here return f"The weather in {location} is sunny and 75°F" chat = ChatWriter() chat_with_tools = chat.bind_tools([get_weather]) messages = [ HumanMessage( "What's the weather like in San Francisco?" ) ] response = chat_with_tools.invoke(messages) messages.append(response) for tool_call in response.tool_calls: selected_tool = { "get_weather": get_weather, }[tool_call["name"].lower()] tool_msg = selected_tool.invoke(tool_call) messages.append(tool_msg) response = chat_with_tools.invoke(messages) print(response.content) ``` ### GraphTool `GraphTool` is a LangChain tool that allows you to retrieve information from a Knowledge Graph to enhance its responses. The tool executes remotely, so you simply need to provide the IDs of the Knowledge Graph you want to use. For more details on the built-in Knowledge Graph chat tool in Writer, see the [Knowledge Graph chat support guide](/home/kg-chat). #### Usage ```python theme={null} from langchain_writer import ChatWriter from langchain_writer.tools import GraphTool from dotenv import load_dotenv load_dotenv() # Initialize the chat model chat = ChatWriter() # Create a graph tool with your knowledge graph ID graph_tool = GraphTool(graph_ids=["your-knowledge-graph-id"]) # Bind the tool to the chat model chat_with_tools = chat.bind_tools([graph_tool]) # Ask a question that can be answered using the knowledge graph response = chat_with_tools.invoke("What information do you have about product X?") print(response.content) ``` ### NoCodeAppTool `NoCodeAppTool` is a specialized tool that enables access to Writer's no-code applications as LLM tools. This tool allows language models to interact with pre-built applications to enhance their responses. The tool is designed as a standard "function" type tool and requires manual execution. Unlike the `GraphTool` and `LLMTool` which are executed remotely by Writer's servers, you'll need to handle the execution of the `NoCodeAppTool` in your code. When initializing the tool, you must provide an `app_id` (either directly or using an environment variable) that corresponds to a no-code application created in your Writer account. The tool automatically retrieves the input parameters for the app during initialization, so you don't need to specify them manually. You can customize the tool's name (default is "No-code application") and description (default is "No-code application powered by Palmyra") to provide better context to the model. The API key is typically read from environment variables but can also be provided directly. When working with the tool, remember that all required inputs must be provided when invoking it, or a `ValueError` will be raised. Input values can be either strings or lists of strings, depending on what the no-code application expects. This tool is particularly useful for generating content, performing specialized data transformations, creating custom outputs based on user inputs, integrating with domain-specific applications, enhancing responses with formatted content, or leveraging pre-built applications for common tasks. #### Usage Here's an example of how to use the `NoCodeAppTool`: ```python theme={null} from langchain_writer import ChatWriter from langchain_writer.tools import NoCodeAppTool from langchain_core.messages import HumanMessage import os from dotenv import load_dotenv load_dotenv() chat = ChatWriter() # Create a NoCodeAppTool app_tool = NoCodeAppTool( app_id=os.getenv("APP_ID"), name="Social post generator", description="No-code app that generates social posts from product descriptions" ) # Bind the tool ChatWriter chat_with_tools = chat.bind_tools([app_tool]) product_description = "The Terra running shoe is a high-performance, lightweight shoe that offers a comfortable and durable experience. The shoe is also lightweight and easy to carry, making it an ideal option for runners looking for a new pair of shoes." # Create a conversation messages = [ HumanMessage("Can you help me generate a social post about a new running shoe? Here is the product description:\n\n" + product_description) ] # Get the model's response response = chat_with_tools.invoke(messages) messages.append(response) # If the model requests to use the tool if response.tool_calls: for tool_call in response.tool_calls: print("\nTool call:", tool_call) # Dynamically build the inputs dictionary from the args inputs = {} for arg in tool_call['args']: inputs[arg] = tool_call['args'][arg] # Execute the tool call try: tool_response = app_tool.run(tool_input={"inputs": inputs}) messages.append(tool_response.suggestion) except Exception as e: print(f"Error running tool: {e}") # Get the final response try: final_response = chat_with_tools.invoke(messages) print("\nFinal response:", final_response.content) except Exception as e: print(f"Error getting final response: {e}") else: print("No tool calls were requested.") ``` When providing inputs to the tool, you'll need to format them as a dictionary: ```python theme={null} # Example of providing inputs to the tool inputs = { "Input name": "Input value", "Another input name": ["List", "of", "string", "values"] } # Invoke the tool with the inputs result = app_tool.run(tool_input={"inputs": inputs}) ``` ### LLMTool `LLMTool` is a specialized tool that enables delegation to another model. This tool allows a primary model to delegate calls to a different model—including [external models](/home/external-models) configured for your organization—to enhance its responses. Unlike most LangChain tools that use the standard "function" type, the `LLMTool` has a type of `llm` and is designed specifically for use within the Writer environment. Due to its remote execution nature, this tool doesn't support direct invocation through the `_run` method—attempting to call this method will raise a `NotImplementedError`. When initializing the tool, you specify which model to delegate to using the `model_name` parameter. This can be a Palmyra model like `palmyra-x5` or an [external model](/home/external-models) configured for your organization. The default model is `palmyra-x5`. The `description` parameter plays a crucial role in helping the model understand when to use this tool. When the model uses the LLM tool, the execution happens remotely on Writer's servers, and the response includes additional data in the `additional_kwargs["llm_data"]` field that you can access in your application. This tool is valuable when you want to delegate a focused task to another model. #### Usage Here's an example of how to use the `LLMTool`: ```python theme={null} from langchain_writer import ChatWriter from langchain_writer.tools import LLMTool from dotenv import load_dotenv load_dotenv() chat = ChatWriter() # Create an LLMTool that delegates coding tasks to a model specialized in code generation llm_tool = LLMTool( model_name="anthropic.claude-3-sonnet-20240229-v1:0", description="A function that invokes a model specialized in writing and debugging code. Use this tool for any request that involves generating, explaining, or fixing code." ) # Bind the tool to the ChatWriter chat_with_tools = chat.bind_tools([llm_tool]) # The primary model delegates the coding request to the specialized model response = chat_with_tools.invoke([ ("system", "You are a helpful assistant. Delegate coding tasks to the code generation tool."), ("human", "Write a Python function that returns the nth Fibonacci number using memoization.") ]) print(response.content) # The LLM data is available in the response print(response.additional_kwargs["llm_data"]) ``` ## Additional tools ### PDFParser `PDFParser` is a document loader that uses Writer's PDF parsing capabilities to extract text from PDF documents. It converts PDFs into LangChain Document objects that can be used in your applications. For more details on the underlying API, see the [PDF parser API reference](/api-reference/tool-api/pdf-parser). #### Usage Here's an example of how to use the `PDFParser`: ```python theme={null} from langchain_writer import PDFParser from langchain_core.documents.base import Blob from dotenv import load_dotenv load_dotenv() # Initialize the PDF parser with the desired output format parser = PDFParser(output_format="markdown") # Options: "text", "markdown" # Load a PDF file file = Blob.from_path("path/to/your/document.pdf") parsed_pages = parser.parse(blob=file) print(parsed_pages) ``` #### Output formats The `PDFParser` supports different output formats: * `text`: Plain text extraction * `markdown`: Structured markdown with preserved formatting ```python theme={null} # For markdown output markdown_parser = PDFParser(output_format="markdown") markdown_docs = markdown_parser.load("path/to/your/document.pdf") ``` ## Conclusion In this tutorial, you've explored the LangChain integration with Writer, covering each of its components: 1. `ChatWriter` for text generation 2. Tool calling capabilities, including: * `GraphTool` for Knowledge Graph integration * `NoCodeAppTool` for no-code applications * `LLMTool` for model delegation 3. Additional tools like `PDFParser` for parsing PDFs This integration provides a foundation for building AI applications with Writer and LangChain. Check out the package [README](https://github.com/writer/langchain-writer) and [documentation](https://github.com/writer/langchain-writer/tree/main/docs), as well as the [LangChain Documentation](https://python.langchain.com/docs/) for more information on how to use LangChain with Writer. # Using Writer with OpenLLMetry Source: https://dev.writer.com/home/integrations/openllmetry Monitor and debug Writer API calls with OpenLLMetry. Export traces to Jaeger, Datadog, New Relic, or Traceloop for LLM observability. This guide shows you how to integrate Writer with [OpenLLMetry](https://www.traceloop.com/openllmetry) for monitoring and debugging your LLM applications. After completing these steps, you can trace and observe your Writer API calls alongside other LLM operations in your observability stack. ![Traceloop dashboard showing Writer integration with OpenLLMetry](https://mintcdn.com/writer/BNRiJTjyBT4r8fSv/images/home/traceloop-dashboard.png?fit=max\&auto=format\&n=BNRiJTjyBT4r8fSv\&q=85\&s=fa60278c3249c46ace6e9eddaa29254e) ## What is OpenLLMetry? OpenLLMetry is an open source project that enables monitoring and debugging of LLM application execution. It provides non-intrusive tracing built on top of OpenTelemetry, allowing you to export traces to your existing observability stack. Since it's built on [OpenTelemetry](https://opentelemetry.io/), you can use any OpenTelemetry compatible backend (Jaeger, Zipkin, Datadog, New Relic, etc.) or the hosted Traceloop platform. ## What you get with the Writer integration The Writer integration with OpenLLMetry provides enhanced observability beyond standard OpenTelemetry traces. You'll see detailed information about your Writer API calls as additional span attributes: * **`gen_ai.request.model`**: the model requested (for example, `palmyra-x5`) * **`gen_ai.prompt`**: array of prompts sent to the Writer model * **`gen_ai.completion`**: array of completions returned from Writer * **`gen_ai.usage.total_tokens`**: total tokens used * **`gen_ai.usage.prompt_tokens`**: number of tokens used for prompts * **`gen_ai.usage.completion_tokens`**: number of tokens used for completions This gives you comprehensive visibility into your Writer API usage, including prompt engineering insights, token consumption patterns, and performance characteristics that aren't available in standard OpenTelemetry traces. > [!NOTE] > > For a complete list of supported attributes, see the full [GenAI Semantic Conventions](https://www.traceloop.com/docs/openllmetry/contributing/semantic-conventions). ## Prerequisites Before you begin, make sure you have: * Python 3.11 or higher installed * A [Writer Control Center](https://app.writer.com/register) account * A [Traceloop](https://auth.traceloop.com/en/login) account * A Writer API key. See instructions in the [API Quickstart](/home/quickstart) * Basic familiarity with Python and [OpenLLMetry concepts](https://www.traceloop.com/docs/openllmetry/introduction) > [!NOTE] > > The example below uses **Traceloop** as the observability provider. See the [connect to an external provider](#connect-to-external-providers) section to learn how to connect to other providers. ## Configuration details | Environment Variable | Required | Default | Description | | - | - | - | - | | `WRITER_API_KEY` | **Required** | None | Writer API key for authenticating API calls. Must be set for the application to function. | | `TRACELOOP_API_KEY` | **Conditional** | None | **Required for Traceloop Cloud**: Create an API key in your [Traceloop dashboard](https://app.traceloop.com/settings/api-keys) and set this environment variable. **Optional for external providers**: When connecting to other observability platforms (Datadog, New Relic, etc.), omit this variable and use `TRACELOOP_HEADERS` instead. | | `TRACELOOP_BASE_URL` | Optional | `https://api.traceloop.com` | OpenTelemetry endpoint to connect to. If prefixed with `http`/`https`, uses [OTLP/HTTP protocol; otherwise uses OTLP/GRPC](https://opentelemetry.io/docs/specs/otel/protocol/exporter/). The SDK appends `/v1/traces`. | | `TRACELOOP_HEADERS` | Optional | None | [Custom HTTP headers for authentication](https://www.traceloop.com/docs/openllmetry/configuration#headers). If set, API key is ignored. | | `TRACELOOP_TRACE_CONTENT` | Optional | `true` | [Enable/disable logging of prompts, completions, and embeddings to span attributes](https://www.traceloop.com/docs/openllmetry/privacy/traces#disabling-logging-globally). | | `TRACELOOP_TELEMETRY` | Optional | `true` | [Enable/disable anonymous telemetry data collection](https://www.traceloop.com/docs/openllmetry/configuration#control-telemetry). | > [!NOTE] > > For additional configuration option details, see the [SDK initialization docs](https://www.traceloop.com/docs/openllmetry/configuration). ## Integrate Writer with OpenLLMetry ### 1. Install the SDK Install OpenLLMetry in your Python environment: ```bash theme={null} pip install traceloop-sdk ``` ### 2. Initialize and configure In your Writer application, initialize the Traceloop tracer. For local development, you may want to disable batch sending to see traces immediately. ```python theme={null} import os from traceloop.sdk import Traceloop from writerai import Writer # Initialize Traceloop for Writer monitoring Traceloop.init( app_name="YOUR_APP_NAME", api_key=os.environ.get("TRACELOOP_API_KEY"), # disable_batch=True # For local development, this disables batch sending so you can see Writer API traces immediately ) # Initialize Writer client client = Writer(api_key=os.environ.get("WRITER_API_KEY")) ``` ### 3. (Optional) annotate your workflows [Workflow annotations](https://www.traceloop.com/docs/openllmetry/tracing/annotations) help organize and group related operations for better trace visualization and debugging. **When to use decorators:** * **Complex processes**: Group related API calls and business logic into logical workflows * **Custom naming**: Override automatic span naming with business-context names * **Hierarchical tracing**: Create parent-child relationships between workflows and tasks **Available decorators:** | Decorator | Purpose | Use case | | - | - | - | | `@workflow` | Multi-step processes or "chains" | Complete business workflows that can be traced as a single unit | | `@task` | Individual operations within workflows | Specific actions or computations within a workflow | | `@agent` | Autonomous agents | AI agents that can make decisions and use tools | | `@tool` | Agent tools | Functions that agents can call to perform specific actions | > [!NOTE] > > Workflow annotations are **optional**. OpenLLMetry traces Writer API calls automatically without needing any decorators or additional code. ```python theme={null} from traceloop.sdk.decorators import workflow, task, agent, tool # Workflow and task example @workflow(name="content_creation") def content_creation_pipeline(topic: str): research = research_topic(topic) content = generate_content(research) return content @task(name="research_topic") def research_topic(topic: str): completion = client.chat.completions.create( model="palmyra-x5", messages=[{"role": "user", "content": f"Provide a comprehensive overview of {topic}, including key concepts, benefits, and current trends."}], max_tokens=300 ) return completion.choices[0].message.content @task(name="generate_content") def generate_content(research: str): completion = client.chat.completions.create( model="palmyra-x5", messages=[{"role": "user", "content": f"Write an engaging article based on this research: {research}"}], max_tokens=500 ) return completion.choices[0].message.content # Agent and tool example @agent(name="content_agent") def content_agent(request: str): return research_tool(request) @tool(name="research_tool") def research_tool(query: str): completion = client.chat.completions.create( model="palmyra-x5", messages=[{"role": "user", "content": f"Find detailed information about {query} and provide key insights and data points."}], max_tokens=300 ) return completion.choices[0].message.content ``` ## Connect to external providers Because the Traceloop SDK is built on OpenTelemetry, the data it generates can be used in any observability platform that supports the OpenTelemetry standard. OpenLLMetry extends this by using the OTLP protocol to connect with external observability providers, letting you send traces directly to your existing stack without relying on Traceloop’s hosted platform. ### Configure external provider connection To connect to an external provider, configure the following environment variables: | Environment Variable | Description | | - | - | | `TRACELOOP_BASE_URL` | The OTLP endpoint URL for your observability provider | | `TRACELOOP_HEADERS` | Authentication headers (if required by your provider) | ### Example configurations #### [Grafana Cloud](https://www.traceloop.com/docs/openllmetry/integrations/grafana#without-grafana-agent) ```bash theme={null} # Generate base64 encoded credentials echo -n ":" | base64 # Set environment variables export TRACELOOP_BASE_URL=https://otlp-gateway-.grafana.net/otlp export TRACELOOP_HEADERS="Authorization=Basic%20" ``` #### [Datadog](https://www.traceloop.com/docs/openllmetry/integrations/datadog) ```bash theme={null} # Connect to your Datadog Agent (requires OTLP HTTP collector enabled) export TRACELOOP_BASE_URL="http://:4318" ``` #### [New Relic](https://www.traceloop.com/docs/openllmetry/integrations/newrelic) ```bash theme={null} export TRACELOOP_BASE_URL=https://otlp.nr-data.net:443 export TRACELOOP_HEADERS="api-key=" ``` > [!NOTE] > > For a complete list of supported integrations, see the full [OpenLLMetry integrations catalog](https://www.traceloop.com/docs/openllmetry/integrations/introduction#the-integrations-catalog). ## Next steps Now that you've set up Writer with OpenLLMetry, you can start monitoring your LLM applications. See the following resources to help you get the most out of your integration: * Explore [OpenLLMetry's advanced features](https://docs.traceloop.com/docs/openllmetry/tracing) for more detailed tracing capabilities * Learn about [workflow annotations](https://docs.traceloop.com/docs/openllmetry/tracing/workflow-annotations) to better organize your traces * Set up [custom integrations](https://docs.traceloop.com/docs/openllmetry/integrations) with your existing observability stack * Review the [Writer OpenLLMetry integration](https://github.com/traceloop/openllmetry/tree/main/packages/opentelemetry-instrumentation-writer) for additional details and examples # Using Writer with AWS Strands Agents Source: https://dev.writer.com/home/integrations/strands > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. Writer's models are available on [AWS Strands Agents](https://strandsagents.com/latest/). Strands Agents SDK from AWS is an open-source framework that enables developers to build and deploy AI agents using a model-driven approach. This integration allows you to use Writer models within the Strands agent ecosystem, from local development to production deployment. ## Available models Writer offers several specialized Palmyra models: | Model | Model ID (Writer API) | Model ID (Bedrock) | Context Window | Availability | Description | | - | - | - | - | - | - | | Palmyra X5 | `palmyra-x5` | `us.writer.palmyra-x5-v1:0` | 1M tokens | [Writer API](#writer-api-configuration) or [Amazon Bedrock](#amazon-bedrock-configuration) | Latest model with 1 million token context for complex workflows, supports vision and multi-content | | Palmyra X4 | `palmyra-x4` | `us.writer.palmyra-x4-v1:0` | 128k tokens | [Writer API](#writer-api-configuration) or [Amazon Bedrock](#amazon-bedrock-configuration) | Advanced model for workflow automation and tool calling | See the [Writer models guide](/home/models) for more details and use cases. > [!NOTE] > > The above Bedrock models IDs for Palmyra X5 and Palmyra X4 are using [cross-region inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html). Check which AWS Regions support Writer models before selecting an inference profile. ## Prerequisites Before you begin, make sure you have: * Python 3.10 or higher installed * Basic familiarity with Python and [AWS Strands](https://strandsagents.com/latest/) ## Writer API configuration ### Prerequisites Before you configure the WRITER API client for Strands Agent SDK, make sure you have: * A [Writer Control Center](https://app.writer.com/register) account * A Writer API key. See instructions in the [API Quickstart](/home/quickstart) ### Installation To use Writer models with Strands Agents, install the optional Writer dependency: ```bash theme={null} pip install 'strands-agents[writer]' ``` > [!NOTE] > > To follow along with the examples in this guide, you'll also need the [Strands Agent Tools package](https://github.com/strands-agents/tools). Install the package with `pip install strands-agents-tools`. ### Client configuration You can pass additional arguments to the Writer client via `client_args`: ```python theme={null} model = WriterModel( client_args={ "api_key": "", "timeout": 30, "base_url": "https://api.writer.com/v1", # Additional client configuration options }, model_id="palmyra-x5" ) ``` ### Environment variables You can set your Writer API key as an environment variable instead of passing it directly: ```bash theme={null} export WRITER_API_KEY="your_api_key_here" ``` Then initialize the model without the `client_args["api_key"]` parameter: ```python theme={null} model = WriterModel(model_id="palmyra-x5") ``` ### Usage After installing, you can import and initialize the Writer provider in Strands Agents: ```python theme={null} from strands import Agent from strands.models.writer import WriterModel from strands_tools import calculator model = WriterModel( client_args={"api_key": ""}, model_id="palmyra-x5", ) agent = Agent(model=model, tools=[calculator]) response = agent("What is 2+2") print(response) ``` > [!NOTE] > > By default, Strands Agents use a `PrintingCallbackHandler` that streams responses to `stdout` as they're generated. When you call `agent("What is 2+2")`, you'll see the response appear in real-time as it's being generated. The `print(response)` above also shows the final collected result after the response is complete. See [Callback Handlers](https://strandsagents.com/latest/documentation/docs/user-guide/concepts/streaming/callback-handlers/?h=callback) in the Strands documentation for more details. ## Amazon Bedrock configuration You can also use Writer models through Amazon Bedrock, which provides a managed service for accessing foundation models. ### Prerequisites Before you configure the Amazon Bedrock client for Strands Agent SDK, follow the [Bedrock integration guide](/home/integrations/bedrock) to set up AWS credentials, enable Writer models in your region, and set up the required IAM permissions. ### Installation Install the base Strands Agents package: ```bash theme={null} pip install strands-agents ``` Bedrock is the default model provider in Strands Agents, so no additional model provider installation is required. The `BedrockModel` class is available by default. > [!NOTE] > > To follow along with the examples in this guide, you'll also need the [Strands Agent Tools package](https://github.com/strands-agents/tools). Install the package with `pip install strands-agent-tools`. > To follow along with the examples in this guide, you'll also need the [Strands Agent Tools package](https://github.com/strands-agents/tools). Install the package with `pip install strands-agents-tools`. ### Client configuration The following client configuration uses the `us.writer.palmyra-x5-v1:0` model ID, which is the ID for the [cross-region inference profile for Palmyra X5](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html). Check which AWS Regions support Writer models before selecting an inference profile. ```python theme={null} # Configure Bedrock model with Writer model ID model = BedrockModel( model_id="us.writer.palmyra-x5-v1:0", region_name="us-west-2", # Your preferred AWS region # Additional client configuration options ) ``` ### Usage After configuring the Bedrock model, you can use it with Strands Agents: ```python theme={null} from strands import Agent from strands.models.bedrock import BedrockModel from strands_tools import calculator # Configure Bedrock model with Writer model ID model = BedrockModel( model_id="us.writer.palmyra-x5-v1:0", region_name="us-west-2" ) agent = Agent(model=model, tools=[calculator]) response = agent("What is 2+2") print(response) ``` ## Model configuration The `WriterModel` accepts configuration parameters as keyword arguments to the model constructor: | Parameter | Type | Description | Default | Options | | - | - | - | - | - | | `model_id` | `str` | Model name to use (`palmyra-x5`, `palmyra-x4`, etc.) | Required | [reference](/home/models) | | `max_tokens` | `Optional[int]` | Maximum number of tokens to generate | See the Context Window for [each available model](#available-models) | [reference](/api-reference/completion-api/chat-completion#body-max-tokens) | | `stop` | `Optional[Union[str, List[str]]]` | A token or sequence of tokens that, when generated, causes the model to stop producing further content. This can be a single token or an array of tokens, acting as a signal to end the output. | `None` | [reference](/api-reference/completion-api/chat-completion#body-stop) | | `stream_options` | `Dict[str, Any]` | Additional options for streaming. Specify `include_usage` to include usage information in the response, in the `accumulated_usage` field. If you don't specify this, `accumulated_usage`for each value. | `None` | [reference](/api-reference/completion-api/chat-completion#body-stream) | | `temperature` | `Optional[float]` | What sampling temperature to use (0.0 to 2.0). A higher temperature produces more random output. | `1` | [reference](/api-reference/completion-api/chat-completion#body-temperature) | | `top_p` | `Optional[float]` | Threshold for "nucleus sampling" | `None` | [reference](/api-reference/completion-api/chat-completion#body-top_p) | ## Examples ### Writer API integration #### Enterprise workflow automation ```python theme={null} from strands import Agent from strands.models.writer import WriterModel from my_tools import web_search, email_sender # Custom tools from your local module model = WriterModel( client_args={"api_key": ""}, model_id="palmyra-x5", ) agent = Agent( model=model, tools=[web_search, email_sender], system_prompt="You are an enterprise assistant that helps automate business workflows." ) response = agent("Research our competitor's latest product launch and draft a summary email for the leadership team") ``` > [!NOTE] > > The `web_search` and `email_sender` tools in this example are custom tools that you would need to define. See [Python Tools](https://strandsagents.com/latest/documentation/docs/user-guide/concepts/tools/python-tools/?h=python+tools) for guidance on creating custom tools, or use existing tools from the [`strands_tools` package](https://strandsagents.com/latest/documentation/docs/user-guide/concepts/tools/example-tools-package/). #### Financial analysis with Palmyra X5 ```python theme={null} from strands import Agent from strands.models.writer import WriterModel # Use Palmyra X5 for financial analysis model = WriterModel( client_args={"api_key": ""}, model_id="palmyra-x5" ) agent = Agent( model=model, system_prompt="You are a financial analyst assistant. Provide accurate, data-driven analysis." ) # Replace the placeholder with your actual financial report content actual_report = """ [Your quarterly earnings report content would go here - this could include: - Revenue figures - Profit margins - Growth metrics - Risk factors - Market analysis - Any other financial data you want analyzed] """ response = agent(f"Analyze the key financial risks in this quarterly earnings report: {actual_report}") ``` #### Long-context document processing ```python theme={null} from strands import Agent from strands.models.writer import WriterModel # Use Palmyra X5 for processing very long documents model = WriterModel( client_args={"api_key": ""}, model_id="palmyra-x5", temperature=0.2 ) agent = Agent( model=model, system_prompt="You are a document analysis assistant that can process and summarize lengthy documents." ) # Can handle documents up to 1M tokens # Replace the placeholder with your actual document content actual_transcripts = """ [Meeting transcript content would go here - this could be thousands of lines of text from meeting recordings, documents, or other long-form content that you want to analyze] """ response = agent(f"Summarize the key decisions and action items from these meeting transcripts: {actual_transcripts}") ``` #### Vision and image analysis Palmyra X5 supports vision capabilities, allowing you to analyze images and extract information from visual content. ```python theme={null} from strands import Agent from strands.models.writer import WriterModel # Use Palmyra X5 for vision tasks model = WriterModel( client_args={"api_key": ""}, model_id="palmyra-x5" ) agent = Agent( model=model, system_prompt="You are a visual analysis assistant. Provide detailed, accurate descriptions of images and extract relevant information." ) # Read the image file with open("path/to/image.png", "rb") as image_file: image_data = image_file.read() messages = [ { "role": "user", "content": [ { "image": { "format": "png", "source": { "bytes": image_data } } }, { "text": "Analyze this image and describe what you see. What are the key elements, colors, and any text or objects visible?" } ] } ] # Create an agent with the image message vision_agent = Agent(model=model, messages=messages) # Analyze the image response = vision_agent("What are the main features of this image and what might it be used for?") print(response) ``` ### Bedrock integration #### Structured output generation Palmyra X5 and X4 support structured output generation using [Pydantic models](https://docs.pydantic.dev/latest/) through Bedrock. This is useful for ensuring consistent, validated responses. > [!NOTE] > > Structured output disables streaming and returns the complete response at once, unlike regular chat completions, which stream by default. See [Callback Handlers](https://strandsagents.com/latest/documentation/docs/user-guide/concepts/streaming/callback-handlers/?h=callback) for more details. ```python theme={null} import os from boto3 import session from dotenv import load_dotenv from pydantic import BaseModel from typing import List from strands import Agent from strands.models import BedrockModel load_dotenv() # Define a structured schema for marketing campaign class MarketingCampaign(BaseModel): campaign_name: str target_audience: str key_messages: List[str] channels: List[str] budget_allocation: str success_metrics: List[str] timeline: str call_to_action: str # Use Writer Palmyra X5 through Bedrock bedrock_model = BedrockModel( model_id='us.writer.palmyra-x5-v1:0', boto_session=session.Session( aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID", ""), aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY", ""), aws_session_token=os.getenv("AWS_SESSION_TOKEN", ""), region_name="us-west-2", ), streaming=False, ) agent = Agent( model=bedrock_model, system_prompt="You are a marketing strategist. Create comprehensive marketing campaigns with structured data for enterprise clients." ) # Generate structured marketing campaign response = agent.structured_output( output_model=MarketingCampaign, prompt="Create a B2B marketing campaign for a cloud infrastructure platform targeting enterprise IT decision-makers and CTOs." ) print(f"Campaign: {response.campaign_name}\nTarget Audience: {response.target_audience}\nKey Messages: {response.key_messages}\nChannels: {response.channels}\nBudget: {response.budget_allocation}\nMetrics: {response.success_metrics}\nTimeline: {response.timeline}\nCall to Action: {response.call_to_action}") ``` #### Memory agent This example demonstrates how to use Writer models through Bedrock with memory capabilities. The `mem0_memory` tool from `strands_tools` provides persistent, long-term memory that stores information using [Mem0's memory architecture](https://strandsagents.com/latest/documentation/docs/examples/python/memory_agent/), allowing the agent to remember user preferences, facts, and context across multiple sessions. The memory system uses semantic search to retrieve relevant information and can store, list, and retrieve memories based on user queries. ```python theme={null} import os import logging from boto3 import session from dotenv import load_dotenv from strands import Agent from strands.models import BedrockModel from strands_tools import mem0_memory, use_llm logger = logging.getLogger(__name__) # Load environment variables load_dotenv() USER_ID = "mem0_user" # System prompt for the memory agent MEMORY_SYSTEM_PROMPT = f"""You are a personal assistant that maintains context by remembering user details. Capabilities: - Store new information using mem0_memory tool (action="store") - Retrieve relevant memories (action="retrieve") - List all memories (action="list") - Provide personalized responses Key Rules: - Always include user_id={USER_ID} in tool calls - Be conversational and natural in responses - Format output clearly - Acknowledge stored information - Only share relevant information - Politely indicate when information is unavailable """ # Use Writer Palmyra X5 through Bedrock bedrock_model = BedrockModel( model_id='us.writer.palmyra-x5-v1:0', boto_session=session.Session( aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID", ""), aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY", ""), aws_session_token=os.getenv("AWS_SESSION_TOKEN", ""), region_name="us-west-2", ), streaming=False, ) # Create an agent with memory capabilities memory_agent = Agent( model=bedrock_model, system_prompt=MEMORY_SYSTEM_PROMPT, tools=[mem0_memory, use_llm], ) def initialize_demo_memories(): """Initialize some demo memories to showcase functionality.""" content = """My name is Alex. I like to travel and stay in Airbnbs rather than hotels. I am planning a trip to Japan next spring. I enjoy hiking and outdoor photography as hobbies. I have a dog named Max. My favorite cuisine is Italian food.""" memory_agent.tool.mem0_memory(action="store", content=content, user_id=USER_ID) # Example usage if __name__ == "__main__": print("\n🧠 Memory Agent 🧠\n") # Initialize demo memories initialize_demo_memories() print("Demo memories initialized!") # Example interactions print("\nExample: What do you know about me?") response = memory_agent("What do you know about me?") print(f"Response: {response}") print("\nExample: Remember that I prefer window seats on flights") response = memory_agent("Remember that I prefer window seats on flights") print(f"Response: {response}") print("\nExample: What are my travel preferences?") response = memory_agent("What are my travel preferences?") print(f"Response: {response}") ``` ## Additional resources See more information and examples below: * [Additional code examples for Strands Agents](https://github.com/writer/aws-examples/tree/main/strands-examples) * [Strands Agents GitHub repository](https://github.com/strands-agents/sdk-python) * [Writer models](/home/models) # Writer Control Center Source: https://dev.writer.com/home/introduction Use Control Center to configure models, data, guardrails, and observability, and build agents that run on Writer Writer Control Center is a full-stack platform and control plane for AI. Platform and IT teams configure models, data, guardrails, and observability once, and the teams they support build agents and applications on top of those controls. This page shows what you can configure and govern in Control Center, and the paths available for building on it. ## Configure and govern your platform Control Center centralizes the controls IT and platform teams use to run AI safely across the organization. Configure these once and they apply to every agent and application built on Writer. > [card] [Guardrails](/home/guardrails) > > Enforce content safety, PII protection, and compliance policies across your AI agents. > [card] [Observability](/home/observability) > > Monitor agent activity with event logs, agent performance metrics, and session logs. > [card] [Encryption](/home/encryption-key-management) > > Manage your own encryption keys to control how Writer protects your data at rest. > [card] [Models](/home/models-overview) > > Configure Writer's Palmyra models and connect external models from providers like AWS Bedrock and OpenRouter. > [card] [Connect your data](/home/mcp-gateway) > > Connect data sources through prebuilt connectors, MCP, and knowledge graphs. > [card] [Usage and spend](/home/usage-and-spend) > > Track organization-wide token consumption, costs, and spending trends. ## Choose how you build Developers build on Control Center through two paths: full-code deployment with Agent Builder v2, or direct API access with the Writer API and SDKs. > [card] [Agent Builder v2](/home/agent-builder/overview) > > Deploy your own dockerized applications to Writer and run them under platform controls. > [card] [API and SDKs](/home/quickstart) > > Integrate chat completions, knowledge graphs, and tool calling into your own stack. → See [Development options](/home/development_options) for the developer build paths. ## Integrate with your stack Writer works with popular frameworks and observability tools. > [card] [Framework integrations](/home/integrations-overview) > > Use Writer with LangChain, AWS Strands, Instructor, and more. > [card] [Observability exports](/home/integrations/openllmetry) > > Export telemetry data to your existing observability tools via OpenLLMetry. ## Where to go for help > [card] [Help center](https://support.writer.com/) > > Need help with billing, account management, or enterprise support? Visit our help center. > [card] [Developer feedback](mailto:dev-feedback@writer.com) > > Stuck on something? Have feedback on the docs? Send us an email. # Use a Knowledge Graph in a chat Source: https://dev.writer.com/home/kg-chat Query Knowledge Graphs during chat completions with tool calling. Reference multiple graphs and configure query parameters for accurate responses. > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. This guide demonstrates how to send questions to a [Knowledge Graph](/home/knowledge-graph) during a [chat completion](/home/chat-completion). Knowledge Graph chat is a predefined tool you can use to reference a Knowledge Graph during a chat. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Tool structure Knowledge Graph chat is a predefined tool supported by Palmyra X4 and later models, to be used with tool calling in the [chat endpoint](/api-reference/completion-api/chat-completion). To use Knowledge Graph chat, add the following object to the `tools` array when calling the chat endpoint: | Parameter | Type | Description | | - | - | - | | `type` | string | The type of tool. Must be `graph` for Knowledge Graph chat. | | `function` | object | An object containing the `graph_ids`, `description`, `subqueries`, and `query_config` parameters | | `function.graph_ids` | array | An array of strings containing the graph IDs you wish to reference | | `function.description` | string | A description of the graphs you are referencing. This helps the model understand when to use the Knowledge Graph tool in the chat. If there are multiple graphs, include a description for each, referencing the graph by name. | | `function.subqueries` | Boolean | A Boolean indicating whether to include the subqueries used by Palmyra in the response. | | `function.query_config` | object | Configuration options for Knowledge Graph queries. See the [Query configuration parameters](#query-configuration-parameters) below. | > [!NOTE] > > Find your Knowledge Graph ID using one of these methods: > > * Call the [Knowledge Graph list endpoint](/api-reference/kg-api/list-graphs) to retrieve all Knowledge Graphs with their IDs. > * Locate the ID in the URL of the Knowledge Graph page in [Control Center](https://app.writer.com/controlcenter). > > Both org-wide Knowledge Graphs and Knowledge Graphs [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5) are accessible via the API and SDK. When a Knowledge Graph is deployed to specific teams, list it with the `team_ids` query parameter or use a team-scoped API key to see it. For more detail, see [Create and manage a Knowledge Graph](/home/knowledge-graph). ### Query configuration parameters | Parameter | Type | Range | Default | Description | | - | - | - | - | - | | `max_subquestions` | integer | 1-10 | 6 | Maximum number of sub-questions to generate when processing complex queries. | | `search_weight` | integer | 0-100 | 50 | Controls the balance between keyword and semantic search in ranking results. | | `grounding_level` | number | 0.0-1.0 | 0.0 | Controls how closely responses must match to source material. | | `max_snippets` | integer | 5-25 (recommended) | 30 | Maximum number of text snippets to retrieve from the Knowledge Graph for context. Works in concert with `search_weight` to control best matches vs broader coverage. **Note**: While technically supports 1-60, values below 5 may return no results due to RAG implementation. Recommended range is 5-25. Due to RAG system behavior, you may see more snippets than requested. | | `max_tokens` | integer | 100-8000 | 4000 | Maximum number of tokens the model can generate in the response. | | `keyword_threshold` | number | 0.0-1.0 | 0.7 | Threshold for keyword-based matching when searching Knowledge Graph content. | | `semantic_threshold` | number | 0.0-1.0 | 0.7 | Threshold for semantic similarity matching when searching Knowledge Graph content. Set higher for stricter relevance, lower for broader range. | | `inline_citations` | Boolean | true/false | false | Whether to include inline citations within the response text. | For detailed explanations and usage examples, see the [Knowledge Graph query configuration guide](/home/knowledge-graph-query-config). ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/chat' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "messages": [ { "role": "user", "content": "Which of our products contain both food coloring and chocolate?" } ], "tool_choice": "auto", "tools": [ { "type": "graph", "function": { "description": "Knowledge Graph containing information about Acme Inc. food products", "graph_ids": [ "" ], "subqueries": true } } ], "stream": true }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() tools = [{ "type": "graph", "function": { "description": "Description of the graph(s)", "graph_ids": [ "" ], "subqueries": True } }] messages = [{"role": "user", "content": "Which of our products contain both food coloring and chocolate?"}] response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, # The tools array defined earlier. tool_choice="auto", stream=True ) for chunk in response: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].delta.content, end="", flush=True) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const tools = [{ type: "graph", function: { description: "Description of the graph(s)", graph_ids: [ "" ], subqueries: true } }] let messages = [{role: "user", content: "Which of our products contain both food coloring and chocolate?"}] const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, // The tools array defined earlier. tool_choice: "auto", stream: true }); for await (const chunk of response) { if (chunk.choices[0].delta.content) { process.stdout.write(chunk.choices[0].delta.content); } } ``` > [!NOTE] > > You can only pass one prebuilt tool in the `tools` array at a time. However, you can pass multiple [custom tools](/home/tool-calling) in the same request. > > Prebuilt tools are: > > * Knowledge Graph tool > * [LLM tool](/home/model-delegation) ### Response format When a chat completion uses the Knowledge Graph tool, the response from the Knowledge Graph tool is in the `graph_data` object. That object contains the following fields: | Parameter | Type | Description | | - | - | - | | `sources` | array | An array of objects containing the source file IDs and snippets that helped the model answer the question. | | `sources.file_id` | string | The ID of the source file. | | `sources.snippet` | string | A snippet from the source file that helped the model answer the question. | | `status` | string | The status of the query. | | `subqueries` | array | An array of objects containing the subqueries used by Palmyra in the response. | | `subqueries.query` | string | The query used by Palmyra to answer the question. | | `subqueries.answer` | string | The answer to the question. | | `subqueries.sources` | array | An array of objects containing the source file IDs and snippets that helped the model answer the question. | The full response has the following structure. The subqueries and sources shown are abbreviated for readability. If the `subqueries` parameter is `false`, or if the model doesn't need subqueries to answer the question, this array is be empty. ```json streaming response [expandable] {12} theme={null} { "id": "1234", "object": "chat.completion.chunk", "choices": [ { "index": 0, "finish_reason": "stop", "delta": { "content": "None of our products contain both chocolate and food coloring. The products containing chocolate are different from those containing food coloring.", "role": "assistant", "tool_calls": null, "graph_data": { "sources": [ { "file_id": "1234", "snippet": "with cocoa for an extra touch of chocolate…" }, { "file_id": "5678", "snippet": "Sugar, corn syrup, artificial flavors, food coloring…" } ], "status": "finished", "subqueries": [ { "query": "Which of our products contain food coloring?", "answer": "The products that contain food coloring are...", "sources": [ { "file_id": "1234", "snippet": "Sugar, citric acid, artificial flavors…" }, { "file_id": "5678", "snippet": "Coffee, coconut milk, ice" } ] }, { "query": "Which of our products contain chocolate?", "answer": "Several products contain chocolate. These include…", "sources": [ { "file_id": "1234", "snippet": "with cocoa for an extra touch of chocolate…" } ] } ] } }, } ] // Other fields omitted for brevity } ``` ```json non-streaming response [expandable] {12} theme={null} { "id": "1234", "object": "chat.completion", "choices": [ { "index": 0, "finish_reason": "stop", "message": { "content": "None of our products contain both chocolate and food coloring. The products containing chocolate are different from those containing food coloring.", "role": "assistant", "tool_calls": null, "graph_data": { "sources": [ { "file_id": "1234", "snippet": "with cocoa for an extra touch of chocolate…" }, { "file_id": "5678", "snippet": "Sugar, corn syrup, artificial flavors, food coloring…" } ], "status": "finished", "subqueries": [ { "query": "Which of our products contain food coloring?", "answer": "The products that contain food coloring are...", "sources": [ { "file_id": "1234", "snippet": "Sugar, citric acid, artificial flavors…" }, { "file_id": "5678", "snippet": "Coffee, coconut milk, ice" } ] }, { "query": "Which of our products contain chocolate?", "answer": "Several products contain chocolate. These include…", "sources": [ { "file_id": "1234", "snippet": "with cocoa for an extra touch of chocolate…" } ] } ] } }, } ] // Other fields omitted for brevity } ``` ## Usage example The following example uses a hypothetical product information Knowledge Graph to answer a question about which food products contain both food coloring and chocolate. ### Create the tools array First, define the `tools` array with the `type` set to `graph`. The `function` object contains the `graph_ids`, `description`, and `subqueries` parameters. In this example, the subqueries are included in the response. Subqueries can be useful for debugging or for providing additional context to the user about how the model arrived at the answer. ```bash cURL theme={null} "tools": [ { "type": "graph", "function": { "description": "Knowledge Graph containing information about Acme Inc. food products", "graph_ids": [ "" ], "subqueries": true } } ] ``` ```python Python theme={null} tools = [{ "type": "graph", "function": { "description": "Knowledge Graph containing information about Acme Inc. food products", "graph_ids": [ "" ], "subqueries": True } }] ``` ```javascript JavaScript theme={null} const tools = [{ type: "graph", function: { description: "Knowledge Graph containing information about Acme Inc. food products", graph_ids: [ "" ], subqueries: true } }] ``` ### Send the request Add the tools array to the chat endpoint call along with your array of messages. Setting `tool_choice` to `auto` allows the model to choose when to use the Knowledge Graph tool, based on the user's question and the description of the tool. This example streams the response in real-time as the model generates it. If you are unfamiliar with the chat completions endpoint or streaming vs. non-streaming responses, learn more in the [chat completion guide](/home/chat-completion). ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/chat' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "messages": [ { "role": "user", "content": "Which of our products contain both food coloring and chocolate?" } ], "tool_choice": "auto", "tools": [ { "type": "graph", "function": { "description": "Knowledge Graph containing information about Acme Inc. food products", "graph_ids": [ "" ], "subqueries": true } } ], "stream": true }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() tools = [{ "type": "graph", "function": { "description": "Knowledge Graph containing information about Acme Inc. food products", "graph_ids": [ "" ], "subqueries": True } }] messages = [{"role": "user", "content": "Which of our products contain both food coloring and chocolate?"}] response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, # The tools array defined earlier. tool_choice="auto", stream=True ) for chunk in response: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].delta.content, end="", flush=True) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const tools = [{ type: "graph", function: { description: "Knowledge Graph containing information about Acme Inc. food products", graph_ids: [ "" ], subqueries: true } }] let messages = [{role: "user", content: "Which of our products contain both food coloring and chocolate?"}] const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, // The tools array defined earlier. tool_choice: "auto", stream: true }); for await (const chunk of response) { if (chunk.choices[0].delta.content) { process.stdout.write(chunk.choices[0].delta.content); } } ``` ### Display Knowledge Graph subqueries and sources You may want to display the `sources` or `subqueries` in your UI to assist your user in understanding how the model derived the answer to the question. The following example shows how to display the subqueries as well as the status of the query from the Knowledge Graph. ```python Python theme={null} from writerai import Writer # Initialize the client. client = Writer() tools = [{ "type": "graph", "function": { "description": "Knowledge Graph containing information about Acme Inc. food products", "graph_ids": [ "" ], "subqueries": True } }] messages = [{"role": "user", "content": "Which of our products contain both food coloring and chocolate?"}] response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto", stream=True ) for chunk in response: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].delta.content, end="", flush=True) if chunk.choices[0].delta.graph_data is not None: if chunk.choices[0].delta.graph_data.status is not None: print(f"Query status: {chunk.choices[0].delta.graph_data.status}") if chunk.choices[0].delta.graph_data.subqueries: print(f"Subquery: {chunk.choices[0].delta.graph_data.subqueries[0].query}") ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the client. const client = new Writer(); const tools = [{ type: "graph", function: { description: "Knowledge Graph containing information about Acme Inc. food products", graph_ids: [ "" ], subqueries: true } }] let messages = [{role: "user", content: "Which of our products contain both food coloring and chocolate?"}] const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, // The tools array defined earlier. tool_choice: "auto", stream: true }); for await (const chunk of response) { if (chunk.choices[0].delta.content) { console.log(chunk.choices[0].delta.content); } if (chunk.choices[0].delta.graph_data) { if (chunk.choices[0].delta.graph_data.status) { console.log(`Query status: ${chunk.choices[0].delta.graph_data.status}`); } if (chunk.choices[0].delta.graph_data.subqueries && chunk.choices[0].delta.graph_data.subqueries.length > 0 && chunk.choices[0].delta.graph_data.subqueries[0].query) { console.log(`Subquery: ${chunk.choices[0].delta.graph_data.subqueries[0].query}`); } } } ``` ### Customize query behavior You can fine-tune how your Knowledge Graph searches and retrieves content using the `query_config` parameter. Learn about all available configuration options in the [Knowledge Graph query configuration guide](/home/knowledge-graph-query-config). ## Next steps By following this guide, you can reference Knowledge Graphs in your users' chats in your application. Next, explore other ways to extend your chat applications: * [Analyze images in a chat](/home/chat-with-images) * [Pass questions to another model](/home/model-delegation) # Ask questions to Knowledge Graphs Source: https://dev.writer.com/home/kg-query The Knowledge Graph [question endpoint](/api-reference/kg-api/question) allows you to ask questions directly to one or more Knowledge Graphs. This provides a direct way to query your Knowledge Graphs without needing to use chat completions. You can also enable subqueries to break down complex questions into smaller subqueries and provide answers for each one. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Question endpoint **Endpoint:** `POST /v1/graphs/question` ```bash cURL theme={null} curl --location --request POST https://api.writer.com/v1/graphs/question \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header "Content-Type: application/json" \ --data-raw '{ "graph_ids": [""], "question": "" }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.graphs.question( graph_ids=[""], question="" ) print(f"Answer: {response.answer}") print(f"Sources: {response.sources}") ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.graphs.question({ graph_ids: [""], question: "" }); console.log(`Answer: ${response.answer}`); console.log(`Sources: ${response.sources}`); ``` ### Request body The request body is a JSON object with the following fields: | Parameter | Type | Required | Description | | - | - | - | - | | `graph_ids` | array\[string] | Yes | The unique identifiers of the Knowledge Graphs to query. You can specify multiple Knowledge Graph IDs to search across multiple graphs. | | `question` | string | Yes | The question to answer using the Knowledge Graph. | | `subqueries` | Boolean | No | Specify whether to include subqueries. Defaults to `false`. | | `stream` | Boolean | No | Determines whether to stream the response. If `true`, the output is sent as it is generated, which can be useful for real-time applications. Defaults to `false`. See how to [handle streaming responses](#stream-the-response) below. | | `query_config` | object | No | Configuration options for Knowledge Graph queries. See [Query configuration parameters](#query-configuration-parameters) below for detailed parameter descriptions. | > [!NOTE] > > Find your Knowledge Graph ID using one of these methods: > > * Call the [Knowledge Graph list endpoint](/api-reference/kg-api/list-graphs) to retrieve all Knowledge Graphs with their IDs. > * Locate the ID in the URL of the Knowledge Graph page in [Control Center](https://app.writer.com/controlcenter). > > Both org-wide Knowledge Graphs and Knowledge Graphs [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5) are accessible via the API and SDK. When a Knowledge Graph is deployed to specific teams, list it with the `team_ids` query parameter or use a team-scoped API key to see it. For more detail, see [Create and manage a Knowledge Graph](/home/knowledge-graph). ### Query configuration parameters | Parameter | Type | Range | Default | Description | | - | - | - | - | - | | `max_subquestions` | integer | 1-10 | 6 | Maximum number of sub-questions to generate when processing complex queries. | | `search_weight` | integer | 0-100 | 50 | Controls the balance between keyword and semantic search in ranking results. | | `grounding_level` | number | 0.0-1.0 | 0.0 | Controls how closely responses must match to source material. Set lower for grounded outputs, higher for creativity. | | `max_snippets` | integer | 5-25 (recommended) | 30 | Maximum number of text snippets to retrieve from the Knowledge Graph for context. Works in concert with `search_weight` to control best matches vs broader coverage. **Note**: While technically supports 1-60, values below 5 may return no results due to RAG implementation. Recommended range is 5-25. Due to RAG system behavior, you may see more snippets than requested. | | `max_tokens` | integer | 100-8000 | 4000 | Maximum number of tokens the model can generate in the response. | | `keyword_threshold` | number | 0.0-1.0 | 0.7 | Threshold for keyword-based matching when searching Knowledge Graph content. | | `semantic_threshold` | number | 0.0-1.0 | 0.7 | Threshold for semantic similarity matching when searching Knowledge Graph content. Set higher for stricter relevance, lower for broader range. | | `inline_citations` | Boolean | true/false | false | Whether to include inline citations within the response text. | For detailed explanations and usage examples, see the [Knowledge Graph query configuration guide](/home/knowledge-graph-query-config). ### Response format The response is a JSON object with the following fields: | Parameter | Type | Description | | - | - | - | | `question` | string | The question you asked. | | `answer` | string | The answer to the question based on the Knowledge Graph content. | | `sources` | array | An array of source objects that contain the file information and text snippets used to generate the answer. | | `sources[].file_id` | string | If the source is a file, this is the unique identifier of the file that contains the source information. | | `sources[].snippet` | string | If the source is a file, this is a snippet of text from the source file used to answer the question. | | `subqueries` | array | An array of subquery objects. Only included if `subqueries` is `true`. | | `subqueries[].query` | string | The subquery the model generated to answer the question. | | `subqueries[].answer` | string | The answer to the subquery. | | `subqueries[].sources` | array | An array of source objects for the subquery. | > [tab] Non-streaming response > > ```json theme={null} > { > "question": "What was our company's revenue growth in Q4 2023?", > "answer": "The company achieved 23% year-over-year revenue growth in Q4 2023, reaching $142 million in total revenue.", > "sources": [ > { > "file_id": "1234", > "snippet": "In the fourth quarter of 2023, we saw strong performance with revenue reaching $142 million, representing a 23% increase compared to Q4 2022." > } > ] > } > ``` > [tab] Streaming response > > ```json theme={null} > data: { > "question": "What was our company's revenue growth in Q4 2023?", > "answer": "The", > "sources": [], > "subqueries": null, > "references": null > } > ``` ## Examples ### Query multiple knowledge graphs You can query multiple Knowledge Graphs at once by providing multiple graph IDs in the `graph_ids` array. ```bash cURL theme={null} curl --location --request POST https://api.writer.com/v1/graphs/question \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header "Content-Type: application/json" \ --data-raw '{ "graph_ids": [ "", "" ], "question": "What are the key findings from our research documents?" }' ``` ```python Python theme={null} from writerai import Writer client = Writer() response = client.graphs.question( graph_ids=[ "", "" ], question="What are the key findings from our research documents?" ) print(f"Answer: {response.answer}") ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; const client = new Writer(); const response = await client.graphs.question({ graph_ids: [ "", "" ], question: "What are the key findings from our research documents?" }); console.log(`Answer: ${response.answer}`); ``` ### Enable subqueries When you enable subqueries, the model breaks down complex questions into smaller subqueries and provides answers for each one from the Knowledge Graphs. ```bash cURL theme={null} curl --location --request POST https://api.writer.com/v1/graphs/question \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header "Content-Type: application/json" \ --data-raw '{ "graph_ids": [""], "question": "What are the main products and their market performance?", "subqueries": true }' ``` ```python Python theme={null} from writerai import Writer client = Writer() response = client.graphs.question( graph_ids=[""], question="What are the main products and their market performance?", subqueries=True ) print(f"Main answer: {response.answer}") for subquery in response.subqueries: print(f"Subquery: {subquery.query}") print(f"Answer: {subquery.answer}") ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; const client = new Writer(); const response = await client.graphs.question({ graph_ids: [""], question: "What are the main products and their market performance?", subqueries: true }); console.log(`Main answer: ${response.answer}`); response.subqueries.forEach(subquery => { console.log(`Subquery: ${subquery.query}`); console.log(`Answer: ${subquery.answer}`); }); ``` ### Stream the response You can stream the response from the Knowledge Graphs by setting the `stream` parameter to `true`. This is useful for real-time applications that need to see the response as it is generated. ```bash cURL theme={null} curl --location --request POST https://api.writer.com/v1/graphs/question \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header "Content-Type: application/json" \ --data-raw '{ "graph_ids": [""], "question": "", "stream": true }' ``` ```python Python theme={null} from writerai import Writer client = Writer() response = client.graphs.question( graph_ids=[""], question="", stream=True ) for chunk in response: print(chunk.answer, end="", flush=True) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; const client = new Writer(); const response = await client.graphs.question({ graph_ids: [""], question: "", stream: true }); for await (const chunk of response) { process.stdout.write(chunk.answer); } ``` ## Next steps * Learn how to [create and manage Knowledge Graphs](/home/knowledge-graph) * Use Knowledge Graphs in chat completions with [tool calling](/home/kg-chat) * Explore [Knowledge Graph API reference](/api-reference/kg-api) # Create and manage a Knowledge Graph Source: https://dev.writer.com/home/knowledge-graph Integrate graph-based RAG into your agents with Knowledge Graph API. Achieve higher accuracy than traditional vector-based retrieval methods. Knowledge Graph, our graph-based retrieval-augmented generation (RAG), achieves [higher accuracy](https://arxiv.org/abs/2405.02048) than traditional RAG approaches that use vector retrieval. This guide will help you understand and use the [Knowledge Graph API](/api-reference/kg-api) to integrate RAG capabilities into your agents. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. > [!NOTE] > > Knowledge Graphs can be deployed org-wide (accessible to every team in the organization) or [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5). Both are accessible via the API and SDK. > > * **With an org-scoped API key**, control team scope from the request body: pass `team_ids` on [create](/api-reference/kg-api/create-graph) or [update](/api-reference/kg-api/update-graph), or filter [list](/api-reference/kg-api/list-graphs) with the `team_ids` query parameter. Omit `team_ids` on list to see only org-wide Knowledge Graphs. > * **With a team-scoped API key**, every request is automatically restricted to the key's team. Create assigns to that team; list and retrieve return only that team's Knowledge Graphs; body `team_ids` is not accepted. ## Create a Knowledge Graph A Knowledge Graph is a collection of files that are used to answer questions. To start working with a Knowledge Graph, create an empty Knowledge Graph that you can add files to. **Endpoint**: `POST https://api.writer.com/v1/graphs` ```bash cURL theme={null} curl --location --request POST https://api.writer.com/v1/graphs \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header "Content-Type: application/json" \ --data-raw '{ "name": "Financial Reports", "description": "Knowledge Graph of 2024 financial reports" }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() graph_create_response = client.graphs.create( name="Financial Reports", description="Knowledge Graph of 2024 financial reports" ) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const graphCreateResponse = await client.graphs.create({ name: "Financial Reports", description: "Knowledge Graph of 2024 financial reports" }); ``` ### Request body The request body is a JSON object that contains the following fields: | Parameter | Type | Description | | - | - | - | | `name` | string | The name of the Knowledge Graph. | | `description` | string | The description of the Knowledge Graph. The description should help the model understand the purpose of the Knowledge Graph and when it should be used. | | `team_ids` | array\[integer] | Optional. Team IDs to deploy the Knowledge Graph to. Omit or pass an empty array to create an org-wide Knowledge Graph (the default). Provide one or more team IDs to deploy it to those teams. Only accepted from org-scoped API keys; requests made with a team-scoped API key ignore this field and always assign the Knowledge Graph to that key's team. | ### Response format The response has the following structure: | Parameter | Type | Description | | - | - | - | | `id` | string | The ID of the Knowledge Graph. | | `created_at` | string | The date and time the Knowledge Graph was created. | | `name` | string | The name of the Knowledge Graph. | | `description` | string | The description of the Knowledge Graph. | | `team_ids` | array\[integer] | The team IDs the Knowledge Graph is deployed to. An empty array indicates an org-wide Knowledge Graph. | ```json theme={null} { "id": "6029b226-1ee0-4239-a1b0-cdeebfa3ad5a", "created_at": "2024-06-24T12:34:56Z", "name": "Financial Reports", "description": "Knowledge Graph of 2024 financial reports", "team_ids": [] } ``` ### Deploy a Knowledge Graph to specific teams Pass one or more team IDs in the `team_ids` array to deploy a new Knowledge Graph to those teams instead of the whole organization. Members of any listed team can use the Knowledge Graph; members of other teams cannot. ```bash cURL theme={null} curl --location --request POST https://api.writer.com/v1/graphs \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header "Content-Type: application/json" \ --data-raw '{ "name": "Sales enablement", "description": "Deal decks and objection handling for the Sales team", "team_ids": [42, 43] }' ``` ```python Python theme={null} from writerai import Writer client = Writer() graph = client.graphs.create( name="Sales enablement", description="Deal decks and objection handling for the Sales team", team_ids=[42, 43], ) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; const client = new Writer(); const graph = await client.graphs.create({ name: "Sales enablement", description: "Deal decks and objection handling for the Sales team", team_ids: [42, 43] }); ``` To find team IDs, open a team in [Control Center](https://app.writer.com/controlcenter) and copy the numeric ID from the URL. To later change the team assignment of an existing Knowledge Graph, see [Update team assignment](#update-team-assignment). > [!NOTE] > > Find your Knowledge Graph ID using one of these methods: > > * Call the [Knowledge Graph list endpoint](/api-reference/kg-api/list-graphs) to retrieve all Knowledge Graphs with their IDs. > * Locate the ID in the URL of the Knowledge Graph page in [Control Center](https://app.writer.com/controlcenter). ## Add a file to a Knowledge Graph Once you've created a Knowledge Graph, you can add files to it. The files you add to a Knowledge Graph are used to answer questions and enhance the accuracy of the responses from the LLM You must upload the file to the Writer API before adding it to a Knowledge Graph. See [Manage files](/home/files) for more information about how to upload files. **Endpoint**: `POST /v1/graphs/{graph_id}/file` ```bash cURL theme={null} curl --location --request POST https://api.writer.com/v1/graphs/{graph_id}/file \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header "Content-Type: application/json" \ --data-raw '{"file_id":"1862f090-a281-48f3-8838-26c1e78b605e"}' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() graph_file = client.graphs.add_file_to_graph( graph_id="{graph_id}", file_id="1862f090-a281-48f3-8838-26c1e78b605e", ) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const file = await client.graphs.addFileToGraph('{graph_id}', { file_id: '1862f090-a281-48f3-8838-26c1e78b605e', }); ``` The response will have this structure: ```json theme={null} { "id": "1862f090-a281-48f3-8838-26c1e78b605e", "created_at": "2024-07-01T20:41:44.159505Z", "name": "test.txt", "graph_ids": [ "6029b226-1ee0-4239-a1b0-cdeebfa3ad5a" ] } ``` ### Path parameters | Parameter | Description | | - | - | | `graph_id` | The ID of the Knowledge Graph to update. | ### Request body The request body is a JSON object that contains the following fields: | Parameter | Description | | - | - | | `file_id` | The ID of the file to add to the Knowledge Graph. | You must upload the file to the Writer API before adding it to a Knowledge Graph. See [Manage files](/home/files) for more information about how to upload files. ## Remove a file from a Knowledge Graph **Endpoint**: `DELETE /v1/graphs/{graph_id}/file/{file_id}` ```bash cURL theme={null} curl --location --request DELETE "https://api.writer.com/v1/graphs/{graph_id}/file/{file_id}" \ --header "Authorization: Bearer $WRITER_API_KEY" ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() client.graphs.remove_file_from_graph( graph_id="{graph_id}", file_id="{file_id}" ) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const file = await client.graphs.removeFileFromGraph('{graph_id}', '{file_id}'); ``` ### Path parameters | Parameter | Description | | - | - | | `graph_id` | The ID of the Knowledge Graph to update. | | `file_id` | The ID of the file to remove from the Knowledge Graph. | ### Response format The response has this structure: ```json theme={null} { "id": "1862f090-a281-48f3-8838-26c1e78b605e", "deleted": true } ``` ## List Knowledge Graphs by team Retrieve Knowledge Graphs in an organization with the list endpoint. By default, the response contains only org-wide Knowledge Graphs. To also include Knowledge Graphs deployed to specific teams, pass those team IDs in the `team_ids` query parameter. **Endpoint**: `GET /v1/graphs` ```bash cURL theme={null} # Org-wide only (default) curl --location "https://api.writer.com/v1/graphs" \ --header "Authorization: Bearer $WRITER_API_KEY" # Also include Knowledge Graphs deployed to team 42 or team 43 curl --location "https://api.writer.com/v1/graphs?team_ids=42&team_ids=43" \ --header "Authorization: Bearer $WRITER_API_KEY" ``` ```python Python theme={null} from writerai import Writer client = Writer() # Org-wide only (default) org_wide = client.graphs.list() # Filtered to specific teams team_scoped = client.graphs.list(team_ids=[42, 43]) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; const client = new Writer(); // Org-wide only (default) for await (const graph of client.graphs.list()) { console.log(graph.id); } // Filtered to specific teams for await (const graph of client.graphs.list({ team_ids: [42, 43] })) { console.log(graph.id); } ``` > [!WARNING] > > Omitting `team_ids` returns only org-wide Knowledge Graphs. Knowledge Graphs deployed to specific teams do not appear in an unfiltered list; the caller must opt in by passing `team_ids`. Team-scoped API keys are the exception: those requests always return only that key's team, regardless of `team_ids`. ## Update team assignment Change the teams a Knowledge Graph is deployed to by including `team_ids` in a `PUT /v1/graphs/{graph_id}` request. The array you pass replaces the whole team assignment: * Omit `team_ids` to leave the current team assignment unchanged. * Pass one or more team IDs to scope the Knowledge Graph to exactly those teams. * Pass an empty array (`[]`) to remove every team assignment and make the Knowledge Graph org-wide again. Team-scoped API keys cannot change the team assignment of a Knowledge Graph; the field is only accepted from org-scoped API keys. ```bash cURL theme={null} # Move a Knowledge Graph from org-wide to Sales and Marketing teams curl --location --request PUT "https://api.writer.com/v1/graphs/{graph_id}" \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header "Content-Type: application/json" \ --data-raw '{"team_ids": [42, 43]}' # Move it back to org-wide curl --location --request PUT "https://api.writer.com/v1/graphs/{graph_id}" \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header "Content-Type: application/json" \ --data-raw '{"team_ids": []}' ``` ```python Python theme={null} from writerai import Writer client = Writer() client.graphs.update("{graph_id}", team_ids=[42, 43]) client.graphs.update("{graph_id}", team_ids=[]) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; const client = new Writer(); await client.graphs.update("{graph_id}", { team_ids: [42, 43] }); await client.graphs.update("{graph_id}", { team_ids: [] }); ``` ## Use a team-scoped API key Team-scoped API keys restrict every Knowledge Graph API request to a single team, without any per-request configuration. They are useful when a team owns its own API integration and should not see other teams' Knowledge Graphs. When a team-scoped API key is used: * `POST /v1/graphs` automatically assigns the new Knowledge Graph to the key's team. Passing `team_ids` in the request body is rejected. * `PUT /v1/graphs/{graph_id}` cannot change the team assignment of a Knowledge Graph. Passing `team_ids` in the request body is rejected. * `GET /v1/graphs/{graph_id}`, `DELETE /v1/graphs/{graph_id}`, and the file endpoints return only Knowledge Graphs deployed to the key's team. Org-wide Knowledge Graphs and Knowledge Graphs deployed to other teams are not visible. * `GET /v1/graphs` returns only Knowledge Graphs deployed to the key's team. Passing `team_ids` in the query string is only accepted when it matches the key's team. Create team-scoped API keys the same way you create org-scoped API keys, then select the team the key applies to. Existing org-scoped API keys continue to work exactly as before. ## Add URLs to a Knowledge Graph You can add URLs to a Knowledge Graph to enhance the model's knowledge with content from websites. The LLM can then query and use this information when responding to questions. This example adds a web connector URL to a Knowledge Graph. It first retrieves the Knowledge Graph to see the current URLs and then adds a new URL to the Knowledge Graph. Note that this operation replaces the entire list of URLs attached to the Knowledge Graph, which is why it is important to retrieve the existing list of URLs first. ```bash cURL theme={null} # 1. First, retrieve the current Knowledge Graph to see existing URLs curl --location 'https://api.writer.com/v1/graphs/{graph_id}' \ --header "Authorization: Bearer $WRITER_API_KEY" # 2. Then, send a new request with all the URLs you want to add. In this example, there were no existing URLs, so it's adding a single URL. curl --location --request PUT 'https://api.writer.com/v1/graphs/{graph_id}' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "urls": [ { "url": "https://example.com/documentation", "type": "sub_pages", "exclude_urls": [ "https://example.com/documentation/admin", "https://example.com/documentation/private" ] } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() graph_id = "GRAPH_ID" graph = client.graphs.retrieve(graph_id) urls = graph.urls urls.append({ "url": "https://example.com/documentation", "type": "sub_pages", "exclude_urls": ["https://example.com/documentation/admin", "https://example.com/documentation/private"] }) client.graphs.update(graph_id, urls=urls) print(client.graphs.retrieve(graph_id).urls) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const graph_id = "GRAPH_ID"; const graph = await client.graphs.retrieve(graph_id); const urls = graph.urls; urls.push({ url: 'https://example.com/documentation', type: 'sub_pages', exclude_urls: [ 'https://example.com/documentation/admin', 'https://example.com/documentation/private' ] }); const response = await client.graphs.update(graph_id, { urls }); const updatedGraph = await client.graphs.retrieve(graph_id); console.log(updatedGraph.urls); ``` See more examples in [Add URLs to a Knowledge Graph](/home/web-connector-url). ## Add a Knowledge Graph to a no-code agent After you've created a Knowledge Graph, you can add it to a [no-code agent](/home/applications) to add RAG capabilities. You can use this endpoint to add or remove Knowledge Graphs from a no-code agent. **Endpoint**: `PUT /v1/applications/{application_id}/graphs` ```bash cURL theme={null} curl --location --request PUT "https://api.writer.com/v1/applications/{application_id}/graphs" \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header "Content-Type: application/json" \ --data-raw '{"graph_id":"6029b226-1ee0-4239-a1b0-cdeebfa3ad5a"}' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() client.applications.graphs.update( application_id="{application_id}", graph_ids=["{graph_id}"] ) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); client.applications.graphs.update('{application_id}', ['{graph_id}']); ``` ### Path parameters | Parameter | Description | | - | - | | `application_id` | The ID of the no-code agent to update. | ### Request body The request body is a JSON object that contains the following fields: | Parameter | Type | Description | | - | - | - | | `graph_ids` | array\[string] | The IDs of the Knowledge Graphs to associate with the no-code agent. | This method updates the associated Knowledge Graphs to the exact list of IDs provided in the request. To remove a single Knowledge Graph from the no-code agent, set the `graph_ids` parameter to an array containing the IDs of all the other Knowledge Graphs associated with the no-code agent, excluding the ID of the Knowledge Graph to remove. To remove all Knowledge Graphs from the no-code agent, set this parameter to an empty array. ### Response format The response contains the new list of IDs of the Knowledge Graphs associated with the no-code agent. ```json theme={null} { "graph_ids": [ "6029b226-1ee0-4239-a1b0-cdeebfa3ad5a" ] } ``` ## Next steps * Learn how to ask your Knowledge Graph questions in a chat completion via [tool calling](/home/kg-chat) * Query your Knowledge Graph directly using the [question endpoint](/home/kg-query) * Fine-tune how your Knowledge Graph searches and retrieves content using the `query_config` parameter in the [Knowledge Graph query configuration guide](/home/knowledge-graph-query-config) # Connect your data to AI with Knowledge Graph Source: https://dev.writer.com/home/knowledge-graph-concepts Understand graph-based RAG with Knowledge Graph. Learn how content ingestion, graph construction, and query processing deliver accurate AI responses. Knowledge Graph is Writer's retrieval-augmented generation (RAG) system that uses graph-based relationships that can improve accuracy compared to vector-only approaches ([reference](https://arxiv.org/abs/2405.02048)). Connect your data sources to enable LLMs to access, understand, and reason about your specific information when generating responses. Get inline citations to ensure every answer pulls from your actual data. ## Knowledge Graph concepts Knowledge Graph is a structured way to store and retrieve information from your documents, websites, and data sources. Unlike traditional search systems that rely on keyword matching or vector similarity, Knowledge Graph creates a network of interconnected information that captures relationships between concepts, entities, and ideas. ### How Knowledge Graph works Knowledge Graph processes your data through several stages: 1. **Content ingestion**: upload files, connect data sources, or add website URLs 2. **Graph construction**: analyze content to identify entities, concepts, and relationships 3. **Indexing**: create a searchable graph structure that captures semantic connections 4. **Query processing**: when you ask questions, the system traverses the graph to find relevant information 5. **Response generation**: combine retrieved information with AI to generate accurate, contextual answers ![Knowledge Graph flow from ingestion to graph construction, indexing, query processing, and response generation.](https://mintcdn.com/writer/9kv7QIFPQINxtMk7/images/home/kg-overview.excalidraw.png?fit=max\&auto=format\&n=9kv7QIFPQINxtMk7\&q=85\&s=9a2934f60712ebf1ef24753f53705d9a) ## Data sources and formats Knowledge Graph supports multiple ways to add data: | Source type | Description | Supported formats/features | Learn more | | - | - | - | - | | **File uploads** | Upload documents directly | - PDF, TXT, DOC/DOCX, PPT/PPTX - CSV, XLS/XLSX - EML, HTML, SRT | [Manage Knowledge Graph data](/home/knowledge-graph) | | **Data connectors** | Connect to external platforms | - Confluence: Access team documentation and wikis - Notion: Import workspaces and databases - Google Drive: Connect to shared drives and documents - SharePoint: Access Microsoft 365 content | [Data connectors guide](https://support.writer.com/article/251-setting-up-knowledge-graph-data-connectorss) | | **Website integration** | Add web content | - Add specific URLs or entire domains - Configure page inclusion/exclusion - Automatic content updates | [Website integration guide](https://support.writer.com/article/272-setting-up-knowledge-graph-web-connectors) | Learn more about [data sources and formats](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph). ## Query capabilities Knowledge Graph supports natural language questions and querying across multiple graphs. You can configure the retrieval to break it down into subqueries, support streaming, get inline citations, and fine-tune the search parameters. **Core features:** * **Natural language questions**: ask questions in plain, conversational language without needing special syntax or query formats. For example, "What is our refund policy?" or "Tell me about our enterprise pricing tiers" will work naturally. * **Multi-graph queries**: search across multiple Knowledge Graphs simultaneously. For example, you can compare data across departments or time periods. **Configurable options:** * **Subqueries**: break down complex questions into smaller parts automatically * **Streaming responses**: get answers as they're generated for real-time applications * **Inline citations**: get answers with embedded source references to verify information * **Query configuration**: fine-tune search parameters including search weight, grounding level, maximum snippets and tokens, and semantic thresholds ## Add Knowledge Graph to your Writer applications Add Knowledge Graph to your Writer applications to create conversational AI, generate content, and enable tool calling in complex workflows. Get started with these guides: * [Create and manage Knowledge Graphs](/home/knowledge-graph): set up your first Knowledge Graph via the Writer API and SDKs * [Ask questions to Knowledge Graphs](/home/kg-query): query your data directly via the Writer API and SDKs * [Chat with a Knowledge Graph](/home/kg-chat): create conversational AI that can reference your specific data * [Build agents with Agent Builder](/home/agent-builder/overview): integrate Knowledge Graph into agents in Control Center * [Enable inline citations](/home/inline-citations): get source references in responses from Knowledge Graph queries * [Knowledge Graph query configuration](/home/knowledge-graph-query-config): fine-tune search parameters ## Best practices ### Organize your data * Create separate Knowledge Graphs for different topics or departments * Use descriptive names and descriptions to help the AI understand context * Regularly update content to ensure accuracy ### Optimize queries * Ask specific, well-formed questions for better results * Use the query configuration parameters to fine-tune responses * Enable subqueries for complex multi-part questions ### Monitor and improve * Review source citations to understand how information is being retrieved * Update Knowledge Graphs with new information as it becomes available * Test different query approaches to find what works best for your use case ## Next steps * Learn how to [create and manage Knowledge Graphs](/home/knowledge-graph) * Explore the [Knowledge Graph API reference](/api-reference/kg-api) * See how to [ask questions to Knowledge Graphs](/home/kg-query) * Understand [Knowledge Graph query configuration](/home/knowledge-graph-query-config) * For additional help, visit the [Writer Help Center](https://support.writer.com) for detailed guides and troubleshooting # Configure Knowledge Graph query parameters Source: https://dev.writer.com/home/knowledge-graph-query-config This guide shows you how to customize Knowledge Graph query behavior using the `query_config` parameter. You can tune search algorithms, control response grounding, adjust content retrieval, and enable inline citations to configure Knowledge Graph responses for your specific use cases. ## Overview The `query_config` parameter allows you to fine-tune how Knowledge Graphs search, rank, and retrieve content. You can control the balance between keyword and semantic search, adjust how closely responses match source material, set relevance thresholds, and enable inline citations for source verification. You can use this parameter with: * **Chat completions** with [Knowledge Graph tools](/home/kg-chat) * **Direct Knowledge Graph queries** via the [`/v1/graphs/question`](/home/kg-query) endpoint ## Example Here's a chat completion example that demonstrates various query configuration parameters to configure Knowledge Graph responses: * `grounding_level: 0.2`: keeps responses closely tied to source material (20% creative interpretation allowed) * `search_weight: 60`: balances keyword and semantic search (60% keyword search, 40% semantic search) * `keyword_threshold: 0.6`: requires 60% keyword match for content to be included * `semantic_threshold: 0.8`: requires 80% semantic similarity for content to be included ```bash cURL theme={null} curl --location --request POST 'https://api.writer.com/v1/chat' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header 'Content-Type: application/json' \ --data-raw '{ "model": "palmyra-x5", "messages": [ { "role": "user", "content": "What are the key features of our product?" } ], "tools": [ { "type": "graph", "function": { "description": "Search company knowledge base", "graph_ids": [""], "subqueries": true, "query_config": { "grounding_level": 0.2, "search_weight": 60, "keyword_threshold": 0.6, "semantic_threshold": 0.8, "inline_citations": true } } } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client client = Writer() # Configure Knowledge Graph tool with query parameters tools = [{ "type": "graph", "function": { "description": "Search company knowledge base", "graph_ids": [""], "subqueries": True, "query_config": { "grounding_level": 0.2, "search_weight": 60, "keyword_threshold": 0.6, "semantic_threshold": 0.8, "inline_citations": True } } }] messages = [{"role": "user", "content": "What are the key features of our product?"}] response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto" ) print(response.choices[0].message.content) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the Writer client const client = new Writer(); // Configure Knowledge Graph tool with query parameters const tools = [{ type: "graph", function: { description: "Search company knowledge base", graph_ids: [""], subqueries: true, query_config: { grounding_level: 0.2, search_weight: 60, keyword_threshold: 0.6, semantic_threshold: 0.8, inline_citations: true } } }]; const messages = [{ role: "user", content: "What are the key features of our product?" }]; const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, tool_choice: "auto" }); console.log(response.choices[0].message.content); ``` > [!NOTE] > > Find your Knowledge Graph ID using one of these methods: > > * Call the [Knowledge Graph list endpoint](/api-reference/kg-api/list-graphs) to retrieve all Knowledge Graphs with their IDs. > * Locate the ID in the URL of the Knowledge Graph page in [Control Center](https://app.writer.com/controlcenter). > > Both org-wide Knowledge Graphs and Knowledge Graphs [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5) are accessible via the API and SDK. When a Knowledge Graph is deployed to specific teams, list it with the `team_ids` query parameter or use a team-scoped API key to see it. For more detail, see [Create and manage a Knowledge Graph](/home/knowledge-graph). ## Configure request parameters | Name | Type | Range | Default | Description | | - | - | - | - | - | | `max_subquestions` | Integer | 1-10 | 6 | Maximum number of sub-questions to generate when processing complex queries. Set higher to improve detail, set lower to reduce response time. See [Max sub-questions](#max-sub-questions) for details. | | `search_weight` | Integer | 0-100 | 50 | Controls the balance between keyword and semantic search in ranking results. See [Search weight](#search-weight) for details. | | `grounding_level` | Number | 0.0-1.0 | 0.0 | Controls how closely responses must match to source material. Set lower for grounded outputs, higher for creativity. See [Grounding level](#grounding-level) for details. | | `max_snippets` | Integer | 5-25 (recommended) | 30 | Maximum number of text snippets to retrieve from the Knowledge Graph for context. Works in concert with `search_weight` to control best matches vs broader coverage. **Note**: While technically supports 1-60, values below 5 may return no results due to RAG implementation. Recommended range is 5-25. See [Max snippets](#max-snippets) for details. | | `max_tokens` | Integer | 100-8000 | 4000 | Maximum number of tokens the model can generate in the response. See [Max tokens](#max-tokens) for details. | | `keyword_threshold` | Number | 0.0-1.0 | 0.7 | Threshold for keyword-based matching when searching Knowledge Graph content. Set higher for stricter relevance, lower for broader range. See [Keyword threshold](#keyword-threshold) for details. | | `semantic_threshold` | Number | 0.0-1.0 | 0.7 | Threshold for semantic similarity matching when searching Knowledge Graph content. Set higher for stricter relevance, lower for broader range. See [Semantic threshold](#semantic-threshold) for details. | | `inline_citations` | Boolean | True/False | False | Whether to include inline citations within the response text. This is only available when making direct Knowledge Graph queries via the `/v1/graphs/question` endpoint. See [Work with inline citations in Knowledge Graph responses](/home/inline-citations) for details. | ## Parameter details ### Inline citations When you enable `inline_citations: true`, the response includes source references directly in the text as `[filename.pdf](cite_id)` links. These citations correspond to entries in the `references` array, allowing you to verify information and trace claims back to their origins. **Key features**: * **Source verification**: Each citation links to specific source material * **Transparency**: Users can see exactly which sources support each claim * **Traceability**: Citations include unique identifiers for programmatic processing For detailed information about working with inline citations, see [Work with inline citations in Knowledge Graph responses](/home/inline-citations). ### Max sub-questions Maximum number of sub-questions to generate when processing complex queries. Higher values allow the system to break down complex questions into more detailed sub-queries. **How it works**: * **Higher values**: Improve detail by generating more sub-questions for thorough analysis * **Lower values**: Reduce response time by generating fewer sub-questions **When to adjust**: * **Increase** for complex, multi-part questions that need thorough analysis * **Decrease** for simple, direct questions to reduce processing time ### Search weight Controls the balance between keyword and semantic search in ranking results. **How it works**: * **Higher values (closer to 100)**: Prioritize keyword-based matching * **Lower values (closer to 0)**: Prioritize semantic similarity matching **When to adjust**: * **Increase** for searches where exact keyword matches matter most * **Decrease** for searches where conceptual similarity is more important ### Grounding level Controls how closely responses must be tied to source material. This is different from typical LLM temperature parameters. It specifically controls grounding to Knowledge Graph sources. **How it works**: * **Higher values**: Higher creativity - allow more creative interpretation of source material * **Lower values (closer to 0.0)**: Grounded outputs - stick closely to source material with minimal creativity **Examples**: * `0.0`: "According to the documentation, the API supports JSON responses" (direct quote/paraphrase) * `0.5`: "The API documentation indicates that JSON responses are supported, which suggests additional capabilities" (interpretive) * `1.0`: "Based on the available information, users can expect JSON responses, though other formats might be possible" (highly interpretive) **When to adjust**: * **Increase** for higher creativity when you want more interpretive responses * **Decrease** for grounded outputs when factual reporting or accuracy is critical ### Max snippets Maximum number of text snippets to retrieve from the Knowledge Graph for context. Works in concert with `search_weight` to control best matches vs broader coverage. **How it works**: * **Lower values (5-15)**: Best matches - retrieve fewer, more relevant snippets * **Higher values (15-25)**: Broader coverage - retrieve more snippets for comprehensive context * **Values below 5**: May return no results due to RAG implementation limitations **Important notes**: * **Recommended range**: 5-25 (default is 30, which is higher than recommended) * **Edge case**: Due to RAG system behavior, you may see more snippets than requested. Use the recommended range unless you have a measured need to change it. **When to adjust**: * **Increase** for broader coverage when you need comprehensive research or more context * **Decrease** for best matches when you want focused queries or concise results ### Max tokens Maximum number of tokens the model can generate in the response. This controls the length of the AI's answer. **How it works**: * **Higher values**: Allow longer, more detailed responses * **Lower values**: Generate shorter, more concise responses **When to adjust**: * **Increase** for detailed analysis or comprehensive answers * **Decrease** for quick summaries or when you need faster responses ### Keyword threshold Threshold for keyword-based matching when searching Knowledge Graph content. **How it works**: * **Higher values**: Stricter relevance - require stronger keyword matches * **Lower values**: Broader range - allow more lenient keyword matching **When to adjust**: * **Increase** for stricter relevance when you want very precise keyword matches * **Decrease** for broader range when you want to include content with related but not exact keywords ### Semantic threshold Threshold for semantic similarity matching when searching Knowledge Graph content. **How it works**: * **Higher values**: Stricter relevance - require stronger semantic similarity * **Lower values**: Broader range - allow more lenient semantic matching **Examples**: * `0.9`: Very strict - only content with high semantic similarity (for example, searching "user authentication" only finds content about "user authentication", "login", "sign-in") * `0.7`: Moderate - includes conceptually related content (for example, searching "user authentication" finds "authentication", "security", "access control", "user management") * `0.3`: Lenient - includes tangentially related content (for example, searching "user authentication" finds "authentication", "security", "user management", "database", "API", "web development") **When to adjust**: * **Increase** for stricter relevance when you want very semantically similar content * **Decrease** for broader range when you want to include tangentially related content ## Parameter interactions and performance ### How parameters work together Some parameters interact in ways that affect both results and performance: * **`max_snippets` and `search_weight`**: Work together to control best matches vs broader coverage. `max_snippets` controls how many snippets are fed to the LLM in RAG. * **`max_snippets` and `max_tokens`**: `max_snippets` controls input context size, while `max_tokens` controls output response length. * **`keyword_threshold` and `semantic_threshold`**: Both filters are applied - content must pass both thresholds to be included. * **Search weight and thresholds**: Higher thresholds reduce the candidate pool, then search weight determines the balance between keyword and semantic ranking of remaining results. #### Search weight versus semantic threshold These two parameters work at different stages of the search process: * Semantic threshold is applied during the initial search phase, before ranking * Search weight is applied after filtering, when ranking the remaining results Semantic threshold acts as a gatekeeper that determines which content gets included, while search weight controls the balance between keyword and semantic scoring in final ranking. **Example**: with `semantic_threshold = 0.8` and `search_weight = 30`, you get a small set of very relevant documents ranked more by semantic similarity than keyword matching. ### Performance considerations * **Higher `max_tokens`**: Increases processing time and cost * **Lower thresholds**: May return more results but with lower relevance * **Higher `max_subquestions`**: Increases processing time for complex queries * **`inline_citations: true`**: Minimal performance impact, slight increase in response size ### Recommended starting values For most use cases, use the default values and adjust only if you need specific behavior. The defaults are designed to work well for general Knowledge Graph queries. ## Usage examples ### Chat completions with Knowledge Graph tool ```bash cURL theme={null} curl --location --request POST 'https://api.writer.com/v1/chat' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header 'Content-Type: application/json' \ --data-raw '{ "model": "palmyra-x5", "messages": [ { "role": "user", "content": "What are the key features of our product?" } ], "tools": [ { "type": "graph", "function": { "description": "Search company knowledge base", "graph_ids": [""], "subqueries": true, "query_config": { "grounding_level": 0.2, "search_weight": 60, "keyword_threshold": 0.6, "semantic_threshold": 0.8, "inline_citations": true } } } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client client = Writer() # Configure Knowledge Graph tool with query parameters tools = [{ "type": "graph", "function": { "description": "Search company knowledge base", "graph_ids": [""], "subqueries": True, "query_config": { "grounding_level": 0.2, "search_weight": 60, "keyword_threshold": 0.6, "semantic_threshold": 0.8, "inline_citations": True } } }] messages = [{"role": "user", "content": "What are the key features of our product?"}] response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto" ) print(response.choices[0].message.content) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the Writer client const client = new Writer(); // Configure Knowledge Graph tool with query parameters const tools = [{ type: "graph", function: { description: "Search company knowledge base", graph_ids: [""], subqueries: true, query_config: { grounding_level: 0.2, search_weight: 60, keyword_threshold: 0.6, semantic_threshold: 0.8, inline_citations: true } } }]; const messages = [{ role: "user", content: "What are the key features of our product?" }]; const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, tool_choice: "auto" }); console.log(response.choices[0].message.content); ``` ### Direct Knowledge Graph query ```bash cURL theme={null} curl --location --request POST 'https://api.writer.com/v1/graphs/question' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --header 'Content-Type: application/json' \ --data-raw '{ "graph_ids": [""], "question": "What are the key features of our product?", "query_config": { "grounding_level": 0.2, "keyword_threshold": 0.6, "semantic_threshold": 0.8, "inline_citations": true } }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client client = Writer() # Query Knowledge Graph with configuration parameters response = client.graphs.question( graph_ids=[""], question="What are the key features of our product?", query_config={ "grounding_level": 0.2, "keyword_threshold": 0.6, "semantic_threshold": 0.8, "inline_citations": True } ) print(f"Answer: {response.answer}") print(f"References: {response.references}") ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the Writer client const client = new Writer(); // Query Knowledge Graph with configuration parameters const response = await client.graphs.question({ graph_ids: [""], question: "What are the key features of our product?", query_config: { grounding_level: 0.2, keyword_threshold: 0.6, semantic_threshold: 0.8, inline_citations: true } }); console.log(`Answer: ${response.answer}`); console.log(`References: ${response.references}`); ``` ## Common configuration patterns ### Research and analysis Use this configuration for comprehensive research tasks where you need thorough analysis with source verification. Higher sub-questions and snippets provide more context, while inline citations help track sources. ```json theme={null} { "max_subquestions": 8, "search_weight": 60, "grounding_level": 0.1, "max_snippets": 50, "max_tokens": 7000, "keyword_threshold": 0.6, "semantic_threshold": 0.7, "inline_citations": true } ``` ### Quick answers Use this configuration for fast, focused responses where speed and precision matter more than comprehensive analysis. Strict thresholds ensure high relevance with minimal processing time. ```json theme={null} { "max_subquestions": 3, "search_weight": 80, "grounding_level": 0.0, "max_snippets": 15, "max_tokens": 2000, "keyword_threshold": 0.8, "semantic_threshold": 0.8, "inline_citations": false } ``` ### Creative content generation Use this configuration when you want the AI to interpret and build upon source material creatively. Lower thresholds allow more diverse content, while higher grounding level enables interpretive responses. ```json theme={null} { "max_subquestions": 6, "search_weight": 40, "grounding_level": 0.6, "max_snippets": 30, "max_tokens": 5000, "keyword_threshold": 0.5, "semantic_threshold": 0.6, "inline_citations": false } ``` ## Best practices 1. **Start with defaults**: Begin with the default configuration and adjust based on your specific needs 2. **Test incrementally**: Change one parameter at a time to understand its effect 3. **Consider your use case**: Different applications, like research, Q\&A, and content generation, benefit from different configurations 4. **Monitor performance**: Track how different configurations affect response quality and processing time 5. **Balance precision and recall**: Higher thresholds give more precise results but may miss relevant content ## Next steps * Learn how to [work with inline citations](/home/inline-citations) for source verification and traceability * Explore [Knowledge Graph tools](/home/kg-chat) for chat completions * Check out [direct Knowledge Graph queries](/home/kg-query) for programmatic access * See [Knowledge Graph management](/home/knowledge-graph) for creating and organizing your graphs # Create and manage Knowledge Graphs Source: https://dev.writer.com/home/knowledge-graphs # Language support Source: https://dev.writer.com/home/language_support Palmyra LLM supports 30+ languages including Arabic, French, Spanish, Hindi, and Chinese. View MMLU and BLEU benchmark scores for multilingual text generation. Writer Palmyra LLM supports over 30 languages, including Arabic, French, Spanish, Hindi, Simplified Chinese, Traditional Chinese, and more. This page provides an overview of capabilities, performance benchmarks, and prompting examples on how to use these features. When it comes to multi-language capabilities, there are two primary categories to consider: generation and translation. Generation typically refers to the ability to understand/create content, answer questions, and converse, all within the same language. Translation typically refers to the ability to transform text to and from English, where either the input or output language is English. This page displays two of the many benchmarks used to evaluate multi-language performance in Palmyra LLMs. Writer Palmyra has the highest performance of any production LLM in the Holistic Evaluation of Language Models, an LLM evaluation framework developed by Stanford CRFM to serve as a living benchmark for the community, continuously updated with new scenarios, metrics, and models. While there are limited benchmarks available for evaluating text generation and translation in different languages, Palmyra has achieved some of the highest scores in both MMLU (Massive Multitask Language Understanding) and BLEU (Bilingual Evaluation Understudy) for other languages. One benchmark that Writer uses to evaluate text generation performance is [MMLU](https://arxiv.org/abs/2009.03300). The [MLMM evaluation](https://arxiv.org/pdf/2307.16039.pdf) covers 57 tasks including elementary mathematics, U.S. history, computer science, law, and more. To attain high accuracy on this test, models must possess extensive world knowledge and problem-solving ability. One benchmark that Writer uses to evaluate text translation performance is [BLEU](https://aclanthology.org/P02-1040.pdf). [Any BLEU score higher than 60](https://cloud.google.com/translate/automl/docs/evaluate#interpretation) indicates a higher quality translation than a human translation. While Palmyra's core competency lies in the text generation realm, translation use cases are possible. However, it's important to exercise caution in languages where benchmarks aren't yet established. The team values transparency, and potential users should be aware of this caveat. Therefore, any outputs or usage of Writer LLM should always include guidance from a human expert. The team continuously evaluates and refines capabilities, and learning happens with customers. | Language | MMLU/MLMM | BLEU (source \ English) | | :- | :- | :- | | Arabic | 68.9 | 61.2 | | Bengali | 63.3 | 54.4 | | Bulgarian | 76.3 | 64.2 | | Chinese simplified | 71.7 | 63.8 | | Chinese traditional | 73.7 | 57.0 | | Croatian | 64.9 | 66.4 | | Czech | - | 52.5 | | Danish | 77.7 | 70.5 | | Dutch | 73.6 | 73.9 | | English | 70.2 | - | | Finnish | - | 68.9 | | French | 69.1 | 63.1 | | German | 70.4 | 71.3 | | Greek | - | 60.4 | | Hebrew | - | 67.8 | | Hindi | 77.9 | 68.4 | | Hungarian | 67.7 | 65.3 | | Indonesian | 67.8 | 63.5 | | Italian | 72.5 | 70.9 | | Japanese | 73.5 | 66.8 | | Korean | - | 56.8 | | Lithuanian | - | 59.3 | | Polish | - | 60.6 | | Portuguese | - | 66.2 | | Romanian | 70.9 | 67.6 | | Russian | 75.1 | 65.2 | | Spanish | 72.5 | 79.3 | | Swahili | - | 62.8 | | Swedish | - | 63.2 | | Thai | - | 54.7 | | Turkish | 64.1 | 57.5 | | Ukrainian | 75.2 | 68.0 | | Vietnamese | 72.5 | 60.3 | # Dialect support Writer Palmyra LLM also supports outputting in specific language dialects. The best results come from using a prompt with the following characteristics: 1. The prompt itself is in the desired language and dialect 2. The prompt clearly describes the type of dialect, for example, "It's essential that you use the Spanish spoken in Spain." 3. The prompt provides specific examples of the dialect, both vocabulary and grammatical differences The following example, although not in the desired language for simplicity's sake, is an example of an optimal prompt that asks for a translation in Spanish spoken in Spain. ```text theme={null} Hello, good afternoon! I need you to help me translate the following text. It's essential that you use the Spanish spoken in Spain. For example, you should use words like "coche" and/or "patata" instead of "carro" and/or "pap." Additionally, you need to pay attention to grammatical differences, such as the use of "voy a por" (Spain) instead of "voy por" (Latin America), or the structure of sentences like "hoy he comido una manzana" instead of "hoy comí una manzana." I prefer that you use "vosotros" (speak) instead of "ustedes" (speak), unless it's necessary to write very formally. ``` > Here is the text to translate:\ > \[text you want translated] ``` ## Basic prompt examples ### Translation > Read the content of this source. Provide me with a translation of all its contents in French: https://writer.com/blog/ai-guardrails/ ### Text generation > Please write a blog post about the importance of productivity for small businesses in Arabic. ### Native multi-language support > 人工知能の歴史と大規模言語モデルの開発について、短い段落を書いてください。読者はビジネステクノロジーニュースに興味がありますが、技術的なバックグラウンドはありません。技術的な概念を8年生の読解レベルで簡潔に説明してください。 ``` # Export logs Source: https://dev.writer.com/home/logs-export Poll captured LLM-call, agent-run, and agent-feedback records with the Logs Export API, and resume the feed from a cursor. This guide shows you how to poll captured LLM-call, agent-run, and agent-feedback records with the Logs Export API. After you connect a poller or an incremental connector, you can land those records in a data warehouse, SIEM, or analytics platform. By default, the logs endpoint responds with [OpenTelemetry Protocol (OTLP)](https://opentelemetry.io/docs/specs/otlp/) JSON that follows the [OpenTelemetry semantic conventions for generative AI](https://github.com/open-telemetry/semantic-conventions-genai) (`gen_ai.*` attributes), alongside Writer-specific attributes under `writer.*`. Set `format=native` to receive a Writer-native JSON shape instead. The agent-feedback endpoint only emits native JSON. ## Prerequisites Before you export logs, make sure you have: * A Writer API key. See instructions in the [API keys guide](/api-reference/api-keys). ## Call the export endpoint Request logs for one organization. **URL:** `GET https://api.writer.com/api/observability/v1/organization/{organizationId}/logs/export` Omit `cursor` and `start_date` to start at the current time. Only newly settled rows stream forward. ```bash cURL theme={null} curl --get --location \ "https://api.writer.com/api/observability/v1/organization//logs/export" \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data-urlencode "order=tail" \ --data-urlencode "format=native" \ --data-urlencode "limit=1000" ``` ```python Python theme={null} import os import requests organization_id = "" api_key = os.environ["WRITER_API_KEY"] response = requests.get( "https://api.writer.com/api/observability/v1/organization/" f"{organization_id}/logs/export", headers={"Authorization": f"Bearer {api_key}"}, params={"order": "tail", "format": "native", "limit": 1000}, timeout=60, ) response.raise_for_status() print(response.json()) print(response.headers["x-next-cursor"]) ``` ```javascript JavaScript theme={null} const organizationId = ""; const apiKey = process.env.WRITER_API_KEY; const params = new URLSearchParams({ order: "tail", format: "native", limit: "1000", }); const response = await fetch( `https://api.writer.com/api/observability/v1/organization/${organizationId}/logs/export?${params}`, { headers: { Authorization: `Bearer ${apiKey}` } }, ); if (!response.ok) { throw new Error(`Export request failed with status ${response.status}`); } const body = await response.json(); console.log(body); console.log(response.headers.get("x-next-cursor")); ``` ## Authenticate requests Send the Writer API key on every request. ```http theme={null} Authorization: Bearer ``` Each key is bound to a single organization and can export logs only for that organization. A request that uses a key against a different `organizationId` returns `403 Forbidden`. The gateway or API-key verifier can also reject access; body export still requires an authorized organization-scoped API key. ## Choose a start point You choose where the stream begins. After the first response, page with the cursor alone. The cursor already encodes your position. ### Start from the current time Call the endpoint with `order=tail` and neither `cursor` nor `start_date`. The stream starts at the current time, with no backfill. ### Backfill from a date Pass `start_date` with `order=tail` to request retained records from that ingestion time, then continue polling after the backlog drains. `start_date` accepts an ISO-8601 timestamp, epoch seconds, or epoch milliseconds. For example, `start_date=2026-07-01T00:00:00Z`. Available history depends on source telemetry and completed backfills; this does not guarantee full historical coverage. ### Stay inside the retention window A `start_date` older than the retention window (90 days by default) returns `400 Validation Error`. The `detail` field includes the window length and the earliest allowed ISO date. The API returns that error instead of truncating the backfill. ### Page with the cursor alone After you store `x-next-cursor`, send it as the `cursor` query parameter and omit `start_date`. Sending `start_date` together with `cursor` returns `400` because the cursor already encodes the position. ## Set query parameters These parameters control paging, the response shape, and filters. Filters apply in tail mode and keep `(inserted_at, log_id)` order across pages. Call filters qualify agent runs through matching LLM calls. | Parameter | Values | Default | Description | | - | - | - | - | | `order` | `browse`, `tail` | `browse` | `tail` selects the incremental stream. | | `cursor` | Opaque string | None | Resume token from a prior `x-next-cursor` header. Tail only. | | `start_date` | ISO-8601, epoch seconds, or epoch milliseconds | Tail: now; browse: now minus 90 days if both dates are omitted | Tail backfill start, mutually exclusive with `cursor`. Browse window start. | | `end_date` | ISO-8601, epoch seconds, or epoch milliseconds | Browse: now if both dates are omitted | Browse window end. Rejected when `order=tail`. | | `cursor_started_at_ms` | Integer ≥ 0 | None | Browse-only continuation timestamp. Send together with `cursor_log_id`. | | `cursor_log_id` | String | None | Browse-only continuation ID. Send together with `cursor_started_at_ms`. | | `limit` | Integer ≥ 1 | `100` | Page size. Clamped to 1000. With `include_bodies=true`, set `limit` to 50 or less. The default of 100 returns `400`. | | `format` | `otlp`, `native` | `otlp` | Response body shape. | | `signal` | `traces`, `logs` | `traces` | OTLP only. `traces` returns `resourceSpans`. `logs` returns `resourceLogs`. | | `include_bodies` | Boolean | `false` | Requests available prompt and response bodies for LLM calls. Run records have no bodies. | | `model` | String, repeatable | None | Filter by model. Repeat the parameter to pass more than one value. | | `created_by` | String, repeatable | None | Filter by user ID. Repeat the parameter to pass more than one value. | | `source` | `llm_gateway`, `writer_agent`, `other`, repeatable | None | Filter by source. `writer_agent` is WRITER Agent. Repeat the parameter to pass more than one value. | | `provider` | String | None | Filter by provider. | | `status` | String | None | Filter by status. | | `finish_reason` | String | None | Filter by finish reason. | | `guardrail_outcome` | String | None | Filter by guardrail outcome. | | `search` | String | None | Searches metadata such as request, session, run, root-run, and user IDs, and model. Does not search raw prompt or response text. | For `order=browse`, provide both `start_date` and `end_date`, or omit both. Providing only one date returns `400 Validation Error`. For `order=browse`, continue with both `cursor_started_at_ms` and `cursor_log_id`. Read them from `pagination.next_cursor` with `format=native`, or from `x-next-cursor-started-at-ms` and `x-next-cursor-log-id` with `format=otlp`. The opaque `cursor` is tail-only, and the two-part browse parameters are rejected in tail mode. > [!WARNING] > > API-key callers receive unmasked bodies when you request `include_bodies=true`, > even if content masking is enabled in Control Center. The UI masking setting is not > a privacy boundary for API-key exports. User-token detail requests separately > follow the organization masking setting and remain masked if that setting > cannot be resolved. ## Read the response Tail responses put the resume token and the caught-up signal in headers. The body shape depends on `format`. ### Read response headers Use these headers to resume and decide when the settled backlog is drained. Native `pagination.has_more` matches `x-has-more`. In tail mode, native `pagination.next_cursor` is `null`; read the resume token from `x-next-cursor`. Tail responses omit `total_count`, `total_count_is_capped`, and total-count headers. Browse-only bounded counts appear in those native fields, or in `x-total-count` and `x-total-count-is-capped` for OTLP. These counts are not tail catch-up signals. | Header | Meaning | | - | - | | `x-next-cursor` | Opaque resume token. Present on every tail response. After a full page it points past the last row. On a caught-up page it repeats the current position. Store it and send it on the next request. Use `x-has-more` to decide whether more rows are ready. | | `x-has-more` | `true` when another page is available. `false` when the stream is caught up to the settled boundary. | | `x-tail-watermark` | Settled boundary in epoch milliseconds. The boundary is now minus a 5-minute settle lag. Rows with `inserted_at` newer than this value are withheld from the page. | | `retry-after` | Seconds to wait. Present only on `429`. | ### Read a native body With `format=native`, the body is a JSON object containing heterogeneous rows. `result[].inserted_at_ms` and `result[].log_id` are the two components of the tail ordering axis. Upsert by `log_id`, retaining the revision with the newest `inserted_at_ms`. This example shows selected fields from an LLM call and an agent run: ```json theme={null} { "result": [ { "record_type": "llm_call", "log_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "inserted_at_ms": 1734600000000, "model": "palmyra-x5", "duration_ms": 1200 }, { "record_type": "agent_run", "log_id": "agent-run:run-123", "inserted_at_ms": 1734600001000, "agent_run_id": "run-123", "root_agent_run_id": "run-123", "run_status": "completed", "duration_ms": null, "model": "", "prompt_tokens": null, "completion_tokens": null, "total_tokens": null } ], "pagination": { "limit": 1000, "has_more": true, "next_cursor": null } } ``` #### Distinguish calls and runs Use `record_type` to distinguish `llm_call` from `agent_run`. The fields describe different units of work: | Field | LLM call | Agent run | | - | - | - | | `log_id` | Call identity | Stable `agent-run:` identity | | `started_at_ms` | Call start timestamp | Terminal event timestamp | | `duration_ms` | Call duration | Execution-leg lifecycle duration, or `null` | | `model` | Inference model | Empty string | | Token fields | Inference token counts | `null` | | `has_body` | Whether the call has a body | `false` | Run rows describe terminal execution legs with a qualifying LLM call. Still-running and tool-only legs are excluded. Runs have no inference model, token, or body values. #### Interpret run duration A run's `duration_ms` is lifecycle timing for that execution leg. It is not: * A sum of call latency * A session total * Exact user-visible latency Missing or ambiguous timing remains `null`; do not infer a duration or replace it with zero. Parent, child, and resumed legs remain separate records. There is no session-total record. #### Correlate records Correlate records using `agent_run_id`, `root_agent_run_id`, `request_id`, and `session_id` where present. A root ID does not guarantee a user turn or identify a subagent role. Uncorrelated calls remain exportable. Late lifecycle events or call correlation can revise the same run identity. Accept later revisions rather than permanently discarding known IDs. See [Apply delivery guarantees](#apply-delivery-guarantees). #### Handle unavailable bodies When you request `include_bodies=true`, an unavailable call body is `null` with a `body_unavailable_reason`. The reason codes distinguish: * **Capture:** `not_captured` * **Processing or retrieval:** `pending`, `missing`, `failed` * **Authorization:** `ekm_denied`, `unauthorized` * **Retention or deletion:** `expired`, `deleted` * **Other unavailability:** `unavailable` These conditions are distinct from masking. Run records return `body: null` without hydration or an unavailable-body reason. ### Interpret watermark request observations Where available, LLM-call records include nullable observations of the actual outbound watermark request: | Field | Meaning | | - | - | | `watermark_model_supported` | Whether the resolved managed provider/model supports Writer watermark parameters, independent of organization enablement. | | `watermark_parameters_present` | `true` for observed parameters, `false` for observed absence, and `null` when capture is unavailable or malformed. | | `watermark_enabled` | The actual sent enabled value; `null` when absent or unavailable. | | `watermark_delta` | The actual sent number, including zero; never reconstructed from saved policy. | | `watermark_degree` | The low/medium/high degree from the same resolution that generated the parameters sent; `null` for replacement parameters or when that evidence is unavailable. | | `watermark_payload_bit_length` | The actual nonempty binary wire-message length; `null` for missing, empty, nonstring or nonbinary messages. Only the integer is retained. | Missing historical fields remain unknown, not disabled. An omitted parameter object does not identify why it was omitted. Agent-run rows have no corresponding provider attempt and carry null facts. These six request observations do not establish that the output was watermarked; no application-status field is reported. OTLP omits unknown `writer.watermark_*` attributes. Hash keys, wire messages/codes, labels and the original watermark object are excluded, including from protected bodies. Existing access and masking rules remain unchanged. Existing model-visibility rules can also withhold watermark metadata. In that case all six facts are null, including the support and parameter-presence booleans. A null value is not evidence that watermarking was unsupported, disabled or absent. These metadata rules do not expand access to protected request or response content. ### Read an OTLP body With `format=otlp` (the default), the body is an [OTLP/JSON](https://opentelemetry.io/docs/specs/otlp/#otlphttp) payload. Choose the body shape with `signal`: | Signal | Top-level field | | - | - | | `traces` (default) | `resourceSpans` | | `logs` | `resourceLogs` | Pagination stays in the response headers. In tail mode, use `x-next-cursor`, `x-has-more`, and `x-tail-watermark`. Agent runs become `writer.agent.run` spans with kind `INTERNAL`, or log records with event name `writer.agent.run.terminal`. Spans end at the terminal event time and start at that time minus the run duration. Unknown duration produces a point span without `writer.agent.run.duration_ms`; that does not mean the run took zero time. Run spans and logs expose stable `writer.record.id` and correlation attributes. They do not include inference model, token, or body attributes. #### Follow the OpenTelemetry semantic conventions for generative AI Attributes on LLM-call spans follow the [OpenTelemetry semantic conventions for generative AI](https://github.com/open-telemetry/semantic-conventions-genai) where one exists, with `gen_ai.*` names such as `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, and `gen_ai.usage.output_tokens`. Prompt and response bodies, when included, follow the OpenTelemetry generative AI message schemas on `gen_ai.input.messages` and `gen_ai.output.messages`. These conventions are still in development; expect additive changes over time. Writer-specific attributes keep the `writer.` prefix. Agent-run spans use the span name `writer.agent.run`, log records use the event name `writer.agent.run.terminal`, and both carry the stable `writer.record.id` and, when known, `writer.agent.run.duration_ms`. ## Store and resend the cursor The tail cursor is a versioned, HMAC-signed token. Treat it as an opaque string. Store it verbatim and send it back unchanged on the `cursor` parameter. > [!WARNING] > > Do not parse, truncate, or reconstruct the cursor. A tampered or > version-incompatible token returns `400 Validation Error` with detail `Invalid > tail cursor`. ## Apply delivery guarantees Tail mode is an ordered revision feed. The settlement delay does not make a record immutable, and a cursor identifies a position rather than a fixed snapshot. * **Ordering.** Rows return in `(inserted_at ASC, log_id ASC)` order. Replaying a cursor returns no row that ordered before that cursor. * **Settled window.** A page contains only rows whose `inserted_at` is at or before `x-tail-watermark`. The watermark is now minus a 5-minute settle lag. A row with an older event time and a newer `inserted_at` arrives when the watermark passes that `inserted_at`. Settlement is not record finality. * **Revision-aware upserts.** Retries, overlapping workers, and later revisions can deliver the same `log_id` again. Upsert on `log_id`, retaining the newest `inserted_at_ms`, so an older replay cannot overwrite a newer revision. Never permanently discard an ID because you have already seen it. * **Replay.** Replaying a cursor can observe newer rows at or after that position. After the stream is caught up, polling again can return newly settled rows. Missing source telemetry is not reconstructed, and the feed does not promise lossless real-time delivery. ## Stay within limits Each organization has a fixed window of 120 requests per 60 seconds by default. A request over that limit returns `429 Rate Limited` with a `retry-after` header. The value is the whole seconds until the window resets, with a minimum of one second. The limit is checked before authentication. Wait for `retry-after`, then retry. `limit` is clamped to 1000. A larger value is reduced to 1000. When `include_bodies=true`, set `limit` to 50 or less. The default of 100 is above that maximum and returns `400 Validation Error`. ## Handle errors Service error bodies use the Problem+JSON shape, with `code` and `detail`. Gateway authentication errors can use a different envelope: an unauthenticated public request can return `401` with generic JSON rather than the service Problem+JSON shape. Handle the HTTP status even when the body does not contain a service error code. | Status | Code | When | | - | - | - | | `400` | `VALIDATION_ERROR` | Tampered or version-incompatible cursor. `start_date` older than retention. `end_date` with tail. `cursor` with browse. `start_date` with `cursor`. Only one browse date bound. Incomplete browse cursor pair or browse cursor parameters with tail. `include_bodies=true` with `limit` above 50. | | `401` | `UNAUTHORIZED` or gateway-specific | Missing, malformed or rejected credentials at the public authentication boundary. | | `403` | `FORBIDDEN` or gateway-specific | The key targets a different organization, or the gateway/verifier denies access. | | `429` | `RATE_LIMITED` | The per-organization rate limit is exceeded. The response includes `retry-after`. | ## Poll for new logs Poll with the returned `x-next-cursor` to pick up newly settled rows and revisions: * **Drain and pause:** Drain settled pages until `x-has-more` is `false`, then pause before polling again. * **Upsert revisions:** Upsert by `log_id`, retaining the newest `inserted_at_ms`. A primary key alone does not prevent older retries from overwriting newer revisions. * **Persist cursor:** Save the cursor only after the complete page is successfully processed. Restart from that saved cursor. These examples keep the cursor in memory only. * **Handle rate limits:** On `429`, wait for `retry-after` before retrying. The 30-second pause in these examples applies after the stream is caught up. The Python and JavaScript examples emit each complete row revision as JSON to stdout. The cURL example prints each response body. ```bash cURL theme={null} #!/usr/bin/env bash set -euo pipefail organization_id="" poll_interval_seconds=30 cursor="" base_url="https://api.writer.com/api/observability/v1/organization/${organization_id}/logs/export" while true; do headers_file=$(mktemp) body_file=$(mktemp) args=( --silent --show-error --get --location --output "$body_file" --dump-header "$headers_file" --header "Authorization: Bearer ${WRITER_API_KEY}" --data-urlencode "order=tail" --data-urlencode "format=native" --data-urlencode "limit=1000" ) if [[ -n "$cursor" ]]; then args+=(--data-urlencode "cursor=${cursor}") fi status=$(curl "${args[@]}" --write-out "%{http_code}" "$base_url") if [[ "$status" == "429" ]]; then retry_after=$(grep -i '^retry-after:' "$headers_file" | tail -n 1 | awk '{print $2}' | tr -d '\r') rm -f "$headers_file" "$body_file" sleep "${retry_after:-1}" continue fi if [[ "$status" != "200" ]]; then echo "Export request failed with status ${status}" >&2 cat "$body_file" >&2 rm -f "$headers_file" "$body_file" exit 1 fi cat "$body_file" echo cursor=$(grep -i '^x-next-cursor:' "$headers_file" | tail -n 1 | cut -d' ' -f2- | tr -d '\r') has_more=$(grep -i '^x-has-more:' "$headers_file" | tail -n 1 | awk '{print $2}' | tr -d '\r') rm -f "$headers_file" "$body_file" if [[ "$has_more" != "true" ]]; then sleep "$poll_interval_seconds" fi done ``` ```python Python theme={null} import json import os import time import requests organization_id = "" api_key = os.environ["WRITER_API_KEY"] poll_interval_seconds = 30 cursor = None url = ( "https://api.writer.com/api/observability/v1/organization/" f"{organization_id}/logs/export" ) while True: params = {"order": "tail", "format": "native", "limit": 1000} if cursor: params["cursor"] = cursor response = requests.get( url, headers={"Authorization": f"Bearer {api_key}"}, params=params, timeout=60, ) if response.status_code == 429: retry_after = int(response.headers.get("retry-after", "1")) time.sleep(max(retry_after, 1)) continue response.raise_for_status() for row in response.json()["result"]: print(json.dumps(row), flush=True) cursor = response.headers["x-next-cursor"] if response.headers.get("x-has-more") != "true": time.sleep(poll_interval_seconds) ``` ```javascript JavaScript theme={null} const organizationId = ""; const apiKey = process.env.WRITER_API_KEY; const pollIntervalMs = 30000; let cursor = null; function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function pollLogs() { const url = `https://api.writer.com/api/observability/v1/organization/${organizationId}/logs/export`; while (true) { const params = new URLSearchParams({ order: "tail", format: "native", limit: "1000", }); if (cursor) { params.set("cursor", cursor); } const response = await fetch(`${url}?${params}`, { headers: { Authorization: `Bearer ${apiKey}` }, }); if (response.status === 429) { const retryAfter = Number(response.headers.get("retry-after") ?? "1"); await sleep(Math.max(retryAfter, 1) * 1000); continue; } if (!response.ok) { throw new Error(`Export request failed with status ${response.status}`); } const body = await response.json(); for (const row of body.result) { console.log(JSON.stringify(row)); } cursor = response.headers.get("x-next-cursor"); if (response.headers.get("x-has-more") !== "true") { await sleep(pollIntervalMs); } } } pollLogs(); ``` ## Export agent feedback Stream thumbs up and thumbs down ratings, including optional comments, with the same authentication, cursor, rate limit, and error contract as the logs export. The feedback endpoint returns native JSON only. **URL:** `GET https://api.writer.com/api/observability/v1/organization/{organizationId}/agent-feedback/export` Omit `cursor` and `start_date` to start at the current time. Only newly settled rows stream forward. ```bash cURL theme={null} curl --get --location \ "https://api.writer.com/api/observability/v1/organization//agent-feedback/export" \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data-urlencode "order=tail" \ --data-urlencode "limit=100" ``` ```python Python theme={null} import os import requests organization_id = "" api_key = os.environ["WRITER_API_KEY"] response = requests.get( "https://api.writer.com/api/observability/v1/organization/" f"{organization_id}/agent-feedback/export", headers={"Authorization": f"Bearer {api_key}"}, params={"order": "tail", "limit": 100}, timeout=60, ) response.raise_for_status() print(response.json()) print(response.headers["x-next-cursor"]) ``` ```javascript JavaScript theme={null} const organizationId = ""; const apiKey = process.env.WRITER_API_KEY; const params = new URLSearchParams({ order: "tail", limit: "100", }); const response = await fetch( `https://api.writer.com/api/observability/v1/organization/${organizationId}/agent-feedback/export?${params}`, { headers: { Authorization: `Bearer ${apiKey}` } }, ); if (!response.ok) { throw new Error(`Export request failed with status ${response.status}`); } const body = await response.json(); console.log(body); console.log(response.headers.get("x-next-cursor")); ``` ### Set feedback query parameters The feedback endpoint accepts only the shared paging parameters. It has no filters, no `format` option, and no total counts. | Parameter | Values | Default | Description | | - | - | - | - | | `order` | `browse`, `tail` | `browse` | `tail` selects the incremental stream. | | `cursor` | Opaque string | None | Resume token from a prior `x-next-cursor` header. | | `start_date` | ISO-8601, epoch seconds, or epoch milliseconds | Now | Tail backfill start. Mutually exclusive with `cursor`. | | `end_date` | ISO-8601, epoch seconds, or epoch milliseconds | None | Browse only. Rejected when `order=tail`. | | `limit` | Integer ≥ 1 | `100` | Page size. | Both orders page with the opaque `cursor`. A browse continuation takes its window from the cursor and does not require dates. > [!NOTE] > > Cursors are not interchangeable between endpoints. A cursor issued by the > logs export returns `400 Validation Error` on the feedback endpoint, and a > browse cursor presented with `order=tail` (or the reverse) also returns > `400`. ### Read a feedback response Every response sets `x-next-cursor` and `x-has-more`. Tail responses also set `x-tail-watermark`. The body is always native JSON. ```json theme={null} { "result": [ { "feedback_id": "0b1e…", "message_id": "msg_…", "agent_run_id": "run_…", "root_agent_run_id": "run_…", "workflow_id": null, "rating": "negative", "qualitative_comment": "Missed the second question.", "emitted_at_ms": 1759600000000, "inserted_at_ms": 1759600012345, "user_id": "u_…", "team_id": "t_…", "thread_id": "th_…", "session_id": null, "request_id": "req_…", "action_id": null, "trace_id": "4bf9…", "source_service": "writer-agent" } ], "pagination": { "limit": 100, "has_more": false, "next_cursor": null } } ``` | Field | Type | Notes | | - | - | - | | `feedback_id` | string | Stable identity. Upsert key. A re-rating is a new revision of this ID. | | `message_id` | string | The agent message the feedback is about. | | `agent_run_id` | string \| null | Agent run that produced the message. | | `root_agent_run_id` | string \| null | Root run when the feedback sits in a nested run. | | `workflow_id` | string \| null | Workflow that produced the message, if any. | | `rating` | `positive` \| `negative` | Thumbs up or thumbs down. | | `qualitative_comment` | string \| null | Free text entered by the user. Always included. | | `emitted_at_ms` | integer | Rating event time, epoch ms. Browse ordering axis. | | `inserted_at_ms` | integer | Ingestion time, epoch ms. Tail ordering axis. | | `user_id` | string \| null | User who submitted the feedback. | | `team_id` | string \| null | Team associated with the feedback. | | `thread_id` | string \| null | Conversation thread. | | `session_id` | string \| null | Session ID, if available. | | `request_id` | string \| null | Request ID, if available. | | `action_id` | string \| null | Action ID, if available. | | `trace_id` | string \| null | Trace ID for correlating with logs. | | `source_service` | string \| null | Service that emitted the feedback. | ### Handle re-ratings A user can change their rating or edit the comment. Each change emits a new revision of the same `feedback_id` with a newer `emitted_at_ms`. The two orders surface revisions differently: * **Browse** collapses to one row per `feedback_id`—the revision with the latest `emitted_at_ms`—newest-first by `(emitted_at, feedback_id)` within `[start_date, end_date]`. Feedback first given in one window and re-rated in a later window appears only in the later window. * **Tail** returns every revision as a row, ordered `(inserted_at ASC, feedback_id ASC)`. A re-rated message is redelivered as a second row with the same `feedback_id` and a newer `inserted_at_ms`. Upsert by `feedback_id` and retain the newest `inserted_at_ms` to match the latest-rating view browse provides. A tail page never withholds a revision because an earlier revision was already delivered. The settled watermark (`x-tail-watermark`) is the only completeness boundary. > [!WARNING] > > `qualitative_comment` is free text and may contain whatever the user typed. It > is part of every row with no opt-in parameter and no entitlement check. This > differs from the logs export, where prompt and response bodies require > `include_bodies=true` and the Content Export entitlement. Consumers that must > not land free text downstream should drop the field on ingest. ## Connect Airbyte, Fivetran, or Singer The cursor and caught-up signal are header strings, so an incremental connector can store them as a bookmark. Use `format=native` and read `x-next-cursor` from the header. Emit every revision and configure the destination to upsert on `log_id`, retaining the newest `inserted_at_ms`. Save the bookmark only after the destination processes the page. ### Configure Airbyte Airbyte's [cursor pagination](https://docs.airbyte.com/platform/connector-development/config-based/understanding-the-yaml-file/pagination#cursor) can read a response-header token and inject it into the next request. This handles pages within a sync, not the persisted bookmark needed to resume this feed across scheduled syncs. Use these mappings for pagination within a sync: | Export value | Airbyte mapping | | - | - | | `result` | Record extractor field path | | `x-next-cursor` | `CursorPagination.cursor_value`, read from response headers | | `x-has-more` is `false` | `CursorPagination.stop_condition` | | `cursor` query parameter | `DefaultPaginator.page_token_option` request parameter | | `limit` query parameter | `DefaultPaginator.page_size_option` request parameter | For cross-sync resumption, implement a custom incremental source with the [Airbyte Python CDK](https://docs.airbyte.com/platform/connector-development/cdk-python/incremental-stream). The pagination mappings alone are not a complete connector. The source must: 1. Restore the saved opaque `x-next-cursor` from stream state and send it as `cursor` on the **first request of each sync**. Omit `start_date` when resuming. Without saved state, choose a start point as described in [Choose a start point](#choose-a-start-point). 2. Emit every row in `result`, including revisions of known `log_id` values, before emitting a state message for that page's `x-next-cursor`. Do not advance state after a partially processed page. 3. Continue while `x-has-more` is `true`. When it is `false`, retain the returned `x-next-cursor` for the next scheduled sync, even if the final page is empty. 4. Use Airbyte's [state protocol](https://docs.airbyte.com/platform/understanding-airbyte/airbyte-protocol#state--the-whole-sync): a checkpoint becomes safe to resume from only after the destination acknowledges that all preceding records are committed. Emitting records or state from the source alone is not an acknowledgment. The Writer cursor is opaque, not a timestamp. Do not parse it or substitute `inserted_at_ms` for it. Airbyte's [incremental sync configuration](https://docs.airbyte.com/platform/connector-development/connector-builder-ui/incremental-sync) is not a replacement for restoring this bookmark. [Resumable full refresh](https://docs.airbyte.com/platform/connector-development/cdk-python/resumable-full-refresh-stream#airbytestatemessage) is not cross-sync incremental state either: its state is deleted at the start of a new sync job. Set the record primary key to `log_id` and separately configure revision-aware destination updates that retain the newest `inserted_at_ms`. The primary key alone does not enforce revision ordering. On `429`, honor `retry-after` before retrying. ### Configure Fivetran or Singer Singer taps and Fivetran custom connectors use the same header bookmark. * **Singer.** Persist `x-next-cursor` as the stream replication bookmark in `STATE` after the target processes the page. On the next run, send that value as `cursor`. Emit each revision with `log_id` as the record key and retain the newest `inserted_at_ms` in the target. * **Fivetran.** Loop while `x-has-more` is `true`, emit every revision with `log_id` as the primary key, and retain the newest `inserted_at_ms` at the destination. Store `x-next-cursor` in connector state only after processing the page. ## Review default limits These operational defaults apply to the export stream. To request different values, contact your Customer Success team. | Setting | Default | Effect | | - | - | - | | Settle lag | 5 minutes | Withholds rows newer than now minus the lag; later revisions can still arrive. | | Export retention | 90 days | Oldest `start_date` a tail backfill can request. | | Rate limit (requests) | 120 | Requests per window, per organization. | | Rate limit (window) | 60 seconds | Length of the rate-limit window. | ## Next steps View logs in Control Center, or track organization-wide spend. * [Event logs](/home/event-logs): View, filter, and search request logs in Control Center * [Usage and spend](/home/usage-and-spend): Track organization-wide costs and token consumption # Configure connectors Source: https://dev.writer.com/home/mcp-gateway Configure prebuilt and custom connectors for WRITER Agent to securely access enterprise tools and your own APIs This page covers technical details about configuring connectors for your organization, including authentication setup, access control, and security considerations. Connectors enable WRITER Agent to access enterprise tools and custom APIs through Writer's Model Context Protocol (MCP) gateway. Writer provides two types of connectors: * **Prebuilt connectors**: Ready-to-use integrations with popular enterprise tools like Slack and Google Workspace * **Custom connectors**: Connectors you create from OpenAPI specifications or MCP servers to integrate with internal tools and third-party services After you configure connectors in Control Center, users in your organization can connect to them through [WRITER Agent](https://app.writer.com/). For step-by-step connector configuration instructions, see [Setting up connectors](https://support.writer.com/article/299-setting-up-connectors) in the Writer Help Center. > [!WARNING] > > MCP connectors are currently available for [WRITER > Agent](https://app.writer.com/). Connectors do not currently support Agent > Builder, no-code agents, or API integrations. ## How MCP gateway works Writer's MCP gateway sits between WRITER Agent and connector servers (both prebuilt and custom). This architecture provides centralized security, access control, and observability for enterprise deployments. All connector requests—whether prebuilt or custom—flow through the MCP gateway. Connector requests flow through the following steps: 1. **Client connection**: WRITER Agent connects to Writer's unified MCP server 2. **Request submission**: WRITER Agent sends HTTP requests to the MCP gateway endpoint 3. **Authentication**: The gateway validates user identity and permissions using your Writer organization's access controls 4. **Request routing**: Authenticated requests are routed to the appropriate partner MCP server 5. **Response delivery**: Results are returned to the agent through the secure channel ```mermaid theme={null} sequenceDiagram participant Agent as WRITER Agent participant Gateway as MCP Gateway
(Writer) participant Auth as Access Control
(Organization/Team/User) participant MCP as Partner MCP Server
(Slack, Google, etc.) Agent->>Gateway: Request tools/execute action Gateway->>Auth: Validate user identity & permissions Auth-->>Gateway: User authorized ✓ Gateway->>MCP: Forward authenticated request MCP-->>Gateway: Return results Gateway-->>Agent: Deliver response ``` ## Available connectors Writer provides two types of connectors: prebuilt connectors for popular enterprise tools and custom connectors you create from OpenAPI specifications or MCP servers. ### Prebuilt connectors Prebuilt connectors are ready-to-use integrations maintained by Writer. These connectors provide access to popular enterprise tools with pre-configured authentication and tool definitions. | Connector | Auth type | Managed by | Connector docs | | - | - | - | - | | **Adobe Experience Manager** | OAuth 2.0 | Adobe-managed | [View docs](/connectors/adobe-experience-manager) | | **Asana** | OAuth 2.0 | Writer or organization-managed | [View docs](/connectors/asana) | | **Atlassian** | OAuth 2.0 | Atlassian-managed | [View docs](/connectors/atlassian) | | **Contentful** | OAuth 2.0 | Contentful-managed | [View docs](/connectors/contentful) | | **Databricks** | API key | Organization-managed | [View docs](/connectors/databricks) | | **FactSet** | OAuth 2.0 | Organization-managed | [View docs](/connectors/factset) | | **Gmail** | OAuth 2.0 | Organization-managed | [View docs](/connectors/gmail) | | **Gong** | API key | Organization-managed | [View docs](/connectors/gong) | | **Google BigQuery** | OAuth 2.0 | Organization-managed | [View docs](/connectors/google-bigquery) | | **Google Calendar** | OAuth 2.0 | Organization-managed | [View docs](/connectors/google-calendar) | | **Google Docs** | OAuth 2.0 | Organization-managed | [View docs](/connectors/google-docs) | | **Google Drive** | OAuth 2.0 | Organization-managed | [View docs](/connectors/google-drive) | | **Google Sheets** | OAuth 2.0 | Organization-managed | [View docs](/connectors/google-sheets) | | **HubSpot** | OAuth 2.0 | Writer or organization-managed | [View docs](/connectors/hubspot) | | **Microsoft Calendar** | OAuth 2.0 | Writer or organization-managed | [View docs](/connectors/microsoft-calendar) | | **Microsoft OneDrive** | OAuth 2.0 | Writer or organization-managed | [View docs](/connectors/microsoft-onedrive) | | **Microsoft Outlook** | OAuth 2.0 | Writer or organization-managed | [View docs](/connectors/microsoft-outlook) | | **Microsoft SharePoint** | OAuth 2.0 | Writer or organization-managed | [View docs](/connectors/microsoft-sharepoint) | | **Microsoft Teams** | OAuth 2.0 | Writer or organization-managed | [View docs](/connectors/microsoft-teams) | | **PitchBook** | API key | Organization-managed | [View docs](/connectors/pitchbook) | | **Salesforce** | OAuth 2.0 | Writer or organization-managed | [View docs](/connectors/salesforce) | | **Semrush** | OAuth 2.0 | Semrush-managed | [View docs](/connectors/semrush) | | **Slack** | OAuth 2.0 | Writer or organization-managed | [View docs](/connectors/slack) | | **Snowflake** | OAuth 2.0 | Organization-managed | [View docs](/connectors/snowflake) | | **Wrike** | OAuth 2.0 | Organization-managed | [View docs](/connectors/wrike) | | **ZoomInfo** | OAuth 2.0 | Organization-managed | [View docs](/connectors/zoominfo) | ### Custom connectors Custom connectors let you integrate WRITER Agent with any API that has an OpenAPI specification or any external MCP server. Use custom connectors to connect to internal tools, proprietary systems, or third-party services not available as prebuilt connectors. Once created, custom connectors are configured and managed in Control Center the same way as prebuilt connectors. You control authentication, access permissions, and which tools are enabled for users and teams. For step-by-step instructions on creating custom connectors, see [Custom connectors](/home/custom-connectors). ## Set up connectors Connector setup happens in [Control Center](https://app.writer.com/controlcenter) under **Integrations > Connectors**. The setup process differs slightly between connector types: * **Prebuilt connectors**: Select from the connector library and configure authentication. For step-by-step instructions, see [Setting up connectors](https://support.writer.com/article/299-setting-up-connectors). * **Custom connectors**: After creating a custom connector, configure access permissions, enable tools, and enter authentication credentials. For instructions on creating custom connectors, see [Custom connectors](/home/custom-connectors). The sections below cover the technical authentication requirements for configuring connectors. ## Set up connector authentication Both prebuilt and custom connectors support OAuth 2.0 and API key authentication. The type of authentication depends on the third-party service, and the connector configuration flow in Control Center guides you through the required setup. **OAuth 2.0 connectors**: * Most prebuilt OAuth connectors support WRITER-managed authentication (no OAuth app setup required) * Custom connectors and some prebuilt connectors (FactSet, Gmail, Google BigQuery, Google Calendar, Google Docs, Google Drive, Google Sheets, Snowflake, Wrike, ZoomInfo) require organization-managed OAuth * The Adobe Experience Manager, Atlassian, Contentful, and Semrush connectors use dynamic client registration, where the provider automatically creates and manages OAuth credentials (no manual OAuth app setup required) * See [Set up OAuth](#set-up-oauth) for details on all options **API key connectors**: * Require an API key from the third-party service * For prebuilt connectors, see the [prebuilt connectors](#prebuilt-connectors) table for links to provider documentation * For custom connectors, see [Custom connectors](/home/custom-connectors) for setup instructions ### Set up OAuth OAuth connectors support three possible authentication options in Control Center: **WRITER-managed OAuth** (prebuilt connectors only): * Writer provides and manages the OAuth application * No OAuth app setup required * Users authorize access to their account when they first use the connector * Faster setup with less configuration **Organization-managed OAuth** (prebuilt and custom connectors): * You create and manage your own OAuth application with the provider * Provides more control and custom branding * Requires OAuth app configuration with client ID and client secret * Required for custom connectors and the following prebuilt connectors: FactSet, Gmail, Google BigQuery, Google Calendar, Google Docs, Google Drive, Google Sheets, Snowflake, Wrike, ZoomInfo **Dynamic client registration** ([Adobe Experience Manager](/connectors/adobe-experience-manager), [Atlassian](/connectors/atlassian), [Contentful](/connectors/contentful), and [Semrush](/connectors/semrush)): * The provider automatically creates and manages OAuth credentials during the setup process * No manual OAuth application setup, client ID, or client secret required * Faster setup with less configuration #### OAuth connection levels When configuring an OAuth connector, you choose whether to use user-level or org-level authentication: **User-level OAuth** (most common): * Each user connects their own personal account (their Gmail, Slack, etc.) * OAuth authentication happens when individual users first try to use the connector * Administrators configure the connector in Control Center, but don't authenticate during setup * Users authenticate through WRITER Agent the first time they interact with the connector **Org-level OAuth**: * A single shared OAuth connection for the entire organization * OAuth authentication happens during connector setup in Control Center * Administrators authenticate with the provider when configuring the connector * Users can immediately use the connector without individual authentication > [!NOTE] > > With user-level OAuth, administrators set up the connector configuration > (OAuth app credentials, enabled tools, access permissions), but the actual > OAuth authentication happens later when each user first uses the connector. > With org-level OAuth, administrators complete the OAuth authentication during > the initial connector setup. #### Create OAuth applications for organization-managed authentication If you choose organization-managed OAuth, or if using a connector that requires it, you need to create an OAuth application with the provider: 1. Follow the provider's documentation to create an OAuth application. View [prebuilt connectors](#prebuilt-connectors) for links to provider documentation. 2. Add the following Writer redirect URI to the list of allowed redirect URIs in your OAuth application's settings: ``` https://app.writer.com/mcp/oauth/callback ``` > [!NOTE] > > If your organization is deployed in the EU, use `https://app.eu2.writer.com/mcp/oauth/callback` instead. 3. Copy the client ID and client secret for use in Control Center The gateway uses this redirect URI to receive authorization codes from third-party services after users grant permission. #### Required OAuth scopes Each connector requires specific OAuth scopes to access third-party APIs. The connector configuration interface in Control Center displays the required scopes when you configure a connector. ![Google Calendar OAuth scopes](https://mintcdn.com/writer/RmpeckABOl0_oABL/images/home/google-calendar-oauth-scopes.png?fit=max\&auto=format\&n=RmpeckABOl0_oABL\&q=85\&s=16c20858afef3ccd0b4295c69e9c9224) Some connectors require extensive OAuth scopes during authentication. This is because connectors often provide multiple tools with broad functionality across the integrated service. For example, a connector for a productivity service might include tools to: * Read and search documents * Create and modify files * Access calendar events * Send messages or notifications * Manage sharing permissions Each of these capabilities requires corresponding OAuth scopes from the provider. Connectors use either dynamic or fixed OAuth scopes. For details on how scopes work and which connectors support dynamic scopes, see [OAuth scopes](#oauth-scopes). ## Manage access control and permissions Organization and IT administrators can control which users have access to connectors and configure granular permissions for connector functionality. ### Configure connector availability Connectors can be made available to users in two ways: * **All users**: The connector is immediately available to everyone in the organization * **Select teams**: Restrict the connector to specific teams. Users on non-approved teams can request access, which requires admin approval. This access control model allows organizations to gradually roll out connectors or restrict sensitive integrations to specific teams. ### Role-based administration By default, only users with Org Admin and IT Admin roles can configure and manage connectors. These permissions can be adjusted through the roles and permissions settings in Control Center to delegate connector management to other roles if needed. ### Tool-level granular control Within each connector, administrators can selectively enable specific tools rather than activating all available functionality. This provides fine-grained control over what actions AI agents can perform through each connector. For example, you might enable read-only tools for a connector while disabling tools that modify or delete data. ### Revoke connector access Administrators and users can revoke connector access at multiple levels: **Revoke individual user access:** * Users can disconnect their personal OAuth accounts from within WRITER Agent settings * Disconnecting removes the user's authentication tokens but preserves the connector configuration * Users can reconnect by re-authorizing through the OAuth flow **Revoke team or organization access:** * Administrators can disable a connector entirely from Control Center's Integrations > Connectors interface * Disabling a connector immediately revokes access for all users * Re-enabling requires users to re-authenticate with their accounts **Revoke specific tool permissions:** * Administrators can disable individual tools within a connector without removing the entire connector * Users retain their OAuth connections but cannot access disabled tools * Tool permissions can be re-enabled without requiring re-authentication ## Private endpoints A private endpoint is a network path between Writer's MCP gateway and a service in your VPC. Instead of sending connector traffic over the public internet, Writer connects through [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html) or [GCP Private Service Connect](https://cloud.google.com/vpc/docs/private-service-connect) so requests stay on your cloud provider's private network. Register private endpoints in Control Center under **Security & compliance > Private endpoints**. After you register an endpoint, attach it when you configure a connector so WRITER Agent uses that path for that connector's requests. For cloud provider setup, registration, and how to enable an endpoint on a connector, see [Private endpoints](/home/private-endpoints). > [!NOTE] > > For prebuilt connectors, contact your customer success manager to enable > private endpoints. You can enable private endpoints on custom connectors > during connector setup in Control Center. ## Whitelist IP addresses If your organization’s firewall or network policies restrict connections from third-party services, add Writer’s MCP Gateway static egress IP addresses to your allowlist. All outbound traffic from prebuilt and custom connectors originates from the following static IP addresses: **static egress IP addresses** | IP address | | - | | `136.114.152.14` | | `136.114.183.118` | | `136.114.77.197` | | `136.116.231.122` | | `34.10.120.41` | | `34.132.102.189` | | `34.132.239.48` | | `34.136.80.118` | | `34.136.9.195` | | `34.30.77.246` | | `34.41.53.121` | | `34.56.164.176` | | `34.58.72.208` | | `34.63.201.5` | | `34.68.86.48` | | `35.225.95.201` | > [!WARNING] > > IP addresses are subject to change. Last updated **March 10, 2026**. ## Connect as an end user After administrators configure connectors in Control Center, end users interact with them through conversation in WRITER Agent. ### User-level and org-level OAuth Connectors can be configured with different OAuth authentication levels, which affects how users connect: **User-level OAuth** (most common): * Each user connects their own personal account (their Gmail, their Slack workspace, etc.) * Users authenticate individually with their own credentials * The connector accesses only that user's data and permissions * Example: When you use the Gmail connector, it accesses your Gmail inbox, not a shared organizational inbox **Org-level OAuth** (shared connection): * An administrator sets up a single OAuth connection for the entire organization * All users share the same authenticated connection * No individual user authentication required * Less common; typically used when accessing shared organizational resources rather than personal accounts > [!NOTE] > > Most connectors use user-level OAuth where each person connects their own > account. When a connector is configured with user-level OAuth, users must > authenticate individually before using it. ### How users interact with connectors To use a connector, ask WRITER Agent for what you need in everyday language, such as "Summarize unread emails" or "Find messages in Slack." If access is needed, the agent prompts you to connect your account. After you're connected, you can keep making requests the same way—no special steps or commands required. **Example interactions:** **Using Gmail:** ``` User: "Summarize my unread emails from this week" Agent: [If not connected] "I need access to your Gmail to help with that. Please connect your Gmail account to continue." [Shows authentication button] User: [Clicks to authenticate, completes OAuth flow] Agent: "Thanks! I can now access your Gmail. Here's a summary of your unread emails from this week..." ``` ### First-time connection flow For connectors configured with **user-level OAuth**, users must authenticate their personal account the first time they use a connector: 1. **User makes a request**: "Search Slack for messages about the budget" 2. **Authentication prompt**: Agent responds: "I need access to your Slack workspace to search messages. Please connect your Slack account." 3. **OAuth authorization**: User clicks the authentication button and is redirected to Slack's authorization page 4. **Permission consent**: User reviews the permissions and approves access 5. **Return to conversation**: User is redirected back to WRITER Agent 6. **Task completion**: Agent automatically retries the original request: "I found 15 messages about the budget..." For connectors configured with **org-level OAuth**, users can immediately use the connector without individual authentication since the administrator has already set up the shared connection. ## Known limitations ### OAuth token expiration Some providers automatically expire OAuth tokens after periods of inactivity: * **Google services**: OAuth credentials become invalid after 6 months of inactivity. If you haven't used a Google connector (Gmail, Google BigQuery, Google Calendar, Google Docs, Google Drive, Google Sheets) for 6 months, you'll need to re-authenticate. The MCP gateway automatically handles token refresh for active connections, but cannot refresh tokens that have been revoked due to inactivity. ### OAuth scopes OAuth scopes define the permissions a connector receives during authorization. Depending on the connector, the OAuth application requests scopes as either a fixed set or a dynamic set based on the tools you select during configuration. #### Fixed scopes With fixed-scope OAuth connectors, the OAuth application requests all scopes required for every available tool when you authorize the connector, regardless of which tools you enable or disable in your configuration. #### Dynamic scopes With dynamic-scope OAuth connectors, the OAuth application requests only the scopes needed for the tools you enable. The following connectors support dynamic OAuth scopes: * **Google**: [Gmail](/connectors/gmail), [Google BigQuery](/connectors/google-bigquery), [Google Calendar](/connectors/google-calendar), [Google Docs](/connectors/google-docs), [Google Drive](/connectors/google-drive), [Google Sheets](/connectors/google-sheets) * **Microsoft**: [Microsoft Calendar](/connectors/microsoft-calendar), [Microsoft OneDrive](/connectors/microsoft-onedrive), [Microsoft Outlook](/connectors/microsoft-outlook), [Microsoft SharePoint](/connectors/microsoft-sharepoint), [Microsoft Teams](/connectors/microsoft-teams) * **Gong**: [Gong](/connectors/gong) ## Next steps * [Custom connectors](/home/custom-connectors): Create connectors from OpenAPI specifications or MCP servers to integrate with your own APIs and tools. * [Private endpoints](/home/private-endpoints): Connect over a private network using AWS PrivateLink or GCP Private Service Connect. * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Learn how to configure and enable prebuilt connectors in Control Center. * [Tool calling guide](/home/tool-calling): Understand how AI agents use tools in conversations. * [WRITER Agent guide](https://support.writer.com/article/293-how-to-use-action-agent): Learn how to use WRITER Agent with connected tools. * [API reference](/api-reference/completion-api/chat-completion): Explore the Chat Completion API that powers tool calling. # Mitigate bias in AI outputs Source: https://dev.writer.com/home/mitigating_bias ## Introduction In the era of artificial intelligence, ensuring that AI models produce unbiased and fair outputs has become a critical concern. Writer, one of the leading organizations in the field, takes this challenge seriously and employs a range of strategies to detect and mitigate biases in its AI models. In this article, we explore the technical methodologies employed by Writer to grapple with this complex issue. ## Mechanisms and methodologies for detecting and mitigating Bias > [tab] Data cleaning and preprocessing > > At the heart of any machine learning model lies the data on which it's trained. Writer meticulously curates its training data, which is sourced from a mix of publicly available data from the Internet and data licensed from third parties. Text preprocessing techniques, such as removing sensitive content or flagging potential hotspots for bias, are employed before the data is used for training. > [tab] Annotation guidelines > > The first layer of oversight comes in the form of human annotators who label the data. These annotators are guided by a stringent set of rules designed to counteract the introduction of bias. For example, they're trained to avoid favoring any political ideology, ethnicity, or other sociocultural factors when annotating the training data. > [tab] Auditing > > After the initial training, the model is subjected to a rigorous auditing process. This involves running the model through a series of test cases designed to gauge its propensity for biased or unsafe content. These audits are often carried out by both internal teams and third-party organizations to ensure objectivity. > [tab] RLHF > > The next step involves fine-tuning the model based on the results of the audit. Writer uses reinforcement learning from human feedback (RLHF) or similar techniques to adjust the model's parameters, helping it to make less biased decisions. Fine-tuning focuses on specific aspects like language nuances, sentiment interpretation, and context-aware decision-making. > [tab] Feedback loop > > Writer has an active feedback loop with its beta user community. Reports of biased outputs are taken seriously and are used to further fine-tune the model. This makes the model more robust and adaptable to real-world applications. ## Sources of bias in training data Writer models are trained on large datasets that are a snapshot of human culture and thought, collected by our team. While this helps the model to be versatile and knowledgeable, it also brings in the risk of the model inheriting the existing biases in society. Writer mitigates this by adding layers of scrutiny and control, both algorithmic and human, on the data used for training. ## Adapting to different contexts and languages > [tab] Context-aware fine-tuning > > Writer is pioneering research in making its models more context-sensitive. This involves incorporating additional features into the model’s architecture that allows it to understand the specific context in which a text snippet appears, enabling more nuanced responses. > [tab] Language-specific models > > Given the global reach of AI, Writer is also working on language-specific versions of its models. These models undergo fine-tuning with data that is representative of the linguistic and cultural idiosyncrasies of specific languages. > [tab] Annotator teams > > To further the goal of international adaptability, Writer often employs annotators from various cultural backgrounds. This helps in creating a model that is less likely to favor any particular group. ## Conclusion The challenge of eliminating bias in AI models is a complex and ongoing task. Writer employs a multi-faceted approach, combining data science, human oversight, and cutting-edge machine learning techniques, to tackle this critical issue. While there's always room for improvement, the methodologies adopted serve as a strong framework for mitigating bias in AI. # Use another LLM as a tool Source: https://dev.writer.com/home/model-delegation With model delegation, you can use another model as a tool in a [chat completion](/home/chat-completion). The predefined LLM tool allows you to delegate specific tasks to another model available to your organization, including [external models](/home/external-models) from providers like AWS Bedrock and OpenRouter. For example, in a chat application using Palmyra X5, you can delegate focused analysis tasks to a different model. This guide shows you how to set up model delegation with the Writer API. After completing these steps, you can route specific tasks within a chat completion to the model best suited to handle them. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Tool structure Use the LLM tool to delegate specific tasks to another model when using the [chat endpoint](/api-reference/completion-api/chat-completion). Using [tool calling](/home/tool-calling), you can specify the model you want to use for a given task. When the primary chat model calls the LLM tool based on the user's input, it signals it in the chat API response. To use the LLM tool, add it to the `tools` array in your `chat-completion` endpoint request. The LLM tool object has the following structure: | Parameter | Type | Description | | - | - | - | | `type` | `string` | The type of tool, which is `llm` for LLM tool | | `function` | `object` | An object containing the tool's description and model | | `function.description` | `string` | A description of what the model will be used for. | | `function.model` | `string` | The ID of the model to be used for this tool. This can be a [Palmyra model](/home/models) or an [external model](/home/external-models) configured for your organization. | > [!NOTE] > > To help the model understand when to use the tool, follow these best practices for the `function.description` parameter: > > * Indicate that the tool is a function that invokes an LLM > * Specify the model's purpose and capabilities > * Describe when the tool should be used > > An example description for a tool using an external model: > > > "A function that invokes the LLM identified by the given model for detailed analysis. Any user request requiring in-depth analysis should use this tool." ```bash cURL theme={null} "tools": [ { "type": "llm", "function": { "description": "A function that will invoke the llm identified by the given model for detailed analysis and reporting. Any user request requiring in-depth analysis should use this tool.", "model": "anthropic.claude-3-sonnet-20240229-v1:0" } } ] ``` ```python Python theme={null} tools = [{ "type": "llm", "function": { "description": "A function that will invoke the llm identified by the given model for detailed analysis and reporting. Any user request requiring in-depth analysis should use this tool.", "model": "anthropic.claude-3-sonnet-20240229-v1:0" } }] ``` ```js JavaScript theme={null} const tools = [{ type: "llm", function: { description: "A function that will invoke the llm identified by the given model for detailed analysis and reporting. Any user request requiring in-depth analysis should use this tool.", model: "anthropic.claude-3-sonnet-20240229-v1:0" } }] ``` > [!NOTE] > > You can only pass one prebuilt tool in the `tools` array at a time. However, you can pass multiple [custom tools](/home/tool-calling) in the same request. > > Prebuilt tools are: > > * LLM tool > * [Knowledge Graph tool](/home/kg-chat) ### Response format When a chat completion uses the LLM tool, the response from the LLM tool is in the `llm_data` object. The `llm_data` object contains the following fields: | Parameter | Type | Description | | - | - | - | | `prompt` | string | The prompt used by the LLM tool. | | `model` | string | The ID of the model used by the LLM tool. | Below is an example of the full response to a chat completion request that uses the LLM tool with an external model. ```json non-streaming response [expandable] {17} theme={null} { "id": "1234", "object": "chat.completion", "choices": [ { "index": 0, "finish_reason": "stop", "message": { "content": "The recommended daily intake of calcium for a 30-year-old woman is 1,000 mg per day.", "role": "assistant", "tool_calls": null, "graph_data": { "sources": null, "status": null, "subqueries": null }, "llm_data": { "prompt": "What is the recommended daily intake of calcium for a 30-year-old woman?", "model": "anthropic.claude-3-sonnet-20240229-v1:0" }, "image_data": null, "refusal": null }, "logprobs": null } ], "created": 1741970653, "model": "palmyra-x5", "usage": { "prompt_tokens": 259, "total_tokens": 305, "completion_tokens": 46, "prompt_token_details": null, "completion_tokens_details": null }, "system_fingerprint": "v1", "service_tier": null } ``` ```json streaming response [expandable] {16} theme={null} { "id": "1234", "object": "chat.completion.chunk", "choices": [{ "index": 0, "finish_reason": None, "message": { "content": "The", "role": "assistant", "tool_calls": None, "graph_data": { "sources": None, "status": None, "subqueries": None }, "llm_data": { "prompt": "What is the recommended daily intake of calcium for a 30-year-old woman?", "model": "anthropic.claude-3-sonnet-20240229-v1:0" }, "image_data": None, "refusal": None }, "logprobs": None, "delta": { "content": "The", "role": "assistant", "tool_calls": None, "graph_data": { "sources": None, "status": None, "subqueries": None }, "llm_data": { "prompt": "What is the recommended daily intake of calcium for a 30-year-old woman?", "model": "anthropic.claude-3-sonnet-20240229-v1:0" }, "image_data": None, "refusal": None }, "logprobs": None }], "created": 1741970696, "model": "palmyra-x5", "usage": None, "system_fingerprint": "v1", "service_tier": None } ``` ## Usage example Here's an example of how to use the LLM tool in your application. This example delegates detailed questions to an external model. ### Create a tools array containing an LLM tool To use the LLM tool, create a `tools` array that specifies the model you want to use. ```bash cURL theme={null} "tools": [ { "type": "llm", "function": { "description": "A function that will invoke the llm identified by the given model for detailed analysis. Any user request requiring in-depth analysis should use this tool.", "model": "anthropic.claude-3-sonnet-20240229-v1:0" } } ] ``` ```python Python theme={null} tools = [{ "type": "llm", "function": { "description": "A function that will invoke the llm identified by the given model for detailed analysis. Any user request requiring in-depth analysis should use this tool.", "model": "anthropic.claude-3-sonnet-20240229-v1:0" } }] ``` ```js JavaScript theme={null} const tools = [{ type: "llm", function: { description: "A function that will invoke the llm identified by the given model for detailed analysis. Any user request requiring in-depth analysis should use this tool.", model: "anthropic.claude-3-sonnet-20240229-v1:0" } }] ``` ### Send the request using chat completions Add the tools array to the chat endpoint call along with your array of messages. Setting `tool_choice` to `auto` allows the model to choose when to use the LLM tool, based on the user's question and the description of the tool. This example streams the response as the model generates it. If you are unfamiliar with the chat completions endpoint or streaming vs. non-streaming responses, learn more in the [chat completion guide](/home/chat-completion). ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/chat' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "temperature": 0.7, "messages": [ { "role": "user", "content": "What is the recommended daily intake of calcium for a 30-year-old woman?" } ], "tool_choice": "auto", "tools": [ { "type": "llm", "function": { "description": "A function that will invoke the llm identified by the given model for detailed analysis. Any user request requiring in-depth analysis should use this tool.", "model": "anthropic.claude-3-sonnet-20240229-v1:0" } } ], "stream": true }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() messages = [{"role": "user", "content": "What is the recommended daily intake of calcium for a 30-year-old woman?"}] response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, # The tools array defined earlier. tool_choice="auto", stream=True ) for chunk in response: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].delta.content, end="", flush=True) ``` ```js JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const messages = [{role: "user", content: "What is the recommended daily intake of calcium for a 30-year-old woman?"}]; const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, // The tools array defined earlier. tool_choice: "auto", stream: true }); for await (const chunk of response) { if (chunk.choices[0].delta.content) { process.stdout.write(chunk.choices[0].delta.content); } } ``` By following this guide, you can delegate specific tasks to another model within your chat applications. ## Next steps Explore other ways to extend your chat applications: * [Analyze images in a chat](/home/chat-with-images) * [Pass questions to a Knowledge Graph](/home/kg-chat) # Configure model parameters Source: https://dev.writer.com/home/model-parameters ## Likelihood WRITER models learn language by reading text from the internet. Given a sentence such as "I like to play with Legos", the model repeatedly predicts what the next token is: ```text theme={null} \*\*I [?] I like [?] I like to [?] I like to play [?] I like to play with [?]\*\* ``` The model learns that the word “to” is quite likely to follow the word “like” in English, and that the word “play” is likely to follow the word “with” and so on. Likelihood refers to the probability that a given sequence of [tokens](/home/tokens), which can be words or characters, gets generated by the model. You can think of the likelihood of a token as a number that quantifies a model's level of surprise that this token appeared in a sentence. If a token has a low likelihood, it means the model didn't expect this token to appear. Conversely, if a token has a high likelihood, the model was confident that it would appear. You can use the likelihood score to evaluate the quality of the model's output, representing the model's confidence that a given output is the most likely sequence of tokens given the input prompt and the target data. ## Temperature The same prompt may yield different outputs each time you hit "generate" and so, temperature is a parameter used to control the randomness and diversity of the generated output. The temperature scale ranges from 0 to 1. A temperature of 1.0 means that the model is generating outputs with its normal level of confidence, based on the probabilities it has learned during training. A higher temperature increases the randomness of the output, allowing for more diverse and unexpected results. A lower temperature makes the model more conservative in its predictions, generating outputs that are more likely to align with what it has learned during training. Most people find that a temperature between 0.7 and 1 is a good starting point. **Temperature defaults to 0.7** if not specified as an exact parameter With longer prompts, the model becomes more confident in its predictions, so you can raise the temperature higher for a diverse and creative output without the output being too off topic. In contrast, using high temperatures on short prompts can lead to unstable outputs. You can use lower temperature values for tasks like classification, entity extraction, or question answering, and use higher temperature values for tasks like content or idea generation. ## Top-k and top-p Top-k sampling and top-p sampling are methods for picking the output tokens by controlling the quality and diversity of the generated output. ### Top-k **Top-k is currently not an active parameter but if you believe your outputs could improve with this parameter, contact your Writer representative** **Top-k defaults to 40, but it accepts any integer between 1 and 50,400.** Top-k refers to selecting the k tokens with the highest predicted probabilities and then randomly selecting one of these k tokens to generate the next word. This method generates outputs that are more likely to be accurate, but may be less diverse. Top-k refers to the number of tokens that get sampled, sorted by probability with all tokens beneath the `k`-th token not sampled. A lower value can improve quality by removing the long tail of less likely tokens and making it less likely to go off topic. ### Top-p **Top-p defaults to 1 but accepts any number between 0 and 1.** Top-p refers to selecting the top p% of the most likely tokens based on the predicted probabilities of the model, and then randomly selecting one of the top p tokens to generate the next word. Top-p is an alternative way of controlling the randomness of the generated text. Generally, top-p provides better control where your model generates text with accuracy and correctness. \*\*When modifying top-p, make sure that temperature is `1`. As a corollary, if you are modifying temperature, make sure that you set top-p to the default of `1` \*\* Modifying both temperature and top-p from their defaults at the same time can lead to undesired results. The model first performs top-p sampling to narrow down the word selection, and then applies the temperature to adjust the remaining probabilities. This process can produce outputs that become either too constrained or too random, depending on your chosen values. To strike a balance between control and diversity in text generation, it's generally recommended to modify top-p values or temperature values based on your desired outcome. Experimenting with different values and observing the generated outputs can help you determine which parameter suits your specific needs. ## `best_of` **`best_of` defaults to `1`, but it accepts any integer between `1` and `5`** In the context of language models, `best_of` is usually used in the context of [beam search](https://en.wikipedia.org/wiki/Beam_search), which is an algorithm used for generating sequences of words. Beam search explores multiple possible word sequences and selects the most promising ones based on a scoring mechanism. In beam search, the `best_of` value refers to the number of top candidates that get considered at each step of the generation process. For example, if you set `best_of` to `3`, the algorithm considers the top 3 candidates at each step and proceeds with further exploration. The higher the `best_of` value, the more candidates the LLM considers, which can increase the quality and accuracy of the output as well as the computational time and cost of the generation. # Choose a model Source: https://dev.writer.com/home/models Choose the right Palmyra model for your needs. Compare capabilities, context windows, and pricing for the Palmyra X6, X5, and X4 models. > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. Whether you use no-code, Agent Builder, or APIs, you need to choose a model. Here is an overview of the Palmyra models and their capabilities. ## Model comparison The following table compares the capabilities, context windows, and pricing of the Palmyra X6, X5, and X4 models. | Feature | Palmyra X6 | Palmyra X5 | Palmyra X4 | | - | - | - | - | | **Description** | Agentic model for WRITER Agent and long-horizon enterprise workflows with sub-agents, grounding, and MCP tool use | General-purpose model with a 1M token context window and adaptive reasoning | Language model for complex tasks that require extended context | | **API model ID** | `palmyra-x6` | `palmyra-x5` | `palmyra-x4` | | **Bedrock model ID** | — | `writer.palmyra-x5-v1:0` | `writer.palmyra-x4-v1:0` | | **Pricing (Input)** | \$2.00 / 1M tokens | \$0.60 / 1M tokens | \$2.50 / 1M tokens | | **Pricing (Output)** | \$8.00 / 1M tokens | \$6.00 / 1M tokens | \$10.00 / 1M tokens | | **Context window** | 1M tokens | 1M tokens | 128k tokens | | **Max output** | 8,192 tokens | 8,192 tokens | 4,096 tokens | > [!NOTE] > > Palmyra X6 is the default model for [WRITER Agent](/home/pricing#writer-agent). Palmyra X6, X5, and X4 are available via API. To analyze images, use [vision capabilities with Palmyra X5](/home/chat-with-images). > [!NOTE] > > Palmyra X5 in WRITER Agent is billed at \$5.00 input and \$12.00 output per 1M tokens. ## Model details > [accordion] Palmyra X6 > > > [tab] Overview > > > > Palmyra X6 is Writer's default agentic model for [WRITER Agent](https://support.writer.com/article/235-ask-writer) and long-horizon enterprise workflows. It was co-developed with the product's orchestration layer. Capability scores in the Benchmarking tab measure the model in that combined system, which is how customers deploy it. > > > > Palmyra X6 can hold a single objective for up to 8 hours without supervision, planning, executing, verifying output, and delivering finished work rather than a draft that needs another pass. > > > > **Pricing**: > > > > * Input: \$2.00 per 1M tokens > > * Output: \$8.00 per 1M tokens > > > > **Context window**: 1M > > > > **Task economics** (median on Writer's internal evaluation of production customer tasks, n=22): > > > > * Cost per finished task: \$0.12 > > * Latency per finished task: 26 seconds > > > [tab] Use cases and capabilities > > > > Palmyra X6 is built for the agentic work marketing, revenue, and operations teams run in production, including grounded research, content generation, connector-driven actions, and multi-step playbooks. > > > > **WRITER Agent workflows** > > > > * **Connector-driven tasks**: Query CRM records, search Slack messages, update documents, and perform other actions through [prebuilt and custom connectors](/home/mcp-gateway) > > * **Multi-step automation**: Break complex requests into sequenced tool calls across multiple systems > > * **Grounded responses**: Pull context from Knowledge Graphs, documents, and connector data with retrieval and citation > > * **Playbooks**: Execute predefined multi-step workflows end to end > > > > **Agentic capabilities** > > > > * **Sub-agents**: Delegate work to spawned sub-agents and merge results back into the primary workflow > > * **MCP tool use**: Discover and call external tools through MCP connectors > > * **Content generation**: Draft and edit long- and short-form content to a brief > > * **Brand voice**: Apply brand voice and custom instructions to output > > * **Long-horizon execution**: Sustain multi-hour objectives with planning, self-testing, and correction loops > > * **Image analysis and generation**: Interpret input images and generate new images > > * **Presentations** *(early)*: Generate slide presentations from a prompt or source > > > [tab] Benchmarking > > > > Writer evaluates Palmyra X6 on production customer tasks (marketing, revenue, research, and outreach), not abstract reasoning benchmarks alone. Each capability is scored 0 to 1 against a locked baseline (n=22, reference frozen 2026-06-07). Scores measure Palmyra X6 running in WRITER Agent. > > > > **Capability scores (Palmyra X6 in WRITER Agent)** > > > > | Capability | What it measures | Score | > > | - | - | - | > > | Sub-agents | Delegating work to spawned sub-agents and merging results | **0.86** | > > | Grounding and retrieval | Knowledge Graph and document grounding, retrieval, and citation | **0.91** | > > | MCP tool use | Discovering and calling external tools through MCP connectors | **0.88** | > > | Content generation | Drafting and editing long- and short-form content to a brief | **0.88** | > > | Playbooks | Executing predefined multi-step workflows end to end | **0.84** | > > | Model and system awareness | Knowing its identity, tools, scope, and when to safely refuse | **0.97** | > > | Brand voice | Applying brand voice and custom instructions to output | **0.92** | > > | Image analysis and generation | Interpreting input images and generating new images | **0.80** | > > | Presentations *(early)* | Generating slide presentations from a prompt or source | **0.74** | > > > > Average capability score: **0.87**. > > > > **Domain benchmarks (raw model)** > > > > The scores below measure the Palmyra X6 model directly, not in WRITER Agent, on finance benchmarks: > > > > | Benchmark | Score | > > | - | - | > > | Finance Agent | 0.753 | > > | FinanceQA | 0.673 | > > | FinanceBench | 0.855 | > [accordion] Palmyra X5 > > > [!WARNING] > > > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. > > > [tab] Overview > > > > Palmyra X5 is Writer's general-purpose model for building and scaling AI agents, featuring a 1 million token context window, adaptive reasoning, and strong speed and cost efficiency. > > > > **Pricing**: > > > > * Input: \$0.60 per 1M tokens > > > > * Output: \$6.00 per 1M tokens > > > > > [!NOTE] > > > > > > Palmyra X5 in WRITER Agent is billed at \$5.00 input and \$12.00 output per 1M tokens. See [WRITER Agent pricing](/home/pricing#writer-agent). > > > > **Content window**: 1M > > > [tab] Use cases and capabilities > > > > Palmyra X5's 1M token context window further streamlines enterprise workflows and unlocks complex, multi-step use cases that weren't possible before. > > > > **Multi-step agentic workflows** > > > > * **Support documentation**: Classify requests, assess urgency, assign a human review, stage updates in a CMS, and publish after approval. > > * **Fund reporting**: Streamline the analysis and preparation of detailed reports on the performance and status of investment funds, using reporting and research data pulled in from third-party systems > > * **Content lifecycle management**: Flag content that could be outdated, generate suggested revisions, and share them for human review. > > > > **Large data requirements**: > > > > * **Customer feedback analysis**: Analyze large volumes of customer feedback to identify common themes, summarize sentiments, and generate actionable insights. > > * **Research and development**: Process and summarize multiple technical reports, research papers, and experimental data, accelerating innovation and product development. > > * **Financial reporting**: Process and summarize annual reports, SEC filings, and market analysis reports together at once to extract financial data, identify trends, and generate executive summaries. > > * **Legal document analysis**: Analyze lengthy legal documents, including contracts, patents, and compliance reports, to identify key clauses, flag potential risks, and ensure regulatory compliance. > > * **Medical records analysis**: Analyze and summarize large files of medical records containing structured and unstructured data, including patient records, clinical trial reports, audit reports, and more. > > > [tab] Benchmarking > > > > Palmyra X5 demonstrates robust performance across a suite of industry-standard benchmarks, showcasing its capabilities in reasoning, retrieval, and domain-specific tasks. > > > > * **BBH (Big-Bench Hard)**: Evaluates complex reasoning and compositional logic. Palmyra X5 achieves a competitive score of 70.99%, aligning closely with top-tier models. > > * **GPQA (Graduate-Level Google-Proof Q\&A)**: Assesses the model's ability to answer challenging, graduate-level questions in biology, physics, and chemistry that are resistant to simple lookup strategies. X5's score of 47.20% indicates strong performance in scientific reasoning tasks. > > * **MMLU_PRO**: Focuses on professional-level knowledge across various domains such as law, medicine, and finance. Palmyra X5 scores 65.02%, demonstrating its suitability for enterprise applications in regulated sectors. > > * **MATH_HARD**: Tests symbolic reasoning and multi-step problem-solving abilities. X5's score of 71.57% showcases its proficiency in handling complex analytical tasks. > [accordion] Palmyra X4 > > > [!WARNING] > > > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. > > > [tab] Overview > > > > `palmyra-x4` is an advanced language model that excels in processing and understanding complex tasks. It's ideal for workflow automation, coding tasks, and data analysis. > > > > **Pricing**: > > > > * Input: \$2.50 per 1M tokens > > * Output: \$10.00 per 1M tokens > > > > **Content window**: 128k > > > [tab] Use cases and capabilities > > > > * **Agents & actions**: Palmyra X4 acts as an advanced AI agent, capable of executing tasks beyond simple text generation by interacting with external systems like databases, applications, and other services. This enables it to perform real-time data updates and automate complex workflows. > > * **Retrieval-augmented generation (RAG)**: Equipped with RAG, Palmyra X4 can retrieve and incorporate relevant information from vast data sources, enhancing the model's accuracy and ensuring responses are always grounded in current, context-specific data. > > * **Code generation**: The model supports advanced code generation, enabling it to automate scripting and integrate seamlessly with various programming environments, optimizing workflows for technical teams. > > * **Tool calling**: Palmyra X4 is built to handle precise API interactions, allowing it to execute complex functions directly, making it a versatile tool for enterprise-level integrations and automated actions. > > > [tab] Benchmarking > > > > Palmyra X4 consistently ranks at the top in structured output, API tool calling, and accuracy for complex, multi-step workflows. > > > > * **Top accuracy (ACC)**: Palmyra X4 achieves 78.76% accuracy in tool call identification and execution, leading the industry by nearly 20%. > > * **Structured call planning (AST)**: Palmyra X4 scores 87.93% in planning and organizing tool calls, accurately interpreting input, generating parameters, and sequencing steps. > > * **Execution performance (Exec)**: With an 88.27% score in executing tool calls, Palmyra X4 ranks highest in efficiently carrying out enterprise actions. > > * **Global benchmarks**: Palmyra X4 ranks in the world's top 10 on HELM Lite (86.1%) and HELM MMLU (81.3%), excelling across 57 subjects. ## Using models with the Writer API > [tab] Chat completions > > To select the Palmyra model you want to use for a chat completion, specify the model ID in the [`model` parameter](/api-reference/completion-api/chat-completion#body-model) of the request. > > Below is an example of specifying the `palmyra-x5` model in a chat completion request. > > ```bash cURL theme={null} > curl --location 'https://api.writer.com/v1/chat' \ > --header 'Content-Type: application/json' \ > --header "Authorization: Bearer $WRITER_API_KEY" \ > --data '{ > "model": "palmyra-x5", > "messages": [ > { > "role": "user", > "content": "Summarize GDPR compliance requirements for a cloud-based data storage provider" > } > ] > }' > ``` > > ```python Python theme={null} > from writerai import Writer > > # Initialize the client. If you don't pass the `api_key` parameter, > # the client looks for the `WRITER_API_KEY` environment variable. > client = Writer() > > chat_response = client.chat.chat( > model="palmyra-x5", > messages=[ > { > "role": "user", > "content": "Summarize GDPR compliance requirements for a cloud-based data storage provider" > } > ] > ) > > print(chat_response.choices[0].message.content) > ``` > > ```javascript JavaScript theme={null} > import { Writer } from "writer-sdk"; > > // Initialize the client. If you don't pass the `apiKey` parameter, > // the client looks for the `WRITER_API_KEY` environment variable. > const client = new Writer(); > > const chat_response = await client.chat.chat({ > model: "palmyra-x5", > messages: [ > { > role: "user", > content: > "Summarize GDPR compliance requirements for a cloud-based data storage provider", > }, > ], > }); > > console.log(chat_response.choices[0].message.content); > ``` > > You can also use [prebuilt tools](/home/tool-calling) within a general-purpose chat completion request: > > * [LLM tool](/home/model-delegation) to call another model > * [Knowledge Graph tool](/home/kg-chat) to ask questions about a Knowledge Graph > > To analyze images, use [vision capabilities with Palmyra X5](/home/chat-with-images) directly in a chat completion. > [tab] Text generation > > To select the Palmyra model you want to use for text generation, specify the model ID in the [`model` parameter](/api-reference/completion-api/text-generation#body-model) of the request. > > Below is an example of specifying the `palmyra-x5` model in a text generation request. > > ```bash cURL theme={null} > curl --location 'https://api.writer.com/v1/completions' \ > --header 'Content-Type: application/json' \ > --header "Authorization: Bearer $WRITER_API_KEY" \ > --data '{ > "model": "palmyra-x5", > "prompt": "Summarize GDPR compliance requirements for a cloud-based data storage provider" > }' > ``` > > ```python Python theme={null} > from writerai import Writer > > # Initialize the client. If you don't pass the `api_key` parameter, > # the client looks for the `WRITER_API_KEY` environment variable. > client = Writer() > > text_generation = client.completions.create( > model="palmyra-x5", > prompt="Summarize GDPR compliance requirements for a cloud-based data storage provider" > ) > > print(text_generation.choices[0].text) > ``` > > ```javascript JavaScript theme={null} > import { Writer } from "writer-sdk"; > > // Initialize the client. If you don't pass the `apiKey` parameter, > // the client looks for the `WRITER_API_KEY` environment variable. > const client = new Writer(); > > const text_generation = await client.completions.create({ > model: "palmyra-x5", > prompt: > "Summarize GDPR compliance requirements for a cloud-based data storage provider", > }); > > console.log(text_generation.choices[0].text); > ``` Get started with the Writer API by signing up for a free account and following the [API quickstart](/home/quickstart). ## Deprecation policy ### Timeline for deprecation * We'll announce the deprecation of a model at least three months in advance. This will give customers time to plan for the migration to the new model. * We'll continue to support deprecated models for a period of time after they're deprecated. This will give customers time to migrate to the new model. * We'll eventually stop supporting deprecated models. The timeline for this will vary depending on the model. We will announce the end of support for a deprecated model at least six months in advance. ### Deprecated models | Model name | Deprecation Date | | - | - | | Palmyra X5 | 2026-12-14 | | Palmyra X4 | 2026-12-14 | | Palmyra X 003 Instruct | 2026-07-13 | | Palmyra Vision | 2026-07-13 | | Palmyra Med | 2026-07-13 | | Palmyra Fin | 2026-07-13 | | Palmyra Creative | 2026-07-13 | | Palmyra Fin 32k | 2025-03-03 | | Palmyra X 002 32k | 2024-09-06 | | Palmyra X 32k Instruct | 2024-09-06 | | Palmyra X 002 Instruct | 2024-09-06 | ### Migration path * We'll provide customers with a migration path to the new model, including detailed documentation and support to help them migrate their applications. * We'll also offer training and consulting services to help customers transition. # Choose a model Source: https://dev.writer.com/home/models-overview Compare Writer's Palmyra models with external provider models to select the best fit for your AI agents > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. This guide helps you choose between Writer's Palmyra models and external provider models when building agents in Control Center. Both options are available through the [Models page](https://app.writer.com/controlcenter) in Control Center. ## Palmyra models Writer's [Palmyra models](/home/models) are pre-configured and immediately available in Control Center. The Palmyra family includes: | Model | Best for | Available in | | - | - | - | | [Palmyra X6](/home/models#palmyra-x6) | Long-horizon agentic workflows, WRITER Agent, sub-agents, grounding, and MCP tool use | [WRITER Agent](/home/pricing#writer-agent), API | | [Palmyra X5](/home/models#palmyra-x5) | General-purpose tasks with advanced reasoning, including financial, medical, and creative use cases | Agent Builder, no-code, API | | [Palmyra X4](/home/models#palmyra-x4) | Complex tasks requiring extended context | Agent Builder, no-code, API | For detailed capabilities, context windows, and use cases, see [Palmyra models](/home/models). For pricing, see [Palmyra pricing](/home/pricing). Palmyra X6 is the default model for [WRITER Agent](/home/pricing#writer-agent). Palmyra X6, X5, and X4 are available via API. Palmyra X5 and X4 are also available in Agent Builder and no-code apps. ## External models You can also add models from external providers like AWS Bedrock or OpenRouter to use alongside Palmyra models. External models require credential configuration but provide access to models like Claude, Llama, and Mistral. | Provider | Status | Setup guide | | - | - | - | | AWS Bedrock | Available | [Configure AWS Bedrock](/providers/aws-bedrock) | | OpenRouter | Available | [Configure OpenRouter](/providers/openrouter) | For information about adding and managing external models, see [Add external models](/home/external-models). ## Compare Palmyra and external models Consider the following factors when selecting models for your agents: | Consideration | Palmyra models | External models | | - | - | - | | **Setup** | Pre-configured, immediately available | Requires credential configuration | | **Optimization** | Optimized for Writer platform | Varies by provider | | **Specialized domains** | Palmyra X5 covers general-purpose, financial, medical, and creative use cases | General-purpose models | | **Compliance** | Writer-managed compliance | You manage provider compliance | | **Billing** | Unified billing through Writer | Provider rate card plus a [10% WRITER pass-through fee](/home/pricing#external-models-byom) (paid via credits). See [Add external models](/home/external-models). | | **Cost visibility** | Included in Writer dashboard | Tracked in Writer + provider billing | ### When to use Palmyra models Palmyra models are the best choice when you need: * **Domain-specific capabilities**: Palmyra X5 covers general-purpose, financial, medical, and creative use cases * **Simplified billing**: All usage appears on your Writer invoice * **Writer platform features**: Optimized integration with Knowledge Graphs and other Writer capabilities * **Compliance simplicity**: Writer manages model compliance and security ### When to use external models External models are the best choice when you need: * **Existing provider agreements**: You have AWS credits or enterprise agreements with cloud providers * **Specific model access**: You need a particular model not available through Writer (for example, Claude, Llama, or Mistral on Bedrock) * **Provider-specific compliance**: Your organization mandates specific cloud providers for AI workloads * **Model comparison**: You want to evaluate performance across different model providers For information about adding and managing external models, see [Add external models](/home/external-models). ## Use models in your applications Palmyra models are available on different Writer surfaces depending on the model: ### WRITER Agent [WRITER Agent](https://support.writer.com/article/235-ask-writer) uses [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) by default. ### Agent Builder In [Agent Builder](/home/agent-builder/overview), select a model from the **Model** dropdown. Palmyra X5 and X4 appear in the list, along with any external models your team has access to. Palmyra X6 is not available in Agent Builder. ### API usage Palmyra X5 and X4 are available via the API. Use the [List models](/api-reference/completion-api/list-models) endpoint to see all models available to your organization. You can then pass the model ID in any request that supports the `model` parameter. ```bash cURL theme={null} curl https://api.writer.com/v1/models \ -H "Authorization: Bearer $WRITER_API_KEY" ``` ```python Python theme={null} from writerai import Writer client = Writer() models = client.models.list() for model in models.models: print(model.id) ``` ```javascript JavaScript theme={null} import Writer from "writer-sdk"; const client = new Writer(); const models = await client.models.list(); models.models.forEach((model) => console.log(model.id)); ``` To use a model, pass its ID to any completion endpoint. External models use the same API as Palmyra models—just swap the model ID: ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/chat' \ -H "Authorization: Bearer $WRITER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "anthropic.claude-3-sonnet-20240229-v1:0", "messages": [{"role": "user", "content": "Hello!"}] }' ``` ```python Python theme={null} from writerai import Writer client = Writer() response = client.chat.chat( model="anthropic.claude-3-sonnet-20240229-v1:0", messages=[{"role": "user", "content": "Hello!"}] ) print(response.choices[0].message.content) ``` ```javascript JavaScript theme={null} import Writer from "writer-sdk"; const client = new Writer(); const response = await client.chat.chat({ model: "anthropic.claude-3-sonnet-20240229-v1:0", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` ## Next steps * [Add external models](/home/external-models): Configure external models from providers like AWS Bedrock * [Palmyra models](/home/models): Explore Writer's Palmyra model capabilities # Observability overview Source: https://dev.writer.com/home/observability Monitor events, errors, and performance across your Control Center deployment Use Control Center observability tools to inspect captured LLM calls, correlate calls with agent execution legs, and review organization-wide usage. These views help you debug agent behavior and monitor performance, either in Control Center or through external platforms your team already uses. > [!NOTE] > > These views don't yet include [Agent Builder v2](/home/agent-builder/overview) agent events. Agent Builder v2 agents have their own per-agent observability—see [Agent Builder v2 observability](/home/agent-builder/observability). ## Built-in observability Control Center includes the following observability features out of the box: > [card] [Event logs](/home/event-logs) > > Inspect captured LLM calls, their success or failure status, and related > agent-run timing. Logs are not a ledger of every platform action. > [card] [Usage and spend](/home/usage-and-spend) > > Track organization-wide costs, token consumption, and spending trends. > [card] [Agent Builder v2 observability](/home/agent-builder/observability) > > Review request performance, events, usage, and server/deployment logs for > an individual Agent Builder v2 agent. ## External observability Poll the export APIs to pull organization-scoped captured LLM calls, terminal agent execution-leg records, and audit events into a warehouse, SIEM, or analytics platform. Call latency and execution-leg duration are separate from session or conversation logs. Availability can be delayed, and missing source telemetry is not reconstructed. > [card] [Export logs](/home/logs-export) > > Poll call and terminal-run records in ingestion order and resume from a cursor. > [card] [Export audit events](/home/audit-events-export) > > Poll organization audit events for a SIEM or compliance platform and resume from a cursor. ## Next steps Choose the view that matches the activity you need to investigate. * [Event logs](/home/event-logs): Inspect captured LLM calls and related agent runs * [Export logs](/home/logs-export): Poll call and terminal-run records into a warehouse or SIEM * [Export audit events](/home/audit-events-export): Poll audit events into a SIEM or compliance platform * [Usage and spend](/home/usage-and-spend): Track organization-wide costs and token consumption * [Agent Builder v2 observability](/home/agent-builder/observability): Review performance, events, usage, and logs for an individual agent # Parse a PDF Source: https://dev.writer.com/home/parse-pdf > [!WARNING] > > **Deprecation notice**: The [parse PDF API endpoint](/api-reference/tool-api/pdf-parser) at `/v1/tools/pdf-parser/{file_id}` is deprecated and will be removed on **December 22, 2025**. > > **Migration path**: We plan to introduce a prebuilt PDF parsing tool for chat completions that will provide similar functionality. This tool will work similarly to other prebuilt tools like the [LLM tool](/home/model-delegation). We will provide more details about this alternative when it becomes available. The [PDF parser endpoint](/api-reference/tool-api/pdf-parser) converts PDF documents into other formats. This is useful when you need to extract and process text content from PDF files for further analysis or integration into your workflow. ## Use cases * Converting research papers from PDF to searchable text for analysis * Extracting content from business reports for data processing * Converting PDF documentation into markdown format for web publishing * Making archived PDF documents searchable and analyzable * Automating data extraction from PDF forms and invoices > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Endpoint overview **URL:** `POST https://api.writer.com/v1/tools/pdf-parser` ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/tools/pdf-parser/' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "format": "markdown" }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.tools.parse_pdf( file_id="file_id", format="text", ) print(response.content) ``` ```javascript JavaScript theme={null} import Writer from 'writer-sdk'; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); async function main() { const response = await client.tools.parsePdf('file_id', { format: 'text' }); console.log(response.content); } main(); ``` ### Path parameters | Parameter | Description | | - | - | | `file_id` | The ID of the uploaded PDF file to parse. | Before using the PDF parser, you'll need to upload your PDF file to the Writer API and obtain its file ID. Learn more about how to upload files with the [Files API](/home/files). ### Request body The request body includes the following parameters: | Parameter | Type | Description | | - | - | - | | `format` | `string` | The desired output format. Can be `text` or `markdown`. | ### Response parameters Returns an object with a `content` field containing the extracted text in the specified format. ```json JSON theme={null} { "content": "..." } ``` # Pricing Source: https://dev.writer.com/home/pricing View pricing for Writer AI models. Compare costs per million tokens for the Palmyra X6, X5, and X4 models. > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. > [!NOTE] > > For any custom pricing, **[contact Sales](https://go.writer.com/contact-sales)**. ## Base model The table below outlines our [base model](/home/models#models), which is focused on text input and output. The input and output prices are displayed per 1M tokens unless otherwise specified. | Model name | Model ID | Input / 1M | Output / 1M | | - | - | - | - | | [Palmyra X6](/home/models#palmyra-x6) | `palmyra-x6` | \$2.00 | \$8.00 | | [Palmyra X5](/home/models#palmyra-x5) | `palmyra-x5` | \$0.60 | \$6.00 | | [Palmyra X4](/home/models#palmyra-x4) | `palmyra-x4` | \$2.50 | \$10.00 | > [!NOTE] > > Palmyra X5 in [WRITER Agent](#writer-agent) is billed at \$5.00 input and \$12.00 output per 1M tokens. The Palmyra X5 rate in this table applies to API, Agent Builder, and no-code usage. ## WRITER Agent [WRITER Agent](https://support.writer.com/article/235-ask-writer) uses [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) as the default agent model. Usage is billed at the Palmyra X6 model rate, unless a different model is chosen. Admins can enable additional WRITER-managed models or connect bring your own model (BYOM) models from the **Models** page in [Control Center](https://app.writer.com/controlcenter). Input and output rates for each model are shown there before an admin enables it. Model usage in WRITER Agent is billed as follows: | | WRITER-managed | BYOM | | - | - | - | | **Models** | Palmyra and [WRITER-managed third-party models](#writer-managed-third-party-models) enabled from the WRITER catalog | [External models](/home/external-models) connected with your credentials via BYOM (AWS Bedrock or OpenRouter) | | **Provider account** | Not required | Required | | **Billing** | Metered per token through WRITER (1 credit = 1 USD) at the rate shown for each model | Provider rate card plus 10% WRITER pass-through fee (paid via credits). See [external models (BYOM)](#external-models-byom). | | **Usage visibility** | WRITER dashboard | WRITER dashboard and provider billing | | **Availability** | Included with WRITER-managed model access | Enterprise plans | Connector usage, Knowledge Graph, and other WRITER Agent capabilities are priced under their own sections on this page, not as part of model token rates. ## WRITER-managed third-party models The table below lists rates for third-party models in the WRITER catalog. These models are WRITER-managed and available in WRITER Agent only. WRITER meters usage and bills you at the rates shown here. Prices are per 1M tokens unless otherwise specified. This table does not apply to [external models (BYOM)](#external-models-byom). > [!WARNING] > > Rates are subject to change. Last updated: 11/20/26. | Model name | Model ID | Input / 1M | Output / 1M | | - | - | - | - | | Claude Fable 5.2 | `anthropic/claude-fable-5.2` | \$8.00 | \$40.00 | | Claude Haiku 5.5 | `anthropic/claude-haiku-5.5` | \$0.10 | \$0.50 | | Claude Opus 4.5 | `anthropic/claude-opus-4.5` | \$5.00 | \$25.00 | | Claude Opus 4.7 | `anthropic/claude-opus-4.7` | \$5.00 | \$25.00 | | Claude Opus 5 | `anthropic/claude-opus-5` | \$5.00 | \$25.00 | | Claude Opus 5.5 | `anthropic/claude-opus-5.5` | \$4.00 | \$20.00 | | Claude Sonnet 4.5 | `anthropic/claude-sonnet-4.5` | \$3.00 | \$15.00 | | Claude Sonnet 4.6 | `anthropic/claude-sonnet-4.6` | \$3.00 | \$15.00 | | Claude Sonnet 5 | `anthropic/claude-sonnet-5` | \$2.00 | \$10.00 | | Claude Sonnet 5.5 | `anthropic/claude-sonnet-5.5` | \$2.00 | \$10.00 | | DeepSeek V4 Flash | `deepseek/deepseek-v4-flash` | \$0.09 | \$0.18 | | DeepSeek V4 Pro | `deepseek/deepseek-v4-pro` | \$0.44 | \$0.87 | | DeepSeek V4.1 Flash | `deepseek/deepseek-v4.1-flash` | \$0.30 | \$1.20 | | Gemini 2.5 Flash | `google/gemini-2.5-flash` | \$0.30 | \$2.50 | | Gemini 3 Flash Preview | `google/gemini-3-flash-preview` | \$0.50 | \$3.00 | | Gemini 3 Pro Image Preview | `google/gemini-3-pro-image-preview` | \$2.00 | \$12.00 | | Gemini 3.1 Pro Preview | `google/gemini-3.1-pro-preview` | \$2.00 | \$12.00 | | Gemini Omni Flash Preview | `google/gemini-omni-flash-preview` | \$1.50 | \$17.50 | | Gemini Omni 1.1 Flash Preview | `google/gemini-omni-1.1-flash-preview` | \$1.50 | \$17.50 | | Gemini 3.5 Flash | `google/gemini-3.5-flash` | \$1.50 | \$9.00 | | Gemini 3.5 Flash Lite | `google/gemini-3.5-flash-lite` | \$0.30 | \$2.50 | | Gemini 3.6 Flash | `google/gemini-3.6-flash` | \$0.75 | \$3.75 | | Gemini 3.7 Flash | `google/gemini-3.7-flash` | \$0.75 | \$3.75 | | Gemini 3.8 Flash | `google/gemini-3.8-flash` | \$0.825 | \$4.125 | | Gemini 4 Argon | `google/gemini-4-argon` | \$2.00 | \$10.00 | | Nano Banana 2 (Gemini 3.1 Flash Image) | `google/gemini-3.1-flash-image` | \$0.50 | \$3.00 | | Nano Banana 2 Lite (Gemini 3.1 Flash Lite Image) | `google/gemini-3.1-flash-lite-image` | \$0.25 | \$1.50 | | Nano Banana Pro (Gemini 3 Pro Image) | `google/gemini-3-pro-image` | \$2.00 | \$12.00 | | Gemini 3.8 Flash TTS | `google/gemini-3.8-flash-tts` | \$0.50 | \$9.00 | | Gemini 4 Neon | `google/gemini-4-neon` | \$3.00 | \$15.00 | | Lyria 3 Pro Preview | `google/lyria-3-pro-preview` | \$0.00 | \$25.00 | | Veo 3.1 | `google/veo-3.1` | \$0.40/second | \$0.00 | | MiniMax M2.5 | `minimax/minimax-m2.5` | \$0.15 | \$0.90 | | Kimi K2.5 | `moonshotai/kimi-k2.5` | \$0.38 | \$2.03 | | Kimi K2.6 | `moonshotai/kimi-k2.6` | \$0.66 | \$3.41 | | GPT 5.4 Image 2 | `openai/gpt-5.4-image-2` | \$8.00 | \$15.00 | | GPT 5.4 Nano | `openai/gpt-5.4-nano` | \$0.20 | \$1.25 | | GPT OSS 120B | `openai/gpt-oss-120b` | \$0.04 | \$0.18 | | GPT-5.5 | `openai/gpt-5.5` | \$5.00 | \$30.00 | | GPT-5.6 Luna | `openai/gpt-5.6-luna` | \$0.20 | \$1.20 | | GPT-5.6 Luna Pro | `openai/gpt-5.6-luna-pro` | \$0.20 | \$1.20 | | GPT-5.6 Sol | `openai/gpt-5.6-sol` | \$4.00 | \$20.00 | | GPT-5.6 Sol Pro | `openai/gpt-5.6-sol-pro` | \$4.00 | \$20.00 | | GPT-5.6 Terra | `openai/gpt-5.6-terra` | \$2.00 | \$12.00 | | GPT-5.6 Terra Pro | `openai/gpt-5.6-terra-pro` | \$2.00 | \$12.00 | | GPT-6 Astra | `openai/gpt-6-astra` | \$10.00 | \$50.00 | | GPT-6 Astra Pro | `openai/gpt-6-astra-pro` | \$10.00 | \$50.00 | | GPT-6 Luna | `openai/gpt-6-luna` | \$0.10 | \$0.50 | | GPT-6 Luna Pro | `openai/gpt-6-luna-pro` | \$0.10 | \$0.50 | | GPT-6 Sol | `openai/gpt-6-sol` | \$2.00 | \$10.00 | | GPT-6 Sol Pro | `openai/gpt-6-sol-pro` | \$2.00 | \$10.00 | | GPT-6.1 Sol | `openai/gpt-6.1-sol` | \$2.00 | \$10.00 | | GPT-6.1 Sol Pro | `openai/gpt-6.1-sol-pro` | \$2.00 | \$10.00 | | GPT-6.1 Terra | `openai/gpt-6.1-terra` | \$1.00 | \$5.00 | | GPT-6.1 Terra Pro | `openai/gpt-6.1-terra-pro` | \$1.00 | \$5.00 | | GPT-6.2 Astra | `openai/gpt-6.2-astra` | \$8.00 | \$40.00 | | GPT-6.2 Astra Pro | `openai/gpt-6.2-astra-pro` | \$8.00 | \$40.00 | | GPT-6.2 Sol | `openai/gpt-6.2-sol` | \$2.00 | \$10.00 | | GPT-6.2 Sol Pro | `openai/gpt-6.2-sol-pro` | \$2.00 | \$10.00 | | GLM 4.7 | `z-ai/glm-4.7` | \$0.40 | \$1.75 | | GLM 5 | `z-ai/glm-5` | \$0.60 | \$1.92 | | GLM 5.1 | `z-ai/glm-5.1` | \$0.98 | \$3.08 | ## External models (BYOM) Bring your own model (BYOM) connects [external models](/home/external-models) via your AWS Bedrock or OpenRouter credentials. Usage is billed at your provider's rate card plus a **10% WRITER pass-through fee** (paid via credits). BYOM is available on Enterprise plans across WRITER Agent and the API. ## Palmyra Vision (deprecated) The table below outlines pricing for Palmyra Vision, which takes in a variety of inputs and produces text as an output. The input and output price is for 1M tokens unless otherwise specified. Palmyra Vision is deprecated. Use [chat with images](/home/chat-with-images) with Palmyra X5 instead. | Type | Input | Output / 1M | | - | - | - | | Image | \$0.005/image | \$8.00 | | Video | \$0.005/second | \$8.00 | | Text | \$7.50/1M | \$22.50 | ## Knowledge Graph The table below outlines pricing for [Knowledge Graph](/home/knowledge-graph), Writer's graph-based RAG. | Capability | Cost | | - | - | | Data extraction | \$0.00015/page | | File parsing (OCR) | \$0.055/page | | Web Access | \$0.12/page | Data connectors for Knowledge Graph are available for Enterprise plans. To learn, more please [contact Sales](https://go.writer.com/contact-sales). ## Tools API The table below outlines pricing for the [Tools API](/api-reference/tool-api/), which provides utilities for pre-processing and comprehending text. | Tool | Cost | | - | - | | [PDF parser](/api-reference/tool-api/pdf-parser) | \$0.055/page | ## Deprecated models The table below show pricing for deprecated models. See the [deprecation policy](/home/models#deprecation-policy) for more information. | Model name | Deprecation date | Input / 1M | Output / 1M | | - | - | - | - | | Palmyra X5 | 2026-12-14 | \$0.60 | \$6.00 | | Palmyra X4 | 2026-12-14 | \$2.50 | \$10.00 | | Palmyra X 003 Instruct | 2026-07-13 | \$7.50 | \$22.50 | | Palmyra Vision | 2026-07-13 | [See above](#palmyra-vision-deprecated) | [See above](#palmyra-vision-deprecated) | | Palmyra Med | 2026-07-13 | \$5.00 | \$12.00 | | Palmyra Fin | 2026-07-13 | \$5.00 | \$12.00 | | Palmyra Creative | 2026-07-13 | \$5.00 | \$12.00 | | Palmyra Fin 32k | 2025-03-03 | \$5.00 | \$12.00 | | Palmyra X 002 32k | 2024-09-06 | \$1.00 | \$2.00 | | Palmyra X 32k Instruct | 2024-09-06 | \$1.00 | \$2.00 | | Palmyra X 002 Instruct | 2024-09-06 | \$1.00 | \$2.00 | # Private endpoints Source: https://dev.writer.com/home/private-endpoints Connect WRITER Agent to connectors over a private network using AWS PrivateLink or GCP Private Service Connect A private endpoint is a network path between Writer's MCP gateway and a service in your VPC. Instead of sending connector traffic over the public internet, Writer connects through [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html) or [GCP Private Service Connect](https://cloud.google.com/vpc/docs/private-service-connect) so requests stay on your cloud provider's private network. > [!NOTE] > > For prebuilt connectors, contact your customer success manager to enable > private endpoints. You can enable private endpoints on custom connectors > during connector setup in Control Center. ## Prerequisites Before setting up a private endpoint, make sure you have: * Administrator access to your Writer organization * Administrator access to your AWS or GCP account * A service running in your VPC that you want to expose to WRITER Agent ## Create a private endpoint in your cloud provider The first step is to create a private endpoint service in AWS or GCP that exposes your service to Writer. ### AWS PrivateLink Create a VPC endpoint service in AWS that allows Writer to connect to your service privately. 1. Follow the AWS documentation to [create an endpoint service](https://docs.aws.amazon.com/vpc/latest/privatelink/create-endpoint-service.html) 2. When configuring allowed principals, add the Writer AWS account so that Writer can connect to your endpoint service 3. Copy the **Service name** (for example, `com.amazonaws.vpce.us-east-1.vpce-svc-xxxxxxxx`) for use in Control Center ### GCP Private Service Connect Create a published service in GCP that allows Writer to connect to your service privately. 1. Follow the GCP documentation to [configure Private Service Connect as a producer](https://cloud.google.com/vpc/docs/configure-private-service-connect-producer) 2. When configuring accepted consumers, add the Writer GCP project so that Writer can connect to your service 3. Copy the **Service attachment URI** (for example, `projects/PROJECT/regions/REGION/serviceAttachments/SERVICE_ATTACHMENT`) for use in Control Center ## Add the private endpoint in Control Center After creating the endpoint service in your cloud provider, add it in Control Center so it's available when configuring connectors. 1. Navigate to **Security & compliance** in [Control Center](https://app.writer.com/controlcenter) 2. Select **Private endpoints** 3. Select **Add private endpoint** 4. Enter the following details: * **Name**: A descriptive name for the private endpoint * **Cloud provider**: Select **AWS** or **GCP** * **Region**: The region where your endpoint service is hosted * **Service name** (AWS) or **Service attachment URI** (GCP): The identifier you copied from your cloud provider 5. Select **Save** to add the private endpoint The new private endpoint appears in your list and is available when you configure connectors. ## Use a private endpoint with a custom connector After you add a private endpoint in Control Center, attach it when you create or edit a [custom connector](/home/custom-connectors): 1. Create or edit a custom connector in Control Center under **Integrations > Connectors** 2. In the **Connect** step, toggle **Enable private endpoint** on 3. Select the private endpoint you added 4. Complete the rest of the connector configuration WRITER Agent routes requests for that connector through the selected private endpoint instead of the public internet. ## Next steps * [Configure connectors](/home/mcp-gateway): Learn about connector authentication and access control * [Custom connectors](/home/custom-connectors): Create custom connectors from OpenAPI specifications or MCP servers * [Set up connectors](https://support.writer.com/article/299-setting-up-connectors): Configure prebuilt connectors in Control Center * [MCP gateway overview](/home/mcp-gateway): Learn about Writer's MCP gateway architecture # Secure prompts against attacks Source: https://dev.writer.com/home/prompt_injections Security measures against prompt injections, jailbreak attacks, and secrets leakage ## Introduction As AI systems like Writer models become increasingly integrated into a wide range of applications, the importance of securing them against various types of attacks becomes paramount. In this article, we delve into the technical details of how Writer safeguards its AI models against prompt injections, jailbreak attempts, and the leakage of sensitive information. ## Measures against prompt injections > [tab] Input sanitization > > One of the first lines of defense is input sanitization, where incoming prompts are screened for potentially malicious code or harmful strings. Sophisticated Natural Language Processing (NLP) techniques, combined with standard cybersecurity measures, are used to detect and remove or neutralize suspicious inputs. > [tab] Rate limiting > > To prevent brute-force attacks and other malicious activities, Writer often implements [rate limiting](/api-reference/rate-limits) on the API requests. This ensures that a user can't overload the system with a large number of potentially harmful prompts in a short amount of time. > [tab] RBAC > > Role-cased access control (RBAC) to more advanced or potentially risky functionalities is restricted based on roles. This prevents unauthorized users from injecting malicious prompts that could potentially exploit these functionalities. ## Safeguards against jailbreak attacks > [tab] Runtime environment isolation > > The runtime environment in which the AI models operate is isolated from the rest of the system. This isolation is often achieved using containerization technologies like Docker, which limit the resources and system calls available to the running model. > [tab] Anomaly detection systems > > Advanced anomaly detection systems are put in place to monitor the behavior of the AI models in real-time. Any unusual patterns or inconsistencies could trigger alerts, initiating immediate investigation and potential shutdown of the affected instance. > [tab] Code review and static analysis > > Before deployment, the codebase undergoes rigorous reviews and static analysis to ensure that there are no vulnerabilities that could be exploited to "jailbreak" the AI system. ## Measures against secrets leakage > [tab] Encryption and secure storage > > All sensitive information, including security keys and credentials, is encrypted using state-of-the-art encryption algorithms. These encrypted secrets are stored in secure vaults that are accessible only to authorized personnel. > [tab] Zero trust architecture > > A Zero trust architecture is employed, which means that every request or interaction with the AI system is treated as potentially malicious until proven otherwise. This adds an extra layer of security against unauthorized access and data leakage. ## Conclusion Security is a multi-faceted challenge that requires a holistic approach. Writer employs a combination of advanced technologies and best practices to safeguard its AI models against prompt injections, jailbreak attacks, and the leakage of sensitive information. While no system can be 100% secure, these measures provide a robust framework for identifying, mitigating, and responding to various security threats. # Write effective prompts Source: https://dev.writer.com/home/prompting Master prompting fundamentals and advanced techniques. Learn directive writing, context inclusion, few-shot prompting, and chain-of-thought reasoning. This guide covers the [fundamentals](/home/prompting#fundamentals) behind prompting strategies and discusses some [advanced techniques](/home/prompting#advanced-techniques). For in-depth information on prompting, see the Writer [prompt crafting guide](https://writer.com/guides/prompt-crafting/). ## Fundamentals > [card] Directive writing > > Be direct and to the point: > > Write a short summary of the article titled "The Impact of Artificial Intelligence on Employment" > [card] Inclusive prompts > > Include your audience in your prompt: > > Explain the implications of the recent changes in tax laws for small business owners in California. > [card] Structured formatting > > Format your prompt with *### Instruction ###*, followed by *### Question > \###*: > > **### Instruction ###** \ > Write a poem in the style of > Robert Frost. \\ > > **### Question ###** > \ > What's the poem about? > [card] Task breakdown > > Break down complicated tasks into multiple prompts: > > First, provide a brief overview of derivatives. Then, explain how it's related to credit risk. > [card] Positive language > > Use directives like "do" instead of "don't": > > Do provide an analysis of the potential benefits and drawbacks of using renewable energy sources in the manufacturing industry, focusing on the economic, environmental, and social impacts. > [card] Mandatory instructions > > Use phrases like *You MUST*: > > You must provide a step-by-step guide to setting up a WordPress website, including domain registration, web hosting, and content creation. > [card] Penalty warning > > Use phrases like *You'll be penalized*: > > You’ll be penalized if you don't include at least three different methods for solving the following math problem: Find the area of a circle with a radius of 5 units. > [card] Natural responses > > Request a simple response: > > Please provide a brief explanation of the difference between a virus and a bacterium, answering in a natural, human-like manner. > [card] Unbiased descriptions > > Make sure that your answer is unbiased and doesn’t rely on stereotype: > > Please describe the cultural significance of sushi in Japan, making sure that your answer is unbiased. > [card] Educational writing > > To write an essay, text, paragraph, article, or any detailed text: > > Write a detailed essay for me on the history of the monetary policy. > [card] Style consistency > > Improve the tone of the text to make the writing style more > professional: > > Revise the following paragraph to improve its grammar and vocabulary, but make sure that the writing style remains formal. > [card] Creative writing > > I'll give you the beginning of a story. Finish it and keep the flow > consistent: > > As the sun began to set, the sky turned a deep shade of orange. The birds returned to their nests, and the crickets started to chirp. > [card] Linguistic mimicry > > Use the same language as the following paragraph to explain the importance > of exercise: > > The practice of meditation has been around for thousands of years. It's a way to calm the mind and body, and it can be done almost anywhere. > [card] Precise instructions > > Clearly state the requirements that the model must follow to produce > content, in the form of keywords or instructions. \\ > > Write a short summary of the article titled 'The Impact of AI on Employment'. Ensure that the summary is no longer than 150 words and includes the main arguments. ## Advanced techniques > [card] Example driven prompts > > Use example-driven (few-shot) prompting: > > Provide a list of idioms in English, along with their meanings and example > sentences. > > Here is an example for the output: \\ > > **An idiom**: 'Break a leg' \ > **Meaning**: Good luck \ > **Example sentence**: 'I'm sure you'll do great in your interview. > Break a leg!' > [card] Chain-of-thought Prompts > > Combine chain-of-thought (CoT) prompts with few-shot prompts: > > **System instruction:** Create a product detail page for a > fictional innovative smartphone by a retailer known as "TechTrend > Electronics." > > **Prompt 1:** Start by describing the unique features of the smartphone, > such as its solar-powered battery, triple-lens camera system, and foldable > screen technology. > > **Prompt 2:** Next, outline the benefits of these features > for users, like extended battery life, exceptional photo quality, and > enhanced device portability. > > **Prompt 3:** Conclude with crafting compelling product descriptions > and a call-to-action that entices customers to make a purchase during the upcoming > holiday sale. > [card] Delimited prompts > > Use delimiters to structure text: > > Summarize a series of healthcare claims documents for a fictional > healthcare company, 'HealthFirst Solutions', using the following delimiter `\n` > to separate different sections of the summary: > > **Claim Number:** 123456789 `\n` \ > **Date of Service:** January 1, 2024 `\n` \ > **Diagnosis:** Acute sinusitis `\n` \ > **Total Claimed:** \$300 `\n` \ > **Status:** Pending review `\n` \\ # Quickstart Source: https://dev.writer.com/home/quickstart Make your first API call to Writer. Create an API key and generate text using the chat completion endpoint in minutes. This guide shows you how to make your first API calls to the Writer API. After you create an API key in [Control Center](https://app.writer.com/controlcenter), you can generate text with the [chat completion endpoint](/api-reference/completion-api/chat-completion). > [!WARNING] > > **Deprecation notice**: Legacy API keys (keys created under the previous API agent model) will stop working on **January 1, 2027**. > > **Migration path**: Create a new API key, update your applications to use the new key, then revoke the legacy key. ## Get an API key Before you can make API calls, create an API key in [Control Center](https://app.writer.com/controlcenter). **1. Navigate to API Keys** From the [Control Center home page](https://app.writer.com/controlcenter), open **Security & compliance** in the left sidebar, then select **API Keys**. **2. Open Generate an API Key** Select **New** to open the **Generate an API Key** page. **3. Configure the key** Under **About**, enter a **Key name** and an optional **short description**. Under **Who can use this key?**, choose **All teams** or **Specific user**: * For **All teams**, the key is an organization key. You are the key owner. * For **Specific user**, choose the user who owns the key. Under **Limits**, set **Expiration** (for example, **No expiration** or a preset duration). Under **Permissions**, turn on the capabilities this key needs, such as **Models** for chat completions. **4. Generate and copy your API key** Select **Generate**. When the key appears, copy the full value and store it in a secure place. Acknowledge that you have copied the key before you leave the page. You can't view or reveal the full key again after that. > [!WARNING] > > Copy and store the key as soon as it's shown. After you leave this step, the full value is no longer available. > [!TIP] > > Store the API key in a secure location, such as a `.env` file. You can now make calls to the Writer API using this API key as the `Bearer` token in the header: ``` Authorization: Bearer ``` Learn more about creating and managing API keys in the [API keys guide](/api-reference/api-keys). ## Make your first API call Below is an example of an API call to the [chat completion endpoint](/home/chat-completion). It completes a single-turn chat completion, where the user provides a message and the AI assistant generates a response. The request is non-streaming and waits until the response is complete before returning. ```bash theme={null} curl --location 'https://api.writer.com/v1/chat' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "model": "palmyra-x5", "messages": [ { "role": "user", "content": "Write a one sentence product description for a cozy, stylish sweater suitable for both casual and formal occasions" } ] }' ``` The response is a JSON object with a `choices` array. The `message.content` field of the first choice contains the generated text. The `message.role` field indicates that the message is an AI assistant message. ```json theme={null} { "id": "78766762-bd30-4a42-bb2b-e0b35c608217", "object": "chat.completion", "choices": [ { "index": 0, "finish_reason": "stop", "message": { "content": "This versatile, cozy sweater blends warmth and elegance with its soft knit and refined design, making it perfect for both casual days and formal evenings.", "role": "assistant", "tool_calls": null, "graph_data": { "sources": null, "status": null, "subqueries": null }, "llm_data": null, "image_data": null, "refusal": null }, "logprobs": null } ], "created": 1740711212, "model": "palmyra-x5", "usage": { "prompt_tokens": 50, "total_tokens": 79, "completion_tokens": 29, "prompt_token_details": null, "completion_tokens_details": null }, "system_fingerprint": "v1", "service_tier": null } ``` > [!NOTE] > > In a streaming response, the structure of the response is similar. However, the content of the streamed response is returned in a `choices[0].delta.content` field, rather than the `choices[0].message.content` field. Learn more about streaming responses in the [chat completion guide](/home/chat-completion). You can customize your request to the chat completion endpoint by adding or updating parameters to the request body. Learn more about the different parameters in the [chat completion endpoint API reference](/api-reference/completion-api/chat-completion). ## Next steps Now that you've made your first API call, learn how to use [the Writer SDKs](/home/sdks) to make calls to the Writer API in your applications. Or, learn more about building with the chat completion endpoint: * Learn how to build a multi-turn, conversational AI app using the [chat completion guide](/home/chat-completion) * See the full [chat completion endpoint API reference](/api-reference/completion-api/chat-completion) # Research Source: https://dev.writer.com/home/research # SDKs Source: https://dev.writer.com/home/sdks Install and use Writer SDKs for Python and Node.js. Get started with code examples and learn how to integrate Writer AI into your applications. This guide helps you get started with the Writer SDKs. Follow these steps to install the SDKs and perform basic operations. ### Prerequisites > [tab] Python SDK > > * Python 3.7+ > * [pip](https://pypi.org/project/pip/) > * A Writer API key > [tab] Node SDK > > * Node.js > * [`npm`](https://www.npmjs.com/get-npm) > * A Writer API key > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ### Install the SDK Open your terminal or command prompt and install the Writer SDK: ```sh Python theme={null} pip install writer-sdk ``` ```sh Node theme={null} npm install writer-sdk ``` ## Initialize the client To initialize the client, import the Writer SDK and create an instance of the `Writer` class. We recommend setting your API key in an environment variable called `WRITER_API_KEY`. When you initialize the Writer client, the client looks for the `WRITER_API_KEY` environment variable automatically. You can also pass your API key directly to the client. ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() ``` ```js JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); ``` ## Make a chat completion request Once you've initialized the client, you can make a request to the Writer API. The following example shows how to make a [chat completion request](/home/chat-completion) to generate a poem: ```python Python theme={null} from writerai import Writer client = Writer() response = client.chat.chat( messages=[{ "content": "Write a short poem about Python", "role": 'user' }], model="palmyra-x5" ) print(response.choices[0].message.content) ``` ```js JavaScript theme={null} import { Writer } from 'writer-sdk'; const client = new Writer(); const response = await client.chat.chat({ messages: [{ content: "Write a short poem about JavaScript", role: 'user' }], model: "palmyra-x5" }); console.log(response.choices[0].message.content); ``` ## Next steps Now that you're set up with the SDKs, start building with [chat completions](/home/chat-completion) or [text generation](/home/text-generation). You can also use the [API reference](/api-reference) to learn more detailed information about available endpoints. # Set up BYOK encryption Source: https://dev.writer.com/home/setup-byok Connect your own KMS from AWS, Azure, or GCP to control encryption keys for your Writer organization. This guide walks you through enrolling your Writer organization in bring-your-own-key (BYOK) encryption. After completing these steps, your data is encrypted with a master key that you control in your own cloud KMS. Writer never sees or stores the key. For an overview of encryption architecture, scopes, and key actions, see [Encryption Key Management](/home/encryption-key-management). > [!NOTE] > > BYOK encryption is available on Enterprise plans. You must be an organization > admin to configure encryption settings. ![Encryption page in Control Center showing Writer-managed encryption connected and BYOK configuration options for Azure Key Vault, AWS KMS, and GCP Cloud KMS.](https://mintcdn.com/writer/3p8cus-VbaNQmm3T/images/home/encryption-byok-setup.png?fit=max\&auto=format\&n=3p8cus-VbaNQmm3T\&q=85\&s=289e1c042ab8177144d6db6fe46e6a71) ## Prerequisites Before you begin, make sure you have: * A Writer Enterprise plan with organization admin access * An active KMS account with one of the supported providers: * [AWS KMS](https://aws.amazon.com/kms/) * [Azure Key Vault](https://azure.microsoft.com/en-us/products/key-vault) * [GCP Cloud KMS](https://cloud.google.com/kms/docs) * Permissions to create keys and manage access policies in your KMS ## Enroll in encryption To enable encryption, navigate to the **Encryption** page under **Security & compliance** in Control Center. You can choose one of two options: * **Enable Writer-managed encryption**: Writer manages the master key. Select this for zero-maintenance encryption. * **Bring your own encryption keys**: Connect your own KMS from AWS, Azure, or GCP for direct control over the master key. You can start with Writer-managed encryption and switch to BYOK at any time. > [!NOTE] > > Enabling encryption applies only to new data created after enrollment. > Pre-existing data is not retroactively encrypted. ## Connect your KMS for BYOK To set up BYOK, either during initial enrollment or switching from Writer-managed encryption: 1. In Control Center, navigate to the **Encryption** page under **Security & compliance**. 2. On the enrollment screen, select **Bring your own encryption keys**. * If encryption is already enabled, select the **Master key** tab and then select **Configure** under **Bring your own keys**. 3. Choose your cloud provider: **AWS KMS**, **Azure Key Vault**, or **GCP Cloud KMS**. 4. Follow the provider-specific instructions in the setup modal to create or select a key in your KMS and grant Writer access. 5. Paste your key identifier (ARN, key URL, or resource name) into the form. Writer validates the connection to your key. 6. After validation succeeds, the setup confirms that your BYOK configuration is complete. ## Control access from your KMS With BYOK, you can control Writer's access to all encrypted data directly from your cloud provider's KMS console. ### Disable your CMK Disabling your CMK immediately prevents Writer from unwrapping any DEKs across your entire organization. Use this during an active incident investigation when you need to cut off all access at once. * In **AWS KMS**: Select the key and choose **Disable key**. * In **Azure Key Vault**: Set the key's **Enabled** attribute to **false**. * In **GCP Cloud KMS**: Select the key version and choose **Disable**. Re-enabling the key restores Writer's ability to decrypt data. ### Delete your CMK Deleting your CMK permanently prevents Writer from unwrapping any DEKs. All encrypted data across your organization becomes permanently inaccessible. > [!WARNING] > > Deleting your CMK is irreversible. There is no way for Writer or your cloud > provider to restore access to your data after the key is deleted. Most cloud providers enforce a waiting period before permanent deletion (for example, AWS KMS requires a 7-30 day waiting period). Use this window to verify that you intend to destroy access permanently. ## Next steps * Review [Encryption Key Management](/home/encryption-key-management) for encryption architecture, scopes, and key actions * [Event logs](/home/event-logs) to monitor request-level activity across your organization # Stream responses from the API Source: https://dev.writer.com/home/streaming Stream API responses in real-time with Server-Sent Events. Reduce latency and display generated content as it's created for better user experience. The Writer API supports streaming responses from the API. Streams use [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent%5Fevents/Using%5Fserver-sent%5Fevents) so that you can display content as the API generates it in real time. Streaming improves user experience by reducing latency from the time the user submits a request to the time the response is available. ## Overview To stream a response from the API, set the `stream` parameter to `true` in the request body. The following endpoints support streaming: * [Text generation](/api-reference/completion-api/text-generation#body-stream) * [Chat completions](/api-reference/completion-api/chat-completion#body-stream) * [Generate from no-code agent](/api-reference/application-api/applications#body-stream): Currently, only no-code research agents support streaming. * [Knowledge Graph question](/api-reference/kg-api/question#body-stream) ## Sample request and response The code below shows a streaming request and response from a text generation request using `curl`. The response is a stream of [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent%5Fevents/Using%5Fserver-sent%5Fevents). ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/completions' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "prompt": "Respond to a customer chat request about a delayed shipment with a message that apologizes for the delay, offers a tracking number, and provides a new estimated delivery date.", "stream": true }' ``` ```json response theme={null} data: {"value":""} data: {"value":"Hello"} data: {"value":" ["} data: {"value":"Customer"} data: {"value":"'s"} data: {"value":" Name"} ... ``` > [!NOTE] > > If you're using the chat completions endpoint instead of text generation, the streamed response format is slightly different. The content for each chunk appears in `choices[0].delta.content`. See the [Generate chat completions](/home/chat-completion#streaming-response) guide for the full streaming response object. ## Streaming with SDKs When you stream a response using a Writer SDK, the SDK creates an iterator that yields chunks of the response. You can iterate over the stream to receive the response. See below for examples of streaming with the Python and JavaScript SDKs for each endpoint that supports streaming. > [tab] Text Generation > > ```python Python theme={null} > from writerai import Writer > > # Initialize the client. If you don't pass the `api_key` parameter, > # the client looks for the `WRITER_API_KEY` environment variable. > client = Writer() > > text_generation = client.completions.create( > model="palmyra-x5", > prompt="Respond to a customer chat request about a delayed shipment with a message that apologizes for the delay, offers a tracking number, and provides a new estimated delivery date.", > stream=True > ) > > for chunk in text_generation: > if chunk.value: # Only print non-empty chunks > print(chunk.value, end="", flush=True) > ``` > > ```javascript JavaScript theme={null} > import { Writer } from 'writer-sdk'; > > // Initialize the client. If you don't pass the `apiKey` parameter, > // the client looks for the `WRITER_API_KEY` environment variable. > const client = new Writer(); > > const stream = await client.completions.create({ > model: 'palmyra-x5', > prompt: 'Respond to a customer chat request about a delayed shipment with a message that apologizes for the delay, offers a tracking number, and provides a new estimated delivery date.', > stream: true > }); > > for await (const chunk of stream) { > process.stdout.write(chunk.value); > } > ``` > [tab] Chat Completions > > ```python Python theme={null} > from writerai import Writer > > # Initialize the client. If you don't pass the `api_key` parameter, > # the client looks for the `WRITER_API_KEY` environment variable. > client = Writer() > > stream = client.chat.chat( > model="palmyra-x5", > messages=[{"role": "user", "content": "Respond to a customer chat request about a delayed shipment with a message that apologizes for the delay, offers a tracking number, and provides a new estimated delivery date."}], > stream=True > ) > > for chunk in stream: > if chunk.choices[0].delta.content: > print(chunk.choices[0].delta.content, end="", flush=True) > ``` > > ```javascript JavaScript theme={null} > import { Writer } from 'writer-sdk'; > > // Initialize the client. If you don't pass the `apiKey` parameter, > // the client looks for the `WRITER_API_KEY` environment variable. > const client = new Writer(); > > const stream = await client.chat.chat({ > model: 'palmyra-x5', > messages: [{ role: 'user', content: 'Respond to a customer chat request about a delayed shipment with a message that apologizes for the delay, offers a tracking number, and provides a new estimated delivery date.' }], > stream: true > }); > > for await (const chunk of stream) { > if (chunk.choices[0]?.delta?.content) { > process.stdout.write(chunk.choices[0].delta.content); > } > } > ``` > [tab] Generate from no-code agent > > ```python Python theme={null} > from writerai import Writer > > # Initialize the client. If you don't pass the `api_key` parameter, > # the client looks for the `WRITER_API_KEY` environment variable. > client = Writer() > > stream = client.applications.generate_content( > application_id="", > inputs=[ > { > "id": "query", > "value": ["Provide a list of three hotels in San Francisco near Union Square within the price range of $100 to $200 per night"] > } > ], > stream=True > ) > > for chunk in stream: > if chunk.delta.content: > print(chunk.delta.content, end="", flush=True) > elif chunk.delta.stages: > print(chunk.delta.stages[0].content) > ``` > > ```javascript JavaScript theme={null} > import { Writer } from 'writer-sdk'; > > // Initialize the client. If you don't pass the `apiKey` parameter, > // the client looks for the `WRITER_API_KEY` environment variable. > const client = new Writer(); > > const stream = await client.applications.generateContent( > "", > { > inputs: [ > { > id: "query", > value: ["Provide a list of three hotels in San Francisco near Union Square within the price range of $100 to $200 per night"] > } > ], > stream: true > } > ); > > for await (const chunk of stream) { > if (chunk.delta.content) { > process.stdout.write(chunk.delta.content); > } else if (chunk.delta.stages) { > process.stdout.write(chunk.delta.stages[0].content); > } > } > ``` > [tab] Knowledge Graph question > > ```python Python theme={null} > from writerai import Writer > > # Initialize the client. If you don't pass the `api_key` parameter, > # the client looks for the `WRITER_API_KEY` environment variable. > client = Writer() > > stream = client.graphs.question( > graph_ids=[""], > question="What is the generic name for the drug Bavencio?", > stream=True > ) > > for chunk in stream: > if chunk.answer: # Only print non-empty answers > print(chunk.answer, end="", flush=True) > ``` > > ```javascript JavaScript theme={null} > import { Writer } from 'writer-sdk'; > > // Initialize the client. If you don't pass the `apiKey` parameter, > // the client looks for the `WRITER_API_KEY` environment variable. > const client = new Writer(); > > const stream = await client.graphs.question({ > graph_ids: [""], > question: "What is the generic name for the drug Bavencio?", > stream: true > }); > > for await (const chunk of stream) { > process.stdout.write(chunk.answer); > } > ``` ### Streaming helpers for chat completions The Python and Node SDKs include streaming helpers for chat completions. These helpers provide more granular details about the streaming events and accumulate the response. To use the streaming helpers, call `client.chat.stream`. Then, include all the same parameters as you would for a non-streaming chat completion request, except omit the `stream` parameter. ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() with client.chat.stream( model="palmyra-x5", messages=[{"role": "user", "content": "Respond to a customer chat request about a delayed shipment with a message that apologizes for the delay, offers a tracking number, and provides a new estimated delivery date."}] ) as stream: for event in stream: if event.type == "content.delta": print(event.delta, end="", flush=True) # print the final response completion = stream.get_final_completion() print(completion.choices[0].message.content) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const stream = client.chat.stream({ model: 'palmyra-x5', messages: [{ role: 'user', content: 'Respond to a customer chat request about a delayed shipment with a message that apologizes for the delay, offers a tracking number, and provides a new estimated delivery date.' }], }) .on('content', (diff) => process.stdout.write(diff)); // print the final response const completion = await stream.finalChatCompletion(); console.log(completion.choices[0].message.content); ``` For more information about the streaming helpers for chat completions, see the [Python](https://github.com/writer/writer-python/blob/main/helpers.md) and [Node](https://github.com/writer/writer-node/blob/main/helpers.md) SDKs. # Receive structured outputs Source: https://dev.writer.com/home/structured-output > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. ## Overview The [`chat` endpoint](/api-reference/completion-api/chat-completion) supports structured outputs for chat completions with `palmyra-x5` and `palmyra-x4` models. Structured outputs allow you to specify the response schema that the model should follow. You can use structured outputs in one of two ways: 1. [Pass in a `json_schema` object](/home/structured-output#sample-request-and-response) in the `response_format` parameter when making a request to the `chat` endpoint. 2. [Use the `parse` method](/home/structured-output#sdk-parse-methods) in the Python and JavaScript SDKs and pass in a [`Pydantic`](https://docs.pydantic.dev/) or [`Zod`](https://zod.dev/) object. ## Sample request and response The sample request and response below shows how to use structured outputs with the `chat` endpoint and the `response_format` parameter. The `json_schema` object must be in [JSON Schema format](https://json-schema.org/understanding-json-schema/). To guarantee that the model includes all the fields in the response, include the [`required` field](https://json-schema.org/understanding-json-schema/reference/object.html#required) in the `json_schema` object. ```bash cURL theme={null} curl -X POST https://api.writer.com/v1/chat \ --header "Content-Type: application/json" \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "messages": [ { "role": "system", "content": "You are a helpful cooking assistant." }, { "role": "user", "content": "Give me a recipe for a simple pasta dish." } ], "response_format": { "type": "json_schema", "json_schema": { "schema": { "type": "object", "properties": { "recipe_name": {"type": "string"}, "ingredients": {"type": "array", "items": {"type": "string"}}, "steps": {"type": "array", "items": {"type": "string"}}, "preparation_time": {"type": "string"}, "servings": {"type": "number"} }, "required": ["recipe_name", "ingredients", "steps", "preparation_time", "servings"] } } } }' ``` ```python Python theme={null} import json from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.chat.chat( model="palmyra-x5", messages=[ {"role": "system", "content": "You are a helpful cooking assistant."}, {"role": "user", "content": "Give me a recipe for a simple pasta dish."} ], response_format={ "type": "json_schema", "json_schema": { "schema": { "type": "object", "properties": {"recipe_name": {"type": "string"}, "ingredients": {"type": "array", "items": {"type": "string"}}, "steps": {"type": "array", "items": {"type": "string"}}, "preparation_time": {"type": "string"}, "servings": {"type": "number"}}, "required": ["recipe_name", "ingredients", "steps", "preparation_time", "servings"] } } } ) print(json.loads(response.choices[0].message.content)) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.chat.chat({ model: 'palmyra-x5', messages: [ { role: 'system', content: 'You are a helpful cooking assistant.' }, { role: 'user', content: 'Give me a recipe for a simple pasta dish.' } ], response_format: { type: 'json_schema', json_schema: { schema: { type: 'object', properties: { recipe_name: { type: 'string' }, ingredients: { type: 'array', items: { type: 'string' } }, steps: { type: 'array', items: { type: 'string' } }, preparation_time: { type: 'string' }, servings: { type: 'number' } }, required: ['recipe_name', 'ingredients', 'steps', 'preparation_time', 'servings'] } } }, }); console.log(JSON.parse(response.choices[0].message.content)); ``` The response from the `chat` endpoint includes a `message` object with the `content` field set to the raw response from the model. ```json response theme={null} { "id": "1234", "object": "chat.completion", "choices": [ { "index": 0, "finish_reason": "stop", "message": { "content": "{ \"recipe_name\": \"Spaghetti Aglio e Olio\", \"ingredients\": [\"12 oz spaghetti\", \"3-4 garlic cloves\", \"1/3 cup extra virgin olive oil\", \"4-6 dried red chili flakes (optional)\", \"Salt\", \"Freshly ground black pepper\", \"Grated Parmesan cheese (optional)\", \"Fresh parsley, chopped (optional)\"], \"steps\": [\"Bring a large pot of salted water to a boil. Cook the spaghetti according to the package instructions until al dente. Reserve 1 cup of pasta water before draining.\", \"In a large skillet, heat the olive oil over medium-low heat. Add the thinly sliced garlic and cook, stirring occasionally, until golden brown (about 4-5 minutes). Be careful not to burn the garlic.\", \"If using red chili flakes, add them to the skillet and cook for another minute.\", \"Add the reserved pasta water to the skillet and stir to combine.\", \"Add the cooked spaghetti to the skillet, tossing to coat the pasta in the garlic and oil mixture. Season with salt and black pepper to taste.\", \"Serve hot, topped with grated Parmesan cheese and chopped fresh parsley if desired.\"] }", "role": "assistant", "tool_calls": null, "graph_data": { "sources": null, "status": null, "subqueries": null }, "llm_data": null, "image_data": null, "refusal": null }, "logprobs": null } ], "created": 1745948916, "model": "palmyra-x5", "usage": { "prompt_tokens": 2550, "total_tokens": 2797, "completion_tokens": 247, "prompt_token_details": null, "completion_tokens_details": null }, "system_fingerprint": "v1", "service_tier": null } ``` ## SDK parse methods The Python and JavaScript SDKs provide helper `parse` methods for working with structured outputs. You can define a `Pydantic` or `Zod` model for the response schema, and pass it as the `response_format` parameter to the `parse` method. The result from the `parse` method includes a `message` object with the `parsed` field. This field's value is an instance of the `Pydantic` or `Zod` model you passed for the `response_format` parameter. > [!WARNING] > > If you include tool calls in your request, the `parse` method only works with [custom functions](/home/tool-calling) where the tool calls are of type `function`. It does not work with built-in tools with other types such as `graph` or `llm`. For those cases, you can pass a `json_schema` object in the `response_format` parameter for the `chat` endpoint. ```python Python theme={null} from typing import List from pydantic import Field, BaseModel from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() # Define a Pydantic model for structured output class Recipe(BaseModel): recipe_name: str = Field(description="The name of the recipe") ingredients: List[str] = Field(description="A list of ingredients for the recipe") steps: List[str] = Field(description="A list of steps for the recipe") preparation_time: str = Field(description="The preparation time for the recipe") servings: int = Field(description="The number of servings for the recipe") parsed_response = client.chat.parse( model="palmyra-x5", messages=[ {"role": "system", "content": "You are a helpful cooking assistant."}, { "role": "user", "content": "Give me a recipe for a simple pasta dish.", }, ], response_format=Recipe, ) parsed = parsed_response.choices[0].message.parsed # Print the parsed response print(f"Recipe name: {parsed.recipe_name}") print(f"Ingredients:") for item in parsed.ingredients: print(f"- {item}") print(f"Steps:") for item in parsed.steps: print(f"- {item}") print(f"Preparation time: {parsed.preparation_time}") print(f"Servings: {parsed.servings}") ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; import { z } from 'zod'; import { zodResponseFormat } from 'writer-sdk/helpers/zod'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); async function main() { // Define a schema for structured output const recipeSchema = z.object({ recipeName: z.string(), ingredients: z.array( z.object({ name: z.string(), amount: z.string(), }), ), steps: z.array(z.string()), preparationTime: z.string(), servings: z.number(), }); const completion = await client.chat.parse({ model: 'palmyra-x5', messages: [ { role: 'system', content: 'You are a helpful cooking assistant.' }, { role: 'user', content: 'Give me a recipe for a simple pasta dish.' }, ], response_format: zodResponseFormat(recipeSchema, 'recipe'), temperature: 0.7, }); // Access the parsed structured data const message = completion.choices[0]?.message; if (message?.parsed) { console.log('Recipe name:', message.parsed.recipeName); console.log('Ingredients:'); message.parsed.ingredients.forEach((ing) => { console.log(`- ${ing.amount} ${ing.name}`); }); console.log('\nSteps:'); message.parsed.steps.forEach((step, index) => { console.log(`${index + 1}. ${step}`); }); console.log(`\nPreparation time: ${message.parsed.preparationTime}`); console.log(`Servings: ${message.parsed.servings}`); } else { console.log('Raw content:', message?.content); } } main() ``` # Column test Source: https://dev.writer.com/home/temp_component ## Fields A layout component that organises its child components in columns. Must be inside a Column Container component. ![](/framework/public/components/column.png)
Name Type Description Options
## Low code usage This component can be declared directly in Python, using [backend-driven UI](/framework/backend-driven-ui). ```python theme={null} ui.Column(content={ "title": "", # str "width": "1", # Union[float, str] "isSticky": "no", # str [yes, no] "isCollapsible": "no", # str [yes, no] "startCollapsed": "no", # str [yes, no] "separatorColor": "", # str "contentPadding": "", # str "contentHAlign": "", # str "contentVAlign": "", # str "cssClasses": "", # str } ) ``` # Generate text from a prompt Source: https://dev.writer.com/home/text-generation Generate text using the text generation endpoint. Compare text generation vs chat completion and see API examples. You can use the [text generation endpoint](/api-reference/completion-api/text-generation) to generate text with an LLM. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Text generation vs. chat completion The text generation endpoint is appropriate when you need to generate a single text response based on a given prompt, or when you want to ask a specific LLM a question. The [chat completion endpoint](/home/chat-completion) can generate single messages, or create more complex conversations between a user and a general-purpose LLM. Additionally, the chat completion endpoint offers [tool calling](/home/chat-completion), which you can use to access other LLMs, Knowledge Graphs, and custom functions. ## Endpoint overview **URL:** `POST https://api.writer.com/v1/completions` > [!WARNING] > > Using the `/completions` endpoint results in charges for **model usage**. See the [pricing page](/home/pricing) for more information. ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/completions' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "prompt": "Tell me a story", "max_tokens": 1000, "temperature": 0.7, "stream": true }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() text_generation = client.completions.create( model="palmyra-x5", prompt="Tell me a story", max_tokens=1000, temperature=0.7, stream=True ) for chunk in text_generation: print(chunk.value, end="", flush=True) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const text_generation = await client.completions.create({ model: 'palmyra-x5', prompt: 'Tell me a story', max_tokens: 1000, temperature: 0.7, stream: true }); for await (const chunk of text_generation) { process.stdout.write(chunk.value); } ``` ### Request body Below are the required and commonly used optional parameters for the text generation endpoint. | Parameter | Type | Description | | - | - | - | | `model` | string | **Required**. The [ID of the model](/home/models) to use for text generation. | | `prompt` | string | **Required**. The prompt to generate text from. | | `max_tokens` | int | The maximum number of tokens to generate for the response. Defaults to `100`. | | `temperature` | float | Temperature influences the randomness in generated text. Defaults to `1`. Increase the value for more creative responses, and decrease the value for more predictable responses. | | `stream` | Boolean | A Boolean value that indicates whether to stream the response. Defaults to `false`. | See the full list of available parameters in the [text generation endpoint reference](/api-reference/completion-api/text-generation). ### Response parameters #### Non-streaming response If you set the `stream` parameter to `false`, the response is a single JSON object with the following parameters: | Parameter | Type | Description | | - | - | - | | `model` | string | The ID of the model used to generate the response. | | `choices` | array | An array of choices objects. | | `choices[0].text` | string | The generated text. | | `choices[0].log_probs` | object | The [log probabilities](/api-reference/completion-api/text-generation#response-choices-log-probs) of the tokens in the generated text. | ```json theme={null} { "choices": [ { "text": "Camping Gear: The Ultimate Guide\n\nCamping is a great way to get outdoors and enjoy nature", "log_probs": null } ], "model": "palmyra-x5" } ``` #### Streaming response If you set the `stream` parameter to `true`, the response is delivered as [server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) with the following parameters: | Parameter | Description | | - | - | | `value` | The content of the chunk. | ```json theme={null} data: {"value":"Camping Gear: The Ultimate Guide\n\nCamping is a great way to get outdoors and enjoy nature"} ``` ## Generate streaming and non-streaming responses The examples below generate a single message from the `palmyra-x5` model, using the prompt "How can I treat a cold?" ### Streaming response The text generation endpoint supports streaming responses. The response comes in chunks until the entire response finishes. Streaming responses are useful when you want to display the generated text in real-time, or when you want to stream the response to a client, rather than waiting for the entire response to finish. ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/completions' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "prompt": "How can I treat a cold?", "stream": true }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() text_generation = client.completions.create( model="palmyra-x5", prompt="How can I treat a cold?", stream=True ) for chunk in text_generation: print(chunk.value, end="", flush=True) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const text_generation = await client.completions.create({ model: 'palmyra-x5', prompt: 'How can I treat a cold?', stream: true }); for await (const chunk of text_generation) { process.stdout.write(chunk.value); } ``` ### Non-streaming response For non-streaming responses, the response returns as a single JSON object after the entire response is complete. The text is in the `choices[0].text` field. ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/completions' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "model": "palmyra-x5", "prompt": "How can I treat a cold?", "stream": false }' ``` ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() text_generation = client.completions.create( model="palmyra-x5", prompt="How can I treat a cold?", stream=False ) print(text_generation.choices[0].text) ``` ```javascript JavaScript theme={null} import { Writer } from 'writer-sdk'; // Initialize the client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const text_generation = await client.completions.create({ model: 'palmyra-x5', prompt: 'How can I treat a cold?', stream: false }); console.log(text_generation.choices[0].text); ``` ## Next steps Now that you've generated text, try out the following: * Create a chat with an AI assistant using the [chat completion endpoint](/home/chat-completion) * Learn more about the [tool calling](/home/chat-completion#tool-calling) feature of the chat completion endpoint # Understand tokens Source: https://dev.writer.com/home/tokens Tokens are the atomic units that language models use to process text. Language models understand tokens rather than characters or bytes. Each token represents a single unit of meaning, like a word or a group of words. The Writer API processes all text input and output in terms of tokens. See the maximum number of tokens for each model in the [models overview](/home/models) page. ## Tokenization Tokenization is the process of breaking input text down into smaller units. Depending on the tokenization method the model uses, a single word can be represented by one token or may be broken down into multiple sub-word tokens. Here's how different text types typically tokenize: ```python theme={null} "hello world" → ["hello", " world"] # 2 tokens "API" → ["API"] # 1 token "tokenization" → ["token", "ization"] # 2 tokens "www.writer.com" → ["www", "writer", "com"] # 3 tokens ``` ## Input and output token usage Every API call consumes tokens for both the prompt you send and the response generated: ```python theme={null} # Example API call response = client.chat.completions.create( model="palmyra-x5", messages=[ {"role": "user", "content": "Write a product description for a cozy sweater"}, # ~8 tokens ], max_tokens=150, # Maximum tokens to include in the response ) # Total token usage = prompt tokens + response tokens ``` ## Inspect token usage You can inspect the [`usage`](/api-reference/completion-api/chat-completion#response-usage) information from the API response to see the token usage for each response. > [!NOTE] > > The prompt tokens reported in the response include the tokens used for the > model's system prompt. ```python Python theme={null} from writerai import Writer # Initialize the client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.chat.chat( model="palmyra-x5", messages=[{"role": "user", "content": "Write a product description for a cozy sweater"}], max_tokens=150, ) # Log token usage to understand patterns print(f"Prompt tokens: {response.usage.prompt_tokens}") print(f"Response tokens: {response.usage.completion_tokens}") print(f"Total tokens: {response.usage.total_tokens}") ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.chat.chat({ model: "palmyra-x5", messages: [ { role: "user", content: "Write a product description for a cozy sweater" }, ], maxTokens: 150, }); // Log token usage to understand patterns console.log(`Prompt tokens: ${response.usage.prompt_tokens}`); console.log(`Response tokens: ${response.usage.completion_tokens}`); console.log(`Total tokens: ${response.usage.total_tokens}`); ``` You can view your organization's overall token usage and spend in the [Consumption dashboard](/home/usage-and-spend). # Call a custom function in a chat Source: https://dev.writer.com/home/tool-calling Extend LLM capabilities with tool calling. Execute custom functions, query databases, fetch real-time data, and integrate results into chat responses. > [!WARNING] > > **Deprecation notice**: Palmyra X4 (`palmyra-x4`) and Palmyra X5 (`palmyra-x5`) will be deprecated on **December 14, 2026**. > > **Migration path**: Use [Palmyra X6](/home/models#palmyra-x6) (`palmyra-x6`) instead. Palmyra X6 has a 1M token context window (Palmyra X4 is 128k). See [pricing](/home/pricing) for cost details and the [deprecation policy](/home/models#deprecation-policy) for more information. This guide helps you understand how to use tool calling, sometimes known as function calling, with chat completions. Tool calling allows you to extend the capabilities of [chats with LLMs](/home/chat-completion) by enabling the LLM to call custom functions, or tools. Your custom tools can perform a wide range of tasks, such as querying databases, fetching real-time data from APIs, processing data, or executing business logic. You can then integrate the result of these tool calls back into the model's output. Tool calling is available for Palmyra X4 and later models, as well as supported external models. > [!TIP] > > This guide discusses calling custom functions as tools. Writer also offers prebuilt tools that models can execute remotely: > > * [Ask questions to a Knowledge Graph in a chat](/home/kg-chat) > * [Delegate questions to another model](/home/model-delegation) > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. ## Overview To use tool calling, follow these steps: 1. Define your functions in code 2. Pass the functions to the model in a chat completion request 3. Append the assistant's response (containing tool calls) to the message history 4. Check to see which functions the model wants to invoke and run the corresponding functions 5. Append the tool results to the message history 6. Pass the updated messages back to the model to get the final response 7. Append the final response to maintain complete conversation history > [card] Tool calling overview > > ![A flowchart showing how tool calling works: The model receives a prompt, decides to call a tool, executes the tool, and incorporates the result into its response](https://mintcdn.com/writer/EtzIGhya5-RmdX2Q/images/home/tool-calling-diagram.png?fit=max\&auto=format\&n=EtzIGhya5-RmdX2Q\&q=85\&s=1f11e881c1b513db9e5e58343573f990) > [card] Example: Calculate the mean of a list of numbers > > ![A flowchart demonstrating tool calling with a specific example: The model receives numbers, calls a calculate_mean function, gets the result, and provides the final answer](https://mintcdn.com/writer/EtzIGhya5-RmdX2Q/images/home/tool-calling-example.png?fit=max\&auto=format\&n=EtzIGhya5-RmdX2Q\&q=85\&s=1e039770eed85fb224e03803d680d62f) > [card] Example: Calculate the mean and standard deviation of a list of numbers > > ![Diagram of multi-tool calling to calculate the mean and standard deviation of a list of numbers](https://mintcdn.com/writer/UVGROL4WBnovp2ZQ/images/home/multi-tool-calling-diagram.png?fit=max\&auto=format\&n=UVGROL4WBnovp2ZQ\&q=85\&s=0e0edb6f0bf195590a7343655f41a5f7) Continue reading to learn more about each step. ## Define your custom functions First, define the custom functions in your code. Typical use cases for tool calling include calling an API, performing mathematical calculations, or running complex business logic. You can define these functions in your code as you would any other function. Here's an example of a function to calculate the mean of a list of numbers. ```python Python theme={null} def calculate_mean(numbers: list) -> float: return sum(numbers) / len(numbers) ``` ```js JavaScript theme={null} function calculateMean(numbers) { if (numbers.length === 0) { throw new Error("Cannot calculate mean of an empty array"); } return numbers.reduce((sum, num) => sum + num, 0) / numbers.length; } ``` ## Describe functions as tools After you've defined your functions, create a `tools` array to pass to the model. The `tools` array describes your functions as tools available to the model. You describe tools in the form of a [JSON schema](https://json-schema.org/). Each tool should include a `type` of `function` and a `function` object that includes a `name`, `description`, and a dictionary of `parameters`. ### Tool structure The `tools` array contains an object with the following parameters: | Parameter | Type | Description | | - | - | - | | `type` | string | The type of tool, which is `function` for a custom function | | `function` | object | An object containing the tool's description and parameter definitions | | `function.name` | string | The name of the tool | | `function.description` | string | A description of what the tool does and when the model should use it | | `function.parameters` | object | An object containing the tool's input parameters | | `function.parameters.type` | string | The type of the parameter, which is `object` for a JSON schema | | `function.parameters.properties` | object | An object containing the tool's parameters in the form of a [JSON schema](https://json-schema.org/). See below for more details. | | `function.parameters.required` | array | An array of the tool's required parameters | See the full [tools object schema](/api-reference/completion-api/chat-completion#body-tools) for more details. The `function.parameters.properties` object contains the tool's parameter definitions as a [JSON schema](https://json-schema.org/). The object's keys should be the names of the parameters, and the values should be objects containing the parameter's type and description. When the model decides you should use the tool to answer the user's question, it returns the parameters that you should use when calling the function you've defined. ### Example tool array Here's an example of a `tools` array for the `calculate_mean` function: ```python Python theme={null} tools = [ { "type": "function", "function": { "name": "calculate_mean", "description": "A function that calculates the mean (average) of a list of numbers. Any user request asking for the mean of a list of numbers should use this tool.", "parameters": { "type": "object", "properties": { "numbers": { "type": "array", "items": {"type": "number"}, "description": "List of numbers" } }, "required": ["numbers"] } } } ] ``` ```js JavaScript theme={null} const tools = [ { type: "function", function: { name: "calculate_mean", description: "A function that calculates the mean (average) of a list of numbers. Any user request asking for the mean of a list of numbers should use this tool.", parameters: { type: "object", properties: { numbers: { type: "array", items: { type: "number" }, description: "List of numbers", }, }, required: ["numbers"], }, }, }, ]; ``` > [!NOTE] > > To help the model understand when to use the tool, follow these best practices for the `function.description` parameter: > > * Indicate that the tool is a function that invokes a no-code agent > * Specify the function's purpose and capabilities > * Describe when the tool should be used > > An example description for a tool that invokes a function to calculate the mean of a list of numbers: > > > "A function that calculates the mean of a list of numbers. Any user request asking for the mean of a list of numbers should use this tool." ## Pass tools to the model Once the tools array is complete, pass it to the [chat completions endpoint](/home/chat-completion) along with the chat messages. ### Tool choice control The chat completion endpoint has a [`tool_choice parameter`](/api-reference/completion-api/chat-completion#body-tool-choice) that controls how the model decides when to use the tools you've defined. | Value | Description | | - | - | | `auto` | The model decides which tools to use, if any. | | `none` | The model doesn't use tools and only returns a generated response. | | `required` | The model must use at least one of the tools you've defined. | You can also use a JSON object to force the model to use a specific tool. For example, if you want the model to use the `calculate_mean` tool, you can set `tool_choice` to `{"type": "function", "function": {"name": "calculate_mean"}}`. In this example, `tool_choice` is `auto`, which means the model decides which tools to use, if any, based on the message and tool descriptions. ```python Python theme={null} import json from writerai import Writer # Initialize the Writer client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() messages = [{"role": "user", "content": "what is the mean of [1,3,5,7,9]?"}] response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto" ) ``` ```js JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); let messages = [{"role": "user", "content": "what is the mean of [1,3,5,7,9]?"}]; const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, tool_choice: "auto" }); ``` ## Process tool calls When the model identifies a need to call a tool based on the user's input, it indicates it in the response and includes the necessary parameters to pass when calling the tool. You then execute the tool's function and return the result to the model. > [!TIP] > > Proper conversation history management requires appending the assistant's response, tool results, and final response to the message history. The method for checking for tool calls and executing the tool's function differs depending on whether you're streaming the response or not. Each method is described below. > [!NOTE] > > The examples below demonstrate processing a single tool call. For handling multiple tool calls in one request, see the [multiple tool calls](#multiple-tool-calls) section. > [tab] Streaming > > ### Streaming > > When using streaming, the tool calls come back in chunks inside of the delta object of the choices array. To process the tool calls: > > 1. Stream and collect tool calls from the response chunks > 2. Reconstruct the assistant's response and append it to the message history > 3. Execute functions and append tool results to the message history > 4. Get the final response from the model and append it to the message history > > #### Step 1: Stream and collect tool calls from the response chunks > > First, stream and collect tool calls from the response chunks. > > ```python Python theme={null} > streaming_content = "" > function_calls = [] > > for chunk in response: > choice = chunk.choices[0] > > if choice.delta: > # Collect tool calls as they stream in > if choice.delta.tool_calls: > for tool_call in choice.delta.tool_calls: > if tool_call.id: > # Start a new function call > function_calls.append({ > "name": "", > "arguments": "", > "call_id": tool_call.id > }) > if tool_call.function: > # Append to the most recent function call > if function_calls: > function_calls[-1]["name"] += tool_call.function.name or "" > function_calls[-1]["arguments"] += tool_call.function.arguments or "" > > # Collect regular content (for cases where no tools are called) > elif choice.delta.content: > streaming_content += choice.delta.content > ``` > > ```js JavaScript theme={null} > let streamingContent = ""; > const functionCalls = []; > > for await (const chunk of response) { > const choice = chunk.choices[0]; > > if (choice.delta) { > if (choice.delta.tool_calls) { > for (const toolCall of choice.delta.tool_calls) { > if (toolCall.id) { > functionCalls.push({ > name: "", > arguments: "", > call_id: toolCall.id > }); > } > if (toolCall.function) { > if (functionCalls.length > 0) { > functionCalls[functionCalls.length - 1].name += toolCall.function.name || ""; > functionCalls[functionCalls.length - 1].arguments += toolCall.function.arguments || ""; > } > } > } > } else if (choice.delta.content) { > streamingContent += choice.delta.content; > } > } > } > ``` > > #### Step 2: Check finish reason and reconstruct the assistant's response > > Check the `finish_reason` to determine if tools were called, then reconstruct and append the assistant's response to the conversation history. > > ```python Python theme={null} > # Inside the streaming loop, check for finish_reason > if choice.finish_reason: > if choice.finish_reason == "stop": > # No tools were called, just regular response > messages.append({"role": "assistant", "content": streaming_content}) > break > > elif choice.finish_reason == "tool_calls": > # Reconstruct and append assistant message with tool calls > tool_calls_for_message = [] > for func_call in function_calls: > tool_calls_for_message.append({ > "id": func_call["call_id"], > "type": "function", > "function": { > "name": func_call["name"], > "arguments": func_call["arguments"] > } > }) > > assistant_message = { > "role": "assistant", > "content": None, > "tool_calls": tool_calls_for_message > } > messages.append(assistant_message) > ``` > > ```js JavaScript theme={null} > // Inside the streaming loop, check for finish_reason > if (choice.finish_reason) { > if (choice.finish_reason === "stop") { > // No tools were called, just regular response > messages.push({ role: "assistant", content: streamingContent }); > break; > } else if (choice.finish_reason === "tool_calls") { > // Reconstruct and append assistant message with tool calls > const toolCallsForMessage = []; > for (const funcCall of functionCalls) { > toolCallsForMessage.push({ > id: funcCall.call_id, > type: "function", > function: { > name: funcCall.name, > arguments: funcCall.arguments > } > }); > } > > const assistantMessage = { > role: "assistant", > content: null, > tool_calls: toolCallsForMessage > }; > messages.push(assistantMessage); // Append assistant response > } > } > ``` > > #### Step 3: Execute functions and append tool results > > Execute each function in the `function_calls` list and append the results to the messages array. > > ```python Python theme={null} > # Inside the tool_calls finish_reason block > for function_call in function_calls: > function_name = function_call["name"] > > if function_name == "calculate_mean": > try: > arguments_dict = json.loads(function_call["arguments"]) > function_response = calculate_mean(arguments_dict["numbers"]) > > # Append tool result to conversation history > messages.append({ > "role": "tool", > "content": str(function_response), > "tool_call_id": function_call["call_id"], > "name": function_name, > }) > except Exception as e: > # Handle errors gracefully > messages.append({ > "role": "tool", > "content": f"Error: {str(e)}", > "tool_call_id": function_call["call_id"], > "name": function_name, > }) > ``` > > ```js JavaScript theme={null} > // Inside the tool_calls finish_reason block > for (const functionCall of functionCalls) { > const functionName = functionCall.name; > > if (functionName === "calculate_mean") { > try { > const argumentsDict = JSON.parse(functionCall.arguments); > const functionResponse = calculateMean(argumentsDict.numbers); > > // Append tool result to conversation history > messages.push({ > role: "tool", > content: functionResponse.toString(), > tool_call_id: functionCall.call_id, > name: functionName, > }); > } catch (error) { > // Handle errors gracefully > messages.push({ > role: "tool", > content: `Error: ${error.message}`, > tool_call_id: functionCall.call_id, > name: functionName, > }); > } > } > } > ``` > > #### Step 4: Get and append the final response > > After appending tool results, get the final response from the model and append it to maintain complete conversation history. > > ```python Python theme={null} > # Inside the tool_calls finish_reason block, after processing all functions > final_response = client.chat.chat( > model="palmyra-x5", > messages=messages, > stream=True > ) > > final_content = "" > for chunk in final_response: > choice = chunk.choices[0] > if choice.delta and choice.delta.content: > final_content += choice.delta.content > > # Append final response to conversation history > messages.append({ > "role": "assistant", > "content": final_content > }) > ``` > > ```js JavaScript theme={null} > // Inside the tool_calls finish_reason block, after processing all functions > const finalResponse = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > stream: true > }); > > let finalContent = ""; > for await (const chunk of finalResponse) { > const choice = chunk.choices[0]; > if (choice.delta && choice.delta.content) { > finalContent += choice.delta.content; > process.stdout.write(choice.delta.content); > } > } > > // Append final response to conversation history > messages.push({ > role: "assistant", > content: finalContent > }); > ``` > > #### Complete streaming code example > > ```python Python [expandable] theme={null} > import json > from writerai import Writer > > # Initialize the Writer client. If you don't pass the `apiKey` parameter, > # the client looks for the `WRITER_API_KEY` environment variable. > client = Writer() > > def calculate_mean(numbers: list) -> float: > return sum(numbers) / len(numbers) > > tools = [ > { > "type": "function", > "function": { > "name": "calculate_mean", > "description": "Calculate the mean (average) of a list of numbers.", > "parameters": { > "type": "object", > "properties": { > "numbers": { > "type": "array", > "items": {"type": "number"}, > "description": "List of numbers" > } > }, > "required": ["numbers"] > } > } > } > ] > > messages = [{"role": "user", "content": "what is the mean of [1,3,5,7,9]?"}] > > # Step 1: Initial request with tools > response = client.chat.chat( > model="palmyra-x5", > messages=messages, > tools=tools, > tool_choice="auto", > stream=True > ) > > # Step 2: Process streaming response to collect tool calls > streaming_content = "" > function_calls = [] > > for chunk in response: > choice = chunk.choices[0] > > if choice.delta: > # Collect tool calls as they stream in > if choice.delta.tool_calls: > for tool_call in choice.delta.tool_calls: > if tool_call.id: > # Start a new function call > function_calls.append({ > "name": "", > "arguments": "", > "call_id": tool_call.id > }) > if tool_call.function: > # Append to the most recent function call > if function_calls: > function_calls[-1]["name"] += tool_call.function.name or "" > function_calls[-1]["arguments"] += tool_call.function.arguments or "" > > # Collect regular content (for cases where no tools are called) > elif choice.delta.content: > streaming_content += choice.delta.content > > # Check if streaming is complete > if choice.finish_reason: > if choice.finish_reason == "stop": > # No tools were called, just regular response > print(f"Response: {streaming_content}") > messages.append({"role": "assistant", "content": streaming_content}) > break > > elif choice.finish_reason == "tool_calls": > # Step 3: Reconstruct and append assistant message with tool calls > tool_calls_for_message = [] > for func_call in function_calls: > tool_calls_for_message.append({ > "id": func_call["call_id"], > "type": "function", > "function": { > "name": func_call["name"], > "arguments": func_call["arguments"] > } > }) > > assistant_message = { > "role": "assistant", > "content": None, > "tool_calls": tool_calls_for_message > } > messages.append(assistant_message) # Append assistant response > > # Step 4: Execute each function and add results to messages > for function_call in function_calls: > function_name = function_call["name"] > > if function_name == "calculate_mean": > try: > arguments_dict = json.loads(function_call["arguments"]) > function_response = calculate_mean(arguments_dict["numbers"]) > > # Add tool response to messages > messages.append({ > "role": "tool", > "content": str(function_response), > "tool_call_id": function_call["call_id"], > "name": function_name, > }) > except Exception as e: > # Handle errors gracefully > messages.append({ > "role": "tool", > "content": f"Error: {str(e)}", > "tool_call_id": function_call["call_id"], > "name": function_name, > }) > > # Step 5: Get the final response from the model > final_response = client.chat.chat( > model="palmyra-x5", > messages=messages, > stream=True > ) > > final_content = "" > for chunk in final_response: > choice = chunk.choices[0] > if choice.delta and choice.delta.content: > final_content += choice.delta.content > print(choice.delta.content, end="", flush=True) > > # Step 6: Add final response to message history > messages.append({ > "role": "assistant", > "content": final_content > }) > break > ``` > > ```js JavaScript [expandable] theme={null} > import { Writer } from "writer-sdk"; > > // Initialize the Writer client. If you don't pass the `apiKey` parameter, > // the client looks for the `WRITER_API_KEY` environment variable. > const client = new Writer(); > > function calculateMean(numbers) { > if (numbers.length === 0) { > throw new Error("Cannot calculate mean of an empty array"); > } > return numbers.reduce((sum, num) => sum + num, 0) / numbers.length; > } > > const tools = [ > { > type: "function", > function: { > name: "calculate_mean", > description: "Calculate the mean (average) of a list of numbers.", > parameters: { > type: "object", > properties: { > numbers: { > type: "array", > items: { type: "number" }, > description: "List of numbers", > }, > }, > required: ["numbers"], > }, > }, > }, > ]; > > async function main() { > let messages = [ > { role: "user", content: "what is the mean of [1,3,5,7,9]?" }, > ]; > > // Step 1: Initial request with tools > const response = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > tools: tools, > tool_choice: "auto", > stream: true > }); > > // Step 2: Process streaming response to collect tool calls > let streamingContent = ""; > const functionCalls = []; > > for await (const chunk of response) { > const choice = chunk.choices[0]; > > if (choice.delta) { > // Collect tool calls as they stream in > if (choice.delta.tool_calls) { > for (const toolCall of choice.delta.tool_calls) { > if (toolCall.id) { > // Start a new function call > functionCalls.push({ > name: "", > arguments: "", > call_id: toolCall.id, > }); > } > if (toolCall.function) { > // Append to the most recent function call > if (functionCalls.length > 0) { > functionCalls[functionCalls.length - 1].name += toolCall.function.name || ""; > functionCalls[functionCalls.length - 1].arguments += toolCall.function.arguments || ""; > } > } > } > } > // Collect regular content (for cases where no tools are called) > else if (choice.delta.content) { > streamingContent += choice.delta.content; > } > } > > // Check if streaming is complete > if (choice.finish_reason) { > if (choice.finish_reason === "stop") { > // No tools were called, just regular response > console.log(`Response: ${streamingContent}`); > messages.push({ role: "assistant", content: streamingContent }); > break; > } else if (choice.finish_reason === "tool_calls") { > // Step 3: Reconstruct and append assistant message with tool calls > const toolCallsForMessage = []; > for (const funcCall of functionCalls) { > toolCallsForMessage.push({ > id: funcCall.call_id, > type: "function", > function: { > name: funcCall.name, > arguments: funcCall.arguments, > }, > }); > } > > const assistantMessage = { > role: "assistant", > content: null, > tool_calls: toolCallsForMessage, > }; > messages.push(assistantMessage); // Append assistant response > > // Step 4: Execute each function and add results to messages > for (const functionCall of functionCalls) { > const functionName = functionCall.name; > > if (functionName === "calculate_mean") { > try { > const argumentsDict = JSON.parse(functionCall.arguments); > const functionResponse = calculateMean(argumentsDict.numbers); > > // Add tool response to messages > messages.push({ > role: "tool", > content: functionResponse.toString(), > tool_call_id: functionCall.call_id, > name: functionName, > }); > } catch (error) { > // Handle errors gracefully > messages.push({ > role: "tool", > content: `Error: ${error.message}`, > tool_call_id: functionCall.call_id, > name: functionName, > }); > } > } > } > > // Step 5: Get the final response from the model > const finalResponse = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > stream: true > }); > > let finalContent = ""; > for await (const chunk of finalResponse) { > const choice = chunk.choices[0]; > if (choice.delta && choice.delta.content) { > finalContent += choice.delta.content; > process.stdout.write(choice.delta.content); > } > } > > // Step 6: Add final response to message history > messages.push({ > role: "assistant", > content: finalContent, > }); > break; > } > } > } > } > > main(); > ``` > [tab] Non-streaming > > ### Non-streaming > > If you set `stream` to `false`, the tool calls come back in one object inside of the `message` object in the `choices` array. To process the tool calls: > > 1. Get the assistant's response and append it to the message history > 2. Check for tool calls and execute the corresponding functions, appending tool results to the message history > 3. Get the final response from the model and append it to the message history > > #### Step 1: Get and append the assistant's response > > First, get the assistant's response message and append it to your conversation history. This is crucial for maintaining context. > > ```python Python theme={null} > response_message = response.choices[0].message > messages.append(response_message) # Always append the assistant's response > ``` > > ```js JavaScript theme={null} > const responseMessage = response.choices[0].message; > messages.push(responseMessage); // Always append the assistant's response > ``` > > #### Step 2: Execute functions and append tool results > > Next, check for tool calls and execute the corresponding functions with the arguments provided by the model. Then, append the tool results to the conversation history. > > ```python Python theme={null} > tool_calls = response_message.tool_calls > if tool_calls: > for tool_call in tool_calls: > tool_call_id = tool_call.id > function_name = tool_call.function.name > function_args = json.loads(tool_call.function.arguments) > > if function_name == "calculate_mean": > function_response = calculate_mean(function_args["numbers"]) > > # Append tool result to conversation history > messages.append({ > "role": "tool", > "tool_call_id": tool_call_id, > "name": function_name, > "content": str(function_response), > }) > ``` > > ```js JavaScript theme={null} > const toolCalls = responseMessage.tool_calls; > if (toolCalls && toolCalls.length > 0) { > for (const toolCall of toolCalls) { > const toolCallId = toolCall.id; > const functionName = toolCall.function.name; > const functionArgs = JSON.parse(toolCall.function.arguments); > > if (functionName === "calculate_mean") { > const functionResponse = calculateMean(functionArgs.numbers); > > // Append tool result to conversation history > messages.push({ > role: "tool", > tool_call_id: toolCallId, > name: functionName, > content: functionResponse.toString(), > }); > } > } > } > ``` > > #### Step 3: Get and append the final response > > After appending tool results, get the final response from the model and append it to maintain complete conversation history: > > ```python Python theme={null} > final_response = client.chat.chat( > model="palmyra-x5", > messages=messages, > stream=False > ) > > final_content = final_response.choices[0].message.content > print(f"Final response: {final_content}") > > # Append final response to conversation history > messages.append({ > "role": "assistant", > "content": final_content > }) > ``` > > ```js JavaScript theme={null} > const finalResponse = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > stream: false > }); > > const finalContent = finalResponse.choices[0].message.content; > console.log(`Final response: ${finalContent}`); > > // Append final response to conversation history > messages.push({ > role: "assistant", > content: finalContent > }); > ``` > > #### Complete non-streaming code example > > ```python Python [expandable] theme={null} > import json > from writerai import Writer > > # Initialize the Writer client. If you don't pass the `apiKey` parameter, > # the client looks for the `WRITER_API_KEY` environment variable. > client = Writer() > > def calculate_mean(numbers: list) -> float: > return sum(numbers) / len(numbers) > > tools = [ > { > "type": "function", > "function": { > "name": "calculate_mean", > "description": "Calculate the mean (average) of a list of numbers.", > "parameters": { > "type": "object", > "properties": { > "numbers": { > "type": "array", > "items": {"type": "number"}, > "description": "List of numbers" > } > }, > "required": ["numbers"] > } > } > } > ] > > messages = [{"role": "user", "content": "what is the mean of [1,3,5,7,9]?"}] > > # Step 1: Initial request with tools > response = client.chat.chat( > model="palmyra-x5", > messages=messages, > tools=tools, > tool_choice="auto", > stream=False > ) > > # Step 2: Get and append assistant response > response_message = response.choices[0].message > messages.append(response_message) > tool_calls = response_message.tool_calls > > # Step 3: Process tool calls if any > if tool_calls: > for tool_call in tool_calls: > tool_call_id = tool_call.id > function_name = tool_call.function.name > function_args = json.loads(tool_call.function.arguments) > > if function_name == "calculate_mean": > function_response = calculate_mean(function_args["numbers"]) > > # Append tool result to conversation history > messages.append({ > "role": "tool", > "tool_call_id": tool_call_id, > "name": function_name, > "content": str(function_response), > }) > > # Step 4: Get final response > final_response = client.chat.chat( > model="palmyra-x5", > messages=messages, > stream=False > ) > > final_content = final_response.choices[0].message.content > print(f"Final response: {final_content}") > > # Step 5: Append final response to conversation history > messages.append({ > "role": "assistant", > "content": final_content > }) > else: > # No tool calls, just use the original response > print(f"Response: {response_message.content}") > ``` > > ```js JavaScript [expandable] theme={null} > import { Writer } from "writer-sdk"; > > // Initialize the Writer client. If you don't pass the `apiKey` parameter, > // the client looks for the `WRITER_API_KEY` environment variable. > const client = new Writer(); > > function calculateMean(numbers) { > if (numbers.length === 0) { > throw new Error("Cannot calculate mean of an empty array"); > } > return numbers.reduce((sum, num) => sum + num, 0) / numbers.length; > } > > const tools = [ > { > type: "function", > function: { > name: "calculate_mean", > description: "Calculate the mean (average) of a list of numbers.", > parameters: { > type: "object", > properties: { > numbers: { > type: "array", > items: { type: "number" }, > description: "List of numbers", > }, > }, > required: ["numbers"], > }, > }, > }, > ]; > > async function main() { > let messages = [ > { role: "user", content: "what is the mean of [1,3,5,7,9]?" }, > ]; > > // Step 1: Initial request with tools > const response = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > tools: tools, > tool_choice: "auto", > stream: false, > }); > > // Step 2: Get and append assistant response > const responseMessage = response.choices[0].message; > messages.push(responseMessage); // Append assistant response > const toolCalls = responseMessage.tool_calls; > > // Step 3: Process tool calls if any > if (toolCalls && toolCalls.length > 0) { > for (const toolCall of toolCalls) { > const toolCallId = toolCall.id; > const functionName = toolCall.function.name; > const functionArgs = JSON.parse(toolCall.function.arguments); > > if (functionName === "calculate_mean") { > const functionResponse = calculateMean(functionArgs.numbers); > > // Append tool result to conversation history > messages.push({ > role: "tool", > tool_call_id: toolCallId, > name: functionName, > content: functionResponse.toString(), > }); > } > } > > // Step 4: Get final response > const finalResponse = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > stream: false > }); > > const finalContent = finalResponse.choices[0].message.content; > console.log(`Final response: ${finalContent}`); > > // Step 5: Append final response to conversation history > messages.push({ > role: "assistant", > content: finalContent > }); > } else { > // No tool calls, just use the original response > console.log(`Response: ${responseMessage.content}`); > } > } > > main(); > ``` ## Multiple tool calls When the model uses multiple tools in a single request, you'll receive multiple tool calls in the response. This section shows you how to handle multiple tool calls for both streaming and non-streaming approaches. > [!NOTE] > > **Non-streaming**: The processing logic for multiple tool calls is identical to single tool calls - the same code handles both scenarios. The only difference is that the loop for checking the response for tool calling processes multiple tool calls instead of one. > > **Streaming**: Multiple tool calls require different logic because tool calls stream in chunks. You need to collect and reconstruct multiple tool calls from streaming chunks before processing them. ### Define multiple functions First, define the functions in your code. ```python Python theme={null} import math def calculate_mean(numbers: list) -> float: if not numbers: raise ValueError("Cannot calculate mean of an empty list") return sum(numbers) / len(numbers) def calculate_standard_deviation(numbers: list) -> float: if len(numbers) < 2: raise ValueError("Cannot calculate standard deviation with fewer than 2 numbers") mean = calculate_mean(numbers) variance = sum((x - mean) ** 2 for x in numbers) / len(numbers) return math.sqrt(variance) ``` ```js JavaScript theme={null} function calculateMean(numbers) { if (numbers.length === 0) { throw new Error("Cannot calculate mean of an empty array"); } return numbers.reduce((sum, num) => sum + num, 0) / numbers.length; } function calculateStandardDeviation(numbers) { if (numbers.length < 2) { throw new Error("Cannot calculate standard deviation with fewer than 2 numbers"); } const mean = calculateMean(numbers); const variance = numbers.reduce((sum, num) => sum + Math.pow(num - mean, 2), 0) / numbers.length; return Math.sqrt(variance); } ``` ### Define tools array with multiple functions Create a tools array that includes both functions: > [!NOTE] > > For more information about describing functions as tools, see [describe functions as tools section](#describe-functions-as-tools) ```python Python theme={null} tools = [ { "type": "function", "function": { "name": "calculate_mean", "description": "Calculate the mean (average) of a list of numbers. Use this when asked for the average or mean of numbers.", "parameters": { "type": "object", "properties": { "numbers": { "type": "array", "items": {"type": "number"}, "description": "List of numbers to calculate the mean for" } }, "required": ["numbers"] } } }, { "type": "function", "function": { "name": "calculate_standard_deviation", "description": "Calculate the population standard deviation (N) of a list of numbers. Use this when asked for standard deviation, variance, or statistical spread of numbers.", "parameters": { "type": "object", "properties": { "numbers": { "type": "array", "items": {"type": "number"}, "description": "List of numbers to calculate the standard deviation for" } }, "required": ["numbers"] } } } ] ``` ```js JavaScript theme={null} const tools = [ { type: "function", function: { name: "calculate_mean", description: "Calculate the mean (average) of a list of numbers. Use this when asked for the average or mean of numbers.", parameters: { type: "object", properties: { numbers: { type: "array", items: { type: "number" }, description: "List of numbers to calculate the mean for" } }, required: ["numbers"] } } }, { type: "function", function: { name: "calculate_standard_deviation", description: "Calculate the population standard deviation (N) of a list of numbers. Use this when asked for standard deviation, variance, or statistical spread of numbers.", parameters: { type: "object", properties: { numbers: { type: "array", items: { type: "number" }, description: "List of numbers to calculate the standard deviation for" } }, required: ["numbers"] } } } ]; ``` ## Process multiple tool calls When the model identifies a need to call multiple tools based on the user’s input, you'll receive multiple tool calls in the response. The processing differs between streaming and non-streaming approaches. > [tab] Streaming > > ### Streaming > > When using streaming with multiple tool calls, the tool calls come back in chunks inside of the delta object of the choices array. To process multiple tool calls: > > 1. Stream and collect multiple tool calls from the response chunks > 2. Reconstruct the assistant's response with all tool calls and append it to the message history > 3. Execute all functions and append tool results to the message history > 4. Get the final response from the model and append it to the message history > > This requires different logic from single tool calls because you need to collect and reconstruct multiple tool calls from streaming chunks. > > #### Step 1: Stream and collect multiple tool calls from the response chunks > > First, stream and collect multiple tool calls from the response chunks. This is where multiple tool calls differ from single tool calls: > > ```python Python theme={null} > streaming_content = "" > function_calls = [] > > for chunk in response: > choice = chunk.choices[0] > > if choice.delta: > # Collect tool calls as they stream in > if choice.delta.tool_calls: > for tool_call in choice.delta.tool_calls: > if tool_call.id: > # Start a new function call > function_calls.append({ > "name": "", > "arguments": "", > "call_id": tool_call.id > }) > if tool_call.function: > # Append to the most recent function call > if function_calls: > function_calls[-1]["name"] += tool_call.function.name or "" > function_calls[-1]["arguments"] += tool_call.function.arguments or "" > > # Collect regular content (for cases where no tools are called) > elif choice.delta.content: > streaming_content += choice.delta.content > > # Check if streaming is complete > if choice.finish_reason: > if choice.finish_reason == "stop": > # No tools were called, just regular response > messages.append({"role": "assistant", "content": streaming_content}) > break > > elif choice.finish_reason == "tool_calls": > print(f"Tool calls collected: {len(function_calls)}") > break > ``` > > ```js JavaScript theme={null} > let streamingContent = ""; > const functionCalls = []; > > for await (const chunk of response) { > const choice = chunk.choices[0]; > > if (choice.delta) { > // Collect tool calls as they stream in > if (choice.delta.tool_calls) { > for (const toolCall of choice.delta.tool_calls) { > if (toolCall.id) { > // Start a new function call > functionCalls.push({ > name: "", > arguments: "", > call_id: toolCall.id > }); > } > if (toolCall.function) { > // Append to the most recent function call > if (functionCalls.length > 0) { > functionCalls[functionCalls.length - 1].name += toolCall.function.name || ""; > functionCalls[functionCalls.length - 1].arguments += toolCall.function.arguments || ""; > } > } > } > } > // Collect regular content (for cases where no tools are called) > else if (choice.delta.content) { > streamingContent += choice.delta.content; > } > } > > // Check if streaming is complete > if (choice.finish_reason) { > if (choice.finish_reason === "stop") { > // No tools were called, just regular response > messages.push({ role: "assistant", content: streamingContent }); > break; > } else if (choice.finish_reason === "tool_calls") { > console.log(`Tool calls collected: ${functionCalls.length}`); > break; > } > } > } > ``` > > #### Step 2: Reconstruct and append assistant message with multiple tool calls > > Reconstruct the assistant message with all collected tool calls: > > ```python Python theme={null} > # Step 3: Reconstruct and append assistant message with multiple tool calls > tool_calls_for_message = [] > for func_call in function_calls: > tool_calls_for_message.append({ > "id": func_call["call_id"], > "type": "function", > "function": { > "name": func_call["name"], > "arguments": func_call["arguments"] > } > }) > > assistant_message = { > "role": "assistant", > "content": None, > "tool_calls": tool_calls_for_message > } > messages.append(assistant_message) > ``` > > ```js JavaScript theme={null} > // Step 3: Reconstruct and append assistant message with multiple tool calls > const toolCallsForMessage = []; > for (const funcCall of functionCalls) { > toolCallsForMessage.push({ > id: funcCall.call_id, > type: "function", > function: { > name: funcCall.name, > arguments: funcCall.arguments > } > }); > } > > const assistantMessage = { > role: "assistant", > content: null, > tool_calls: toolCallsForMessage > }; > messages.push(assistantMessage); > ``` > > #### Step 3: Execute all functions and append results > > Execute each function and append the results to the conversation history: > > ```python Python theme={null} > # Step 4: Execute all functions and append results > for function_call in function_calls: > function_name = function_call["name"] > > print(f"Processing tool call: {function_name}") > > if function_name == "calculate_mean": > try: > arguments_dict = json.loads(function_call["arguments"]) > function_response = calculate_mean(arguments_dict["numbers"]) > except Exception as e: > function_response = f"Error: {str(e)}" > elif function_name == "calculate_standard_deviation": > try: > arguments_dict = json.loads(function_call["arguments"]) > function_response = calculate_standard_deviation(arguments_dict["numbers"]) > except Exception as e: > function_response = f"Error: {str(e)}" > else: > function_response = f"Unknown function: {function_name}" > > print(f"Function response: {function_response}") > > # Append tool result to conversation history > messages.append({ > "role": "tool", > "content": str(function_response), > "tool_call_id": function_call["call_id"], > "name": function_name, > }) > ``` > > ```js JavaScript theme={null} > // Step 4: Execute all functions and append results > for (const functionCall of functionCalls) { > const functionName = functionCall.name; > let functionResponse; > > console.log(`Processing tool call: ${functionName}`); > > if (functionName === "calculate_mean") { > try { > const argumentsDict = JSON.parse(functionCall.arguments); > functionResponse = calculateMean(argumentsDict.numbers); > } catch (error) { > functionResponse = `Error: ${error.message}`; > } > } else if (functionName === "calculate_standard_deviation") { > try { > const argumentsDict = JSON.parse(functionCall.arguments); > functionResponse = calculateStandardDeviation(argumentsDict.numbers); > } catch (error) { > functionResponse = `Error: ${error.message}`; > } > } else { > functionResponse = `Unknown function: ${functionName}`; > } > > console.log(`Function response: ${functionResponse}`); > > // Append tool result to conversation history > messages.push({ > role: "tool", > content: functionResponse.toString(), > tool_call_id: functionCall.call_id, > name: functionName, > }); > } > ``` > > #### Step 4: Get the final response > > Get the final response from the model after all tool calls are processed: > > ```python Python theme={null} > # Step 5: Get the final response > final_response = client.chat.chat( > model="palmyra-x5", > messages=messages, > stream=True > ) > > final_content = "" > for chunk in final_response: > choice = chunk.choices[0] > if choice.delta and choice.delta.content: > final_content += choice.delta.content > > print(f"Final response: {final_content}") > ``` > > ```js JavaScript theme={null} > // Step 5: Get the final response > const finalResponse = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > stream: true > }); > > let finalContent = ""; > for await (const chunk of finalResponse) { > const choice = chunk.choices[0]; > if (choice.delta && choice.delta.content) { > finalContent += choice.delta.content; > } > } > > console.log(`Final response: ${finalContent}`); > ``` > > #### Step 5: Append final response to conversation history > > Append the final response to maintain complete conversation history: > > ```python Python theme={null} > # Step 5: Append final response to conversation history > messages.append({ > "role": "assistant", > "content": final_content > }) > ``` > > ```js JavaScript theme={null} > // Step 5: Append final response to conversation history > messages.push({ > role: "assistant", > content: finalContent > }); > ``` > > #### Complete streaming code example > > ```python Python [expandable] theme={null} > import json > import math > from writerai import Writer > > # Initialize the Writer client. If you don't pass the `apiKey` parameter, > # the client looks for the `WRITER_API_KEY` environment variable. > client = Writer() > > def calculate_mean(numbers: list) -> float: > if not numbers: > raise ValueError("Cannot calculate mean of an empty list") > return sum(numbers) / len(numbers) > > def calculate_standard_deviation(numbers: list) -> float: > if len(numbers) < 2: > raise ValueError("Cannot calculate standard deviation with fewer than 2 numbers") > mean = calculate_mean(numbers) > variance = sum((x - mean) ** 2 for x in numbers) / len(numbers) > return math.sqrt(variance) > > tools = [ > { > "type": "function", > "function": { > "name": "calculate_mean", > "description": "Calculate the mean (average) of a list of numbers. Use this when asked for the average or mean of numbers.", > "parameters": { > "type": "object", > "properties": { > "numbers": { > "type": "array", > "items": {"type": "number"}, > "description": "List of numbers to calculate the mean for" > } > }, > "required": ["numbers"] > } > } > }, > { > "type": "function", > "function": { > "name": "calculate_standard_deviation", > "description": "Calculate the standard deviation of a list of numbers. Use this when asked for standard deviation, variance, or statistical spread of numbers.", > "parameters": { > "type": "object", > "properties": { > "numbers": { > "type": "array", > "items": {"type": "number"}, > "description": "List of numbers to calculate the standard deviation for" > } > }, > "required": ["numbers"] > } > } > } > ] > > messages = [{"role": "user", "content": "What are the mean and standard deviation of [10, 20, 30, 40, 50]?"}] > > # Step 1: Initial request with tools > response = client.chat.chat( > model="palmyra-x5", > messages=messages, > tools=tools, > tool_choice="auto", > stream=True > ) > > # Step 2: Process streaming response to collect multiple tool calls > streaming_content = "" > function_calls = [] > > for chunk in response: > choice = chunk.choices[0] > > if choice.delta: > # Collect tool calls as they stream in > if choice.delta.tool_calls: > for tool_call in choice.delta.tool_calls: > if tool_call.id: > # Start a new function call > function_calls.append({ > "name": "", > "arguments": "", > "call_id": tool_call.id > }) > if tool_call.function: > # Append to the most recent function call > if function_calls: > function_calls[-1]["name"] += tool_call.function.name or "" > function_calls[-1]["arguments"] += tool_call.function.arguments or "" > > # Collect regular content (for cases where no tools are called) > elif choice.delta.content: > streaming_content += choice.delta.content > > # Check if streaming is complete > if choice.finish_reason: > if choice.finish_reason == "stop": > # No tools were called, just regular response > print(f"Response: {streaming_content}") > messages.append({"role": "assistant", "content": streaming_content}) > break > > elif choice.finish_reason == "tool_calls": > print(f"Tool calls collected: {len(function_calls)}") > break > > # Step 3: Reconstruct and append assistant message with multiple tool calls > tool_calls_for_message = [] > for func_call in function_calls: > tool_calls_for_message.append({ > "id": func_call["call_id"], > "type": "function", > "function": { > "name": func_call["name"], > "arguments": func_call["arguments"] > } > }) > > assistant_message = { > "role": "assistant", > "content": None, > "tool_calls": tool_calls_for_message > } > messages.append(assistant_message) > > # Step 4: Execute all functions and append results > for function_call in function_calls: > function_name = function_call["name"] > > print(f"Processing tool call: {function_name}") > > if function_name == "calculate_mean": > try: > arguments_dict = json.loads(function_call["arguments"]) > function_response = calculate_mean(arguments_dict["numbers"]) > except Exception as e: > function_response = f"Error: {str(e)}" > elif function_name == "calculate_standard_deviation": > try: > arguments_dict = json.loads(function_call["arguments"]) > function_response = calculate_standard_deviation(arguments_dict["numbers"]) > except Exception as e: > function_response = f"Error: {str(e)}" > else: > function_response = f"Unknown function: {function_name}" > > print(f"Function response: {function_response}") > > # Append tool result to conversation history > messages.append({ > "role": "tool", > "content": str(function_response), > "tool_call_id": function_call["call_id"], > "name": function_name, > }) > > # Step 5: Get the final response > final_response = client.chat.chat( > model="palmyra-x5", > messages=messages, > stream=True > ) > > final_content = "" > for chunk in final_response: > choice = chunk.choices[0] > if choice.delta and choice.delta.content: > final_content += choice.delta.content > print(choice.delta.content, end="", flush=True) > > print(f"\nFinal response: {final_content}") > > # Step 6: Append final response to conversation history > messages.append({ > "role": "assistant", > "content": final_content > }) > ``` > > ```js JavaScript [expandable] theme={null} > import { Writer } from "writer-sdk"; > > // Initialize the Writer client. If you don't pass the `apiKey` parameter, > // the client looks for the `WRITER_API_KEY` environment variable. > const client = new Writer(); > > function calculateMean(numbers) { > if (numbers.length === 0) { > throw new Error("Cannot calculate mean of an empty array"); > } > return numbers.reduce((sum, num) => sum + num, 0) / numbers.length; > } > > function calculateStandardDeviation(numbers) { > if (numbers.length < 2) { > throw new Error("Cannot calculate standard deviation with fewer than 2 numbers"); > } > const mean = calculateMean(numbers); > const variance = numbers.reduce((sum, num) => sum + Math.pow(num - mean, 2), 0) / numbers.length; > return Math.sqrt(variance); > } > > const tools = [ > { > type: "function", > function: { > name: "calculate_mean", > description: "Calculate the mean (average) of a list of numbers. Use this when asked for the average or mean of numbers.", > parameters: { > type: "object", > properties: { > numbers: { > type: "array", > items: { type: "number" }, > description: "List of numbers to calculate the mean for" > } > }, > required: ["numbers"] > } > } > }, > { > type: "function", > function: { > name: "calculate_standard_deviation", > description: "Calculate the standard deviation of a list of numbers. Use this when asked for standard deviation, variance, or statistical spread of numbers.", > parameters: { > type: "object", > properties: { > numbers: { > type: "array", > items: { type: "number" }, > description: "List of numbers to calculate the standard deviation for" > } > }, > required: ["numbers"] > } > } > } > ]; > > async function main() { > let messages = [{ role: "user", content: "What are the mean and standard deviation of [10, 20, 30, 40, 50]?" }]; > > // Step 1: Initial request with tools > const response = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > tools: tools, > tool_choice: "auto", > stream: true > }); > > // Step 2: Process streaming response to collect multiple tool calls > let streamingContent = ""; > const functionCalls = []; > > for await (const chunk of response) { > const choice = chunk.choices[0]; > > if (choice.delta) { > // Collect tool calls as they stream in > if (choice.delta.tool_calls) { > for (const toolCall of choice.delta.tool_calls) { > if (toolCall.id) { > // Start a new function call > functionCalls.push({ > name: "", > arguments: "", > call_id: toolCall.id > }); > } > if (toolCall.function) { > // Append to the most recent function call > if (functionCalls.length > 0) { > functionCalls[functionCalls.length - 1].name += toolCall.function.name || ""; > functionCalls[functionCalls.length - 1].arguments += toolCall.function.arguments || ""; > } > } > } > } > // Collect regular content (for cases where no tools are called) > else if (choice.delta.content) { > streamingContent += choice.delta.content; > } > } > > // Check if streaming is complete > if (choice.finish_reason) { > if (choice.finish_reason === "stop") { > // No tools were called, just regular response > console.log(`Response: ${streamingContent}`); > messages.push({ role: "assistant", content: streamingContent }); > break; > } else if (choice.finish_reason === "tool_calls") { > console.log(`Tool calls collected: ${functionCalls.length}`); > break; > } > } > } > > // Step 3: Reconstruct and append assistant message with multiple tool calls > const toolCallsForMessage = []; > for (const funcCall of functionCalls) { > toolCallsForMessage.push({ > id: funcCall.call_id, > type: "function", > function: { > name: funcCall.name, > arguments: funcCall.arguments > } > }); > } > > const assistantMessage = { > role: "assistant", > content: null, > tool_calls: toolCallsForMessage > }; > messages.push(assistantMessage); > > // Step 4: Execute all functions and append results > for (const functionCall of functionCalls) { > const functionName = functionCall.name; > > console.log(`Processing tool call: ${functionName}`); > > let functionResponse; > if (functionName === "calculate_mean") { > try { > const argumentsDict = JSON.parse(functionCall.arguments); > functionResponse = calculateMean(argumentsDict.numbers); > } catch (error) { > functionResponse = `Error: ${error.message}`; > } > } else if (functionName === "calculate_standard_deviation") { > try { > const argumentsDict = JSON.parse(functionCall.arguments); > functionResponse = calculateStandardDeviation(argumentsDict.numbers); > } catch (error) { > functionResponse = `Error: ${error.message}`; > } > } else { > functionResponse = `Unknown function: ${functionName}`; > } > > console.log(`Function response: ${functionResponse}`); > > // Append tool result to conversation history > messages.push({ > role: "tool", > content: functionResponse.toString(), > tool_call_id: functionCall.call_id, > name: functionName, > }); > } > > // Step 5: Get the final response > const finalResponse = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > stream: true > }); > > let finalContent = ""; > for await (const chunk of finalResponse) { > const choice = chunk.choices[0]; > if (choice.delta && choice.delta.content) { > finalContent += choice.delta.content; > process.stdout.write(choice.delta.content); > } > } > > console.log(`\nFinal response: ${finalContent}`); > > // Step 6: Append final response to conversation history > messages.push({ > role: "assistant", > content: finalContent > }); > } > > main(); > ``` > [tab] Non-streaming > > ### Non-streaming > > The processing logic for multiple tool calls is identical to single tool calls - the same code handles both scenarios. The only difference is that the loop for checking the response for tool calling processes multiple tool calls instead of one. > > #### Step 1: Get and append the assistant's response > > First, get the assistant's response message and append it to your conversation history. This is crucial for maintaining context. > > ```python Python theme={null} > response_message = response.choices[0].message > messages.append(response_message) # Always append the assistant's response > tool_calls = response_message.tool_calls > ``` > > ```js JavaScript theme={null} > const responseMessage = response.choices[0].message; > messages.push(responseMessage); // Always append the assistant's response > const toolCalls = responseMessage.tool_calls; > ``` > > #### Step 2: Execute functions and append tool results > > Next, check for tool calls and execute the corresponding functions with the arguments provided by the model. Then, append the tool results to the conversation history. > > ```python Python theme={null} > tool_calls = response_message.tool_calls > if tool_calls: > for tool_call in tool_calls: > tool_call_id = tool_call.id > function_name = tool_call.function.name > function_args = json.loads(tool_call.function.arguments) > > # Execute the appropriate function based on the tool call > if function_name == "calculate_mean": > function_response = calculate_mean(function_args["numbers"]) > elif function_name == "calculate_standard_deviation": > function_response = calculate_standard_deviation(function_args["numbers"]) > else: > function_response = f"Unknown function: {function_name}" > > # Append tool result to conversation history > messages.append({ > "role": "tool", > "tool_call_id": tool_call_id, > "name": function_name, > "content": str(function_response), > }) > else: > # No tool calls, just use the original response > print(f"Response: {response_message.content}") > ``` > > ```js JavaScript theme={null} > const toolCalls = responseMessage.tool_calls; > if (toolCalls && toolCalls.length > 0) { > for (const toolCall of toolCalls) { > const toolCallId = toolCall.id; > const functionName = toolCall.function.name; > const functionArgs = JSON.parse(toolCall.function.arguments); > > // Execute the appropriate function based on the tool call > let functionResponse; > if (functionName === "calculate_mean") { > functionResponse = calculateMean(functionArgs.numbers); > } else if (functionName === "calculate_standard_deviation") { > functionResponse = calculateStandardDeviation(functionArgs.numbers); > } else { > functionResponse = `Unknown function: ${functionName}`; > } > > // Append tool result to conversation history > messages.push({ > role: "tool", > tool_call_id: toolCallId, > name: functionName, > content: functionResponse.toString(), > }); > } > } else { > // No tool calls, just use the original response > console.log(`Response: ${responseMessage.content}`); > } > ``` > > #### Step 3: Get and append the final response > > After appending tool results, get the final response from the model and append it to maintain complete conversation history: > > ```python Python theme={null} > final_response = client.chat.chat( > model="palmyra-x5", > messages=messages, > stream=False > ) > > final_content = final_response.choices[0].message.content > print(f"Final response: {final_content}") > ``` > > ```js JavaScript theme={null} > const finalResponse = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > stream: false > }); > > const finalContent = finalResponse.choices[0].message.content; > console.log(`Final response: ${finalContent}`); > ``` > > #### Step 4: Append final response to conversation history > > Append the final response to maintain complete conversation history: > > ```python Python theme={null} > # Append final response to conversation history > messages.append({ > "role": "assistant", > "content": final_content > }) > ``` > > ```js JavaScript theme={null} > // Append final response to conversation history > messages.push({ > role: "assistant", > content: finalContent > }); > ``` > > #### Complete non-streaming code example > > ```python Python [expandable] theme={null} > import json > import math > from writerai import Writer > > # Initialize the Writer client. If you don't pass the `apiKey` parameter, > # the client looks for the `WRITER_API_KEY` environment variable. > client = Writer() > > def calculate_mean(numbers: list) -> float: > if not numbers: > raise ValueError("Cannot calculate mean of an empty list") > return sum(numbers) / len(numbers) > > def calculate_standard_deviation(numbers: list) -> float: > if len(numbers) < 2: > raise ValueError("Cannot calculate standard deviation with fewer than 2 numbers") > mean = calculate_mean(numbers) > variance = sum((x - mean) ** 2 for x in numbers) / len(numbers) > return math.sqrt(variance) > > tools = [ > { > "type": "function", > "function": { > "name": "calculate_mean", > "description": "Calculate the mean (average) of a list of numbers. Use this when asked for the average or mean of numbers.", > "parameters": { > "type": "object", > "properties": { > "numbers": { > "type": "array", > "items": {"type": "number"}, > "description": "List of numbers to calculate the mean for" > } > }, > "required": ["numbers"] > } > } > }, > { > "type": "function", > "function": { > "name": "calculate_standard_deviation", > "description": "Calculate the standard deviation of a list of numbers. Use this when asked for standard deviation, variance, or statistical spread of numbers.", > "parameters": { > "type": "object", > "properties": { > "numbers": { > "type": "array", > "items": {"type": "number"}, > "description": "List of numbers to calculate the standard deviation for" > } > }, > "required": ["numbers"] > } > } > } > ] > > messages = [{"role": "user", "content": "What are the mean and standard deviation of [10, 20, 30, 40, 50]?"}] > > # Step 1: Initial request with tools > response = client.chat.chat( > model="palmyra-x5", > messages=messages, > tools=tools, > tool_choice="auto", > stream=False > ) > > # Step 2: Get and append assistant response > response_message = response.choices[0].message > messages.append(response_message) > tool_calls = response_message.tool_calls > > # Step 3: Process tool calls if any > if tool_calls: > for tool_call in tool_calls: > tool_call_id = tool_call.id > function_name = tool_call.function.name > function_args = json.loads(tool_call.function.arguments) > > # Execute the appropriate function based on the tool call > if function_name == "calculate_mean": > function_response = calculate_mean(function_args["numbers"]) > elif function_name == "calculate_standard_deviation": > function_response = calculate_standard_deviation(function_args["numbers"]) > else: > function_response = f"Unknown function: {function_name}" > > # Append tool result to conversation history > messages.append({ > "role": "tool", > "tool_call_id": tool_call_id, > "name": function_name, > "content": str(function_response), > }) > > # Step 4: Get final response > final_response = client.chat.chat( > model="palmyra-x5", > messages=messages, > stream=False > ) > > final_content = final_response.choices[0].message.content > print(f"Final response: {final_content}") > > # Step 5: Append final response to conversation history > messages.append({ > "role": "assistant", > "content": final_content > }) > else: > # No tool calls, just use the original response > print(f"Response: {response_message.content}") > ``` > > ```js JavaScript [expandable] theme={null} > import { Writer } from "writer-sdk"; > > // Initialize the Writer client. If you don't pass the `apiKey` parameter, > // the client looks for the `WRITER_API_KEY` environment variable. > const client = new Writer(); > > function calculateMean(numbers) { > if (numbers.length === 0) { > throw new Error("Cannot calculate mean of an empty array"); > } > return numbers.reduce((sum, num) => sum + num, 0) / numbers.length; > } > > function calculateStandardDeviation(numbers) { > if (numbers.length < 2) { > throw new Error("Cannot calculate standard deviation with fewer than 2 numbers"); > } > const mean = calculateMean(numbers); > const variance = numbers.reduce((sum, num) => sum + Math.pow(num - mean, 2), 0) / numbers.length; > return Math.sqrt(variance); > } > > const tools = [ > { > type: "function", > function: { > name: "calculate_mean", > description: "Calculate the mean (average) of a list of numbers. Use this when asked for the average or mean of numbers.", > parameters: { > type: "object", > properties: { > numbers: { > type: "array", > items: { type: "number" }, > description: "List of numbers to calculate the mean for" > } > }, > required: ["numbers"] > } > } > }, > { > type: "function", > function: { > name: "calculate_standard_deviation", > description: "Calculate the standard deviation of a list of numbers. Use this when asked for standard deviation, variance, or statistical spread of numbers.", > parameters: { > type: "object", > properties: { > numbers: { > type: "array", > items: { type: "number" }, > description: "List of numbers to calculate the standard deviation for" > } > }, > required: ["numbers"] > } > } > } > ]; > > async function main() { > let messages = [{ role: "user", content: "What are the mean and standard deviation of [10, 20, 30, 40, 50]?" }]; > > // Step 1: Initial request with tools > const response = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > tools: tools, > tool_choice: "auto", > stream: false > }); > > // Step 2: Get and append assistant response > const responseMessage = response.choices[0].message; > messages.push(responseMessage); > const toolCalls = responseMessage.tool_calls; > > // Step 3: Process tool calls if any > if (toolCalls && toolCalls.length > 0) { > for (const toolCall of toolCalls) { > const toolCallId = toolCall.id; > const functionName = toolCall.function.name; > const functionArgs = JSON.parse(toolCall.function.arguments); > > // Execute the appropriate function based on the tool call > let functionResponse; > if (functionName === "calculate_mean") { > functionResponse = calculateMean(functionArgs.numbers); > } else if (functionName === "calculate_standard_deviation") { > functionResponse = calculateStandardDeviation(functionArgs.numbers); > } else { > functionResponse = `Unknown function: ${functionName}`; > } > > // Append tool result to conversation history > messages.push({ > role: "tool", > tool_call_id: toolCallId, > name: functionName, > content: functionResponse.toString(), > }); > } > > // Step 4: Get final response > const finalResponse = await client.chat.chat({ > model: "palmyra-x5", > messages: messages, > stream: false > }); > > const finalContent = finalResponse.choices[0].message.content; > console.log(`Final response: ${finalContent}`); > > // Step 5: Append final response to conversation history > messages.push({ > role: "assistant", > content: finalContent > }); > } else { > // No tool calls, just use the original response > console.log(`Response: ${responseMessage.content}`); > } > } > > main(); > ``` > [!NOTE] > > When processing multiple tool calls, ensure that: > > * All tool calls are executed before getting the final response > * Each tool result is properly appended to the conversation history > * Error handling is implemented for each tool call > * The final response includes all tool results for context ## Example: External API call The following example covers a common use case for tool calling: calling an external API. The code uses a publicly available [dictionary API](https://dictionaryapi.dev/) to return information about an English word's phonetic pronunciation. This example is using non-streaming; for streaming, refer to the [multiple tool calls streaming example](#process-multiple-tool-calls) to adjust the code. ### Define function calling an API First, define the function in your code. The examples below take in a word, call the dictionary API, and return the phonetic pronunciation of the word as a JSON-formatted string. ```python Python theme={null} import requests import json def get_word_pronunciation(word): url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}" response = requests.get(url) if response.status_code == 200: return json.dumps(response.json()[0]['phonetics']) else: return f"Failed to retrieve word pronunciation. Status code: {response.status_code}" ``` ```js JavaScript theme={null} async function getWordPronunciation(word) { const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`; try { const response = await fetch(url); if (response.ok) { const data = await response.json(); return JSON.stringify(data[0]['phonetics']); } else { return `Failed to retrieve word pronunciation. Status code: ${response.status}`; } } catch (error) { return `Error fetching word pronunciation: ${error.message}`; } } ``` ### Define tools array Next, define a tools array that describes the tool with a JSON schema. ```python Python theme={null} tools = [ { "type": "function", "function": { "name": "get_word_pronunciation", "description": "A function that will return JSON containing the phonetic pronunciation of an English word", "parameters": { "type": "object", "properties": { "word": { "type": "string", "description": "The word to get the phonetic pronunciation for", } }, "required": ["word"], }, }, } ] ``` ```js JavaScript theme={null} const tools = [ { type: "function", function: { name: "get_word_pronunciation", description: "A function that will return JSON containing the phonetic pronunciation of an English word", parameters: { type: "object", properties: { word: { type: "string", description: "The word to get the phonetic pronunciation for" } }, required: ["word"] } } } ]; ``` ### Pass the tools to the model Call the `chat.chat` method with the `tools` parameter set to the `tools` array and `tool_choice` set to `auto`. ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() messages = [{"role": "user", "content": "what is the phonetic pronunciation of the word 'epitome' in English?"}] response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto", stream=False ) ``` ```js JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); let messages = [{role: "user", content: "what is the phonetic pronunciation of the word 'epitome' in English?"}]; const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, tool_choice: "auto", stream: false }); ``` ### Check response for tool calling Loop through the `tool_calls` array to check for the invocation of the tool. Then, call the tool's function with the arguments the model provided. ```python Python theme={null} response_message = response.choices[0].message messages.append(response_message) tool_calls = response_message.tool_calls if tool_calls: tool_call = tool_calls[0] tool_call_id = tool_call.id function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if function_name == "get_word_pronunciation": function_response = get_word_pronunciation(function_args["word"]) ``` ```js JavaScript theme={null} const responseMessage = response.choices[0].message; messages.push(responseMessage); // Append assistant response const toolCalls = responseMessage.tool_calls; if (toolCalls && toolCalls.length > 0) { const toolCall = toolCalls[0]; const toolCallId = toolCall.id; const functionName = toolCall.function.name; const functionArgs = JSON.parse(toolCall.function.arguments); if (functionName === "get_word_pronunciation") { const functionResponse = await getWordPronunciation(functionArgs.word); } } ``` ### Append the tool result to the conversation history Finally, pass the result back to the model by appending it to the messages array, and get the final response. ```python Python theme={null} messages.append({ "role": "tool", "tool_call_id": tool_call_id, "name": function_name, "content": function_response, }) final_response = client.chat.chat( model="palmyra-x5", messages=messages, stream=False ) final_content = final_response.choices[0].message.content # Append final response to conversation history messages.append({ "role": "assistant", "content": final_content }) print(f"Final response: {final_content}") # Final response: The phonetic pronunciation of the word "epitome" in English is /əˈpɪt.ə.mi/... ``` ```js JavaScript theme={null} messages.push({ role: "tool", tool_call_id: toolCallId, name: functionName, content: functionResponse, }); const finalResponse = await client.chat.chat({ model: "palmyra-x5", messages: messages, stream: false }); const finalContent = finalResponse.choices[0].message.content; // Append final response to conversation history messages.push({ role: "assistant", content: finalContent }); console.log(`Final response: ${finalContent}`); // Final response: The phonetic pronunciation of the word "epitome" in English is /əˈpɪt.ə.mi/... ``` ### Complete external API call example ```python Python [expandable] theme={null} import requests import json from writerai import Writer # Initialize the Writer client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() def get_word_pronunciation(word): url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}" try: response = requests.get(url) if response.status_code == 200: return json.dumps(response.json()[0]['phonetics']) else: return f"Failed to retrieve word pronunciation. Status code: {response.status_code}" except Exception as e: return f"Error fetching word pronunciation: {str(e)}" tools = [ { "type": "function", "function": { "name": "get_word_pronunciation", "description": "A function that will return JSON containing the phonetic pronunciation of an English word", "parameters": { "type": "object", "properties": { "word": { "type": "string", "description": "The word to get the phonetic pronunciation for", } }, "required": ["word"], }, }, } ] messages = [{"role": "user", "content": "what is the phonetic pronunciation of the word 'epitome' in English?"}] # Step 1: Initial request response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto", stream=False ) # Step 2: Append assistant response response_message = response.choices[0].message messages.append(response_message) tool_calls = response_message.tool_calls # Step 3: Process tool calls if tool_calls: for tool_call in tool_calls: tool_call_id = tool_call.id function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if function_name == "get_word_pronunciation": function_response = get_word_pronunciation(function_args["word"]) # Append tool result messages.append({ "role": "tool", "tool_call_id": tool_call_id, "name": function_name, "content": function_response, }) # Step 4: Get final response final_response = client.chat.chat( model="palmyra-x5", messages=messages, stream=False ) final_content = final_response.choices[0].message.content # Step 5: Append final response messages.append({ "role": "assistant", "content": final_content }) print(f"Final response: {final_content}") # The conversation history is now complete and ready for additional turns ``` ```javascript JavaScript [expandable] theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); async function getWordPronunciation(word) { const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`; try { const response = await fetch(url); if (response.ok) { const data = await response.json(); return JSON.stringify(data[0]['phonetics']); } else { return `Failed to retrieve word pronunciation. Status code: ${response.status}`; } } catch (error) { return `Error fetching word pronunciation: ${error.message}`; } } const tools = [ { type: "function", function: { name: "get_word_pronunciation", description: "A function that will return JSON containing the phonetic pronunciation of an English word", parameters: { type: "object", properties: { word: { type: "string", description: "The word to get the phonetic pronunciation for" } }, required: ["word"] } } } ]; async function main() { let messages = [{ role: "user", content: "what is the phonetic pronunciation of the word 'epitome' in English?" }]; // Step 1: Initial request const response = await client.chat.chat({ model: "palmyra-x5", messages: messages, tools: tools, tool_choice: "auto", stream: false }); // Step 2: Append assistant response const responseMessage = response.choices[0].message; messages.push(responseMessage); const toolCalls = responseMessage.tool_calls; // Step 3: Process tool calls if (toolCalls && toolCalls.length > 0) { for (const toolCall of toolCalls) { const toolCallId = toolCall.id; const functionName = toolCall.function.name; const functionArgs = JSON.parse(toolCall.function.arguments); if (functionName === "get_word_pronunciation") { const functionResponse = await getWordPronunciation(functionArgs.word); // Append tool result messages.push({ role: "tool", tool_call_id: toolCallId, name: functionName, content: functionResponse, }); } } // Step 4: Get final response const finalResponse = await client.chat.chat({ model: "palmyra-x5", messages: messages, stream: false }); const finalContent = finalResponse.choices[0].message.content; // Step 5: Append final response messages.push({ role: "assistant", content: finalContent }); console.log(`Final response: ${finalContent}`); } } main(); ``` ## Next steps By following this guide, you can incorporate tool calling into your application and augment the capabilities of a model with real-time data, math operations, business logic, and much more. For more examples, check out the [tool calling cookbooks](https://github.com/writer/cookbooks/tree/main/tool_calling) available on GitHub. Next, learn how to invoke [no-code agents with tool calling](/home/applications-tool-calling). Or, explore prebuilt tools that Writer models can execute remotely: * [Ask questions to a Knowledge Graph in a chat](/home/kg-chat) * [Delegate questions to another model](/home/model-delegation) # Toxic check Source: https://dev.writer.com/home/toxic-check We developed an independent system that classifies input and output textual data and predicts its level of toxicity. Our model was trained on a distinct dataset that included both toxic and nontoxic examples. Each prompt is sent through the API to one of our large language models, and the generated text is analyzed and classified by a model that predicts the text's toxicity level. This probability lies between 0 and 1, where 0 indicates toxic classes and 1 indicates nontoxic classes The Palmyra models provide scores for several different attributes, including Toxicity. Here are some of the other attributes Palmyra can provide scores for: * **Severe Toxicity**: A very hateful, aggressive, disrespectful comment or otherwise very likely to make a user leave a discussion or give up on sharing their perspective. This attribute is much less sensitive to more mild forms of toxicity, such as comments that include positive uses of curse words. * **Insult**: Insulting, inflammatory, or negative comment towards a person or a group of people. * **Profanity**: Swear words, curse words, or other obscene or profane language. * **Identity Attack**: Negative or hateful comments targeting someone because of their identity. * **Threat**: Describes an intention to inflict pain, injury, or violence against an individual or group. * **Sexually explicit**: Contains references to sexual acts, body parts, or other lewd content. The text completion API methods return a JSON response with two fields, prompt labels and completion labels, that indicate the toxicity scores for each part independently. The field class name contains a binary class label determined by score, where a value less than 0.5 indicates toxicity and a value greater than 0.5 indicates nontoxicity. ```json theme={null} "prompt_labels": [ { "class_name": "nontoxic", "score": 0.995605 } ], "completion_labels": [ { "class_name": "nontoxic", "score": 0.997559 } ] ``` # Transparency Source: https://dev.writer.com/home/transparency Ensuring transparency and accountability in AI systems ## Introduction The complexity of deep learning models like Palmyra-X makes them remarkably powerful but also increasingly opaque. As the adoption of these AI technologies expands, the necessity for transparency and accountability becomes critical. Writer addresses these concerns by employing a multi-tiered approach that leverages cutting-edge algorithms and technologies. This article provides a detailed technical perspective on these strategies. ## Tools and algorithms for insights into decision-making > [tab] Attention mechanism analysis > > In transformer-based models like Palmyra, attention mechanisms play a crucial role in determining output. By visualizing the weights in the multi-headed attention layers, one can gain insights into which input tokens significantly influence the output. Algorithms like layer-wise relevance propagation can be employed to decompose these attention scores. > [tab] SHAP > > SHAP (SHapley Additive exPlanations) values are derived from cooperative game theory and offer a unified measure of feature importance. By computing SHAP values for each feature in the input data, one can quantify how much each feature contributes to a particular decision, thus offering a granular view of the model's inner workings. > [tab] Comprehensive logging > > A robust logging system captures not just input-output pairs but also intermediate representations, attention maps and activation functions. Tools like TensorBoard with custom dashboards are used for real-time monitoring and auditing at testing stage. > [tab] Bayesian A/B testing > > Traditional A/B testing is enhanced with Bayesian statistical methods to rigorously compare the performance and decision-making processes of different model versions. This provides confidence intervals and posterior distributions that offer more nuanced insights than point estimates. ## Addressing the 'opaque' nature of AI: explainability and transparency > [tab] LIME > > Local Interpretable Model-agnostic Explanations (LIME) is used to create surrogate models that approximate the behavior of the complex model in the vicinity of the instance being explained. By perturbing the input and observing the output, LIME fits a simple model that is easier to interpret, thus shedding light on the original model's decision-making process. > [tab] Counterfactual Explanations > > Counterfactual explanations provide "what-if" scenarios that help understand how a different input could lead to a different output. We use DiCE Algorithm (Diverse Counterfactual Explanations) to generate these scenarios. > [tab] Open Source and Community Auditing > > Releasing the models under an open-source Apache 2.0 license allows for community-based auditing. Skilled developers and researchers can scrutinize the codebase, algorithms, and even contribute to enhancing transparency features. > [tab] Differential Privacy > > To safeguard user data while maintaining transparency, differential privacy algorithms like Laplace noise addition or Differential Privacy SGD are implemented. This allows the model to be queried for insights without revealing any individual data points. ## Compliance and regulations For regulatory compliance, techniques such as Automatic Fairness Verification and Fairness-aware Learning are integrated into the model training pipeline. These ensure that the model meets standards like GDPR, which mandates the right to explanation for automated decisions. ## Conclusion Transparency and accountability in AI models are complex challenges that require a multi-layered, algorithmically robust approach. By employing advanced techniques like SHAP, LIME‌ and Bayesian A/B testing, Writer aims to open up the "black box" of its AI models. While full transparency remains a moving target, these technologies and methodologies provide a comprehensive framework for making significant strides in understanding and auditing AI systems. # Usage and spend Source: https://dev.writer.com/home/usage-and-spend Track organization-wide costs, token usage, and consumption trends across all agents The Consumption view in Control Center gives billing administrators and finance teams a detailed breakdown of usage and spend month-by-month across all agents. Track costs by agent type, model, and service to understand where your organization's AI budget is going. > [!NOTE] > > The Consumption view is only available to [organization > admins](https://support.writer.com). ## View your consumption data To access the Consumption view, [log in to Control Center](https://app.writer.com/controlcenter) and select **Billing**, then **Consumption**, in the left sidebar. ![Consumption view in Control Center](https://mintcdn.com/writer/NOX5YaKoHPVl5k0p/images/observability-consumption/navbar-dropdown-observability.png?fit=max\&auto=format\&n=NOX5YaKoHPVl5k0p\&q=85\&s=4476f217d8b0de5e67de6c9855bc1669) You can switch between a cost view and an activity view, which shows the number of tokens used for each agent type. See below for more details about the data available in the [cost view](#cost-view) and the [activity view](#activity-view). For additional WRITER Agent analytics, see [WRITER Agent analytics](https://support.writer.com/articles/9441751516-writer-agent-analytics) in the Writer Help Center. ## Cost view The cost view shows the following information: * **Monthly usage-based spend**: The total cost of usage for the month, with a comparison to the previous month. * **Spend by agent type**: A day-by-day breakdown of the cost of usage by agent type (API, Framework, and No-Code). * **Spend breakdown**: * **LLM models**: The usage cost for each LLM model. * **Others**: The usage cost for all other services, such as web access and optical character recognition (OCR). ## Activity view The activity view shows the following information: * **Monthly token usage**: The total number of tokens used for the month, with a comparison to the previous month. * **Top users by token usage**: The top five users with the most token usage. * **Top agents by token usage**: The top five agents with the most token usage. * **Token usage by agent type**: A day-by-day breakdown of the token usage by agent type (API, Framework, and No-Code). * **Token usage by model**: The total number of tokens used for each model. ## Next steps * [Observability overview](/home/observability): Monitor events, errors, and performance across your deployment * [Event logs](/home/event-logs): View, filter, and search request logs in Control Center * [WRITER Agent analytics](https://support.writer.com/articles/9441751516-writer-agent-analytics): View additional analytics for WRITER Agent in the Help Center # Usage policy Source: https://dev.writer.com/home/usage-policy Please review the following policies to ensure responsible usage of the Writer API: ## Content Policy The Writer API doesn't allow for the generation of the following types of content: * Hate * Harassment * Violence * Self-harm * Sexual * Political * Spam * Deception * Malware ## Platform Policy * The API is provided for the purpose of accessing the services, and users are expected to use it in accordance with this policy. * Users are responsible for ensuring the security and confidentiality of their API key and any data obtained through the API. * The API may be subject to rate limiting to ensure fair use and prevent excessive use of the system. * The API may be temporarily unavailable for maintenance or upgrades without prior notice. * The API is provided for commercial use, and users are expected to comply with all applicable laws and regulations. * Users may not use the API to engage in any illegal, fraudulent, or malicious activities. * Users may not sell, resell, or lease the API or the data obtained through the API to third parties. * Failure to comply with this policy may result in suspension or termination of access to the API. Writer reserves the right to take necessary measures to enforce this policy and protect the system and other users from harm. This policy may be revised at any time without prior notice. Users are responsible for regularly checking the policy for updates. # Add web content to a Knowledge Graph Source: https://dev.writer.com/home/web-connector-url This guide demonstrates how to add web content to a [Knowledge Graph](/home/knowledge-graph) using web connector URLs. Adding web connector URLs to your Knowledge Graph allows you to automatically extract and index content from websites, making it available for querying in your Knowledge Graph. > [!NOTE] > > You need an API key to access the Writer API. Get an API key by following the steps in the [API quickstart](/home/quickstart). > > We recommend setting the API key as an environment variable in a `.env` file with the name `WRITER_API_KEY`. > [!NOTE] > > Knowledge Graphs can be deployed org-wide (accessible to every team in the organization) or [deployed to specific teams](https://support.writer.com/article/242-how-to-create-and-manage-a-knowledge-graph#Managing-a-Knowledge-Graph-R4Mg5). Both are accessible via the API and SDK. > > * **With an org-scoped API key**, control team scope from the request body: pass `team_ids` on [create](/api-reference/kg-api/create-graph) or [update](/api-reference/kg-api/update-graph), or filter [list](/api-reference/kg-api/list-graphs) with the `team_ids` query parameter. Omit `team_ids` on list to see only org-wide Knowledge Graphs. > * **With a team-scoped API key**, every request is automatically restricted to the key's team. Create assigns to that team; list and retrieve return only that team's Knowledge Graphs; body `team_ids` is not accepted. ## Overview Adding URLs to your Knowledge Graph enables you to: * Automatically extract content from websites * Index web pages for Knowledge Graph queries * Process single pages or entire sub-pages * Monitor the status of URL processing * Exclude specific URLs from processing ## Add URLs to a Knowledge Graph To add web connector URLs to your Knowledge Graph, use the [PUT endpoint](/api-reference/kg-api/update-graph) to update the graph with the URLs you want to process. This endpoint allows you to add, update, or remove URLs from your Knowledge Graph. > [!WARNING] > > You can only add URLs to a Knowledge Graph with the `type` set to `web`. To create a Knowledge Graph with the `web` type, you must create the Knowledge Graph in [Control Center](https://app.writer.com/controlcenter) and select "Add Website" as the way you want to add content to the Knowledge Graph. See [Setting up Knowledge Graph web connectors](https://support.writer.com/article/272-setting-up-knowledge-graph-web-connectors) for more information. > > You can see the type of a Knowledge Graph in the [Knowledge Graph details](/api-reference/kg-api/retrieve-graph) or in the [Knowledge Graph list](/api-reference/kg-api/list-graphs) endpoints. ```bash cURL theme={null} # Note that this operation replaces the entire list of URLs attached to the Knowledge Graph. curl --location --request PUT 'https://api.writer.com/v1/graphs/{graph_id}' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "urls": [ { "url": "https://example.com/documentation", "type": "sub_pages", "exclude_urls": [ "https://example.com/documentation/admin", "https://example.com/documentation/private" ] } ] }' ``` ```python python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() # Note that this operation replaces the entire list of URLs attached to the Knowledge Graph with the new list of URLs. client.graphs.update( "GRAPH_ID", urls=[{ "url": "https://example.com/documentation", "type": "sub_pages", "exclude_urls": [ "https://example.com/documentation/admin", "https://example.com/documentation/private" ] }] ) print(client.graphs.retrieve("GRAPH_ID").urls) ``` ```javascript javascript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); // Note that this operation replaces the entire list of URLs attached to the Knowledge Graph with the new list of URLs. const response = await client.graphs.update('GRAPH_ID', { urls: [{ url: 'https://example.com/documentation', type: 'sub_pages', exclude_urls: [ 'https://example.com/documentation/admin', 'https://example.com/documentation/private' ] }] }); console.log(response.urls); ``` ### Request structure > [!WARNING] > > The `urls` array in your request **replaces** the entire existing list of URLs attached to the Knowledge Graph. To add a new URL, include both the existing URLs and the new one in your request. To remove a URL, send a request with all URLs except the one you want to remove. When updating a Knowledge Graph with URLs, you need to provide a `urls` array in your request body. Each URL object has the following parameters: | Parameter | Type | Description | | - | - | - | | `url` | string | The URL you want to add to your Knowledge Graph | | `type` | string | How you want to process the URL: either `single_page` (just this URL) or `sub_pages` (this URL and linked pages) | | `exclude_urls` | array | Optional. Any URLs you want to exclude from processing if `type` is `sub_pages` | ### Response structure After you update the Knowledge Graph, you see the status of each URL in the `status` object. The `status` object has the following parameters: | Parameter | Type | Description | | - | - | - | | `status` | string | The current processing status: `validating`, `success`, or `error` | | `error_type` | string | If there was an error, what type of error occurred | ```json theme={null} { "id": "51b058d8", "created_at": "2025-07-16T20:19:23.565884Z", "name": "Public docs", "description": "Public docs", "urls": [ { "url": "https://example.com/docs", "status": { "status": "validating", "error_type": null }, "exclude_urls": [ "https://example.com/docs/admin", "https://example.com/docs/private" ], "type": "sub_pages" } ] } ``` #### Possible error types If URL processing fails, you may see these error types: * `invalid_url`: The URL format is not valid * `not_searchable`: The content cannot be accessed or processed * `not_found`: The URL returns a 404 error * `paywall_or_login_page`: The content requires authentication * `unexpected_error`: An unspecified error occurred ## Usage examples The following examples show how to add a web connector URL to a Knowledge Graph and monitor its processing status. ### Add a web connector URL This example adds a web connector URL to a Knowledge Graph. It first retrieves the Knowledge Graph to see the current URLs and then adds a new URL to the Knowledge Graph. Note that this operation replaces the entire list of URLs attached to the Knowledge Graph, which is why it is important to retrieve the existing list of URLs first. ```bash cURL theme={null} # 1. First, retrieve the current Knowledge Graph to see existing URLs curl --location 'https://api.writer.com/v1/graphs/{graph_id}' \ --header "Authorization: Bearer $WRITER_API_KEY" # 2. Then, send a new request with all the URLs you want to add. In this example, there were no existing URLs, so it's adding a single URL. curl --location --request PUT 'https://api.writer.com/v1/graphs/{graph_id}' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "urls": [ { "url": "https://example.com/documentation", "type": "sub_pages", "exclude_urls": [ "https://example.com/documentation/admin", "https://example.com/documentation/private" ] } ] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() graph_id = "GRAPH_ID" graph = client.graphs.retrieve(graph_id) urls = graph.urls urls.append({ "url": "https://example.com/documentation", "type": "sub_pages", "exclude_urls": ["https://example.com/documentation/admin", "https://example.com/documentation/private"] }) client.graphs.update(graph_id, urls=urls) print(client.graphs.retrieve(graph_id).urls) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const graph_id = "GRAPH_ID"; const graph = await client.graphs.retrieve(graph_id); const urls = graph.urls; urls.push({ url: 'https://example.com/documentation', type: 'sub_pages', exclude_urls: [ 'https://example.com/documentation/admin', 'https://example.com/documentation/private' ] }); const response = await client.graphs.update(graph_id, { urls }); const updatedGraph = await client.graphs.retrieve(graph_id); console.log(updatedGraph.urls); ``` ### Delete all URLs from a Knowledge Graph To delete all URLs from a Knowledge Graph, you can send a request with an empty `urls` array. ```bash cURL theme={null} curl --location --request PUT 'https://api.writer.com/v1/graphs/{graph_id}' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "urls": [] }' ``` ```python Python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() graph_id = "GRAPH_ID" client.graphs.update(graph_id, urls=[]) print(client.graphs.retrieve(graph_id).urls) ``` ```javascript JavaScript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const graph_id = "GRAPH_ID"; const response = await client.graphs.update(graph_id, { urls: [] }); console.log(response.urls); ``` ### Monitor processing status You can check the status of your web connector URLs by retrieving the Knowledge Graph details. ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/graphs/{graph_id}' \ --header "Authorization: Bearer $WRITER_API_KEY" ``` ```python python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() graph = client.graphs.retrieve("GRAPH_ID") print(graph.urls) ``` ```javascript javascript theme={null} import Writer from 'writer-sdk'; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); async function main() { const graph = await client.graphs.retrieve('GRAPH_ID'); console.log(graph.urls); } main(); ``` ### Query the Knowledge Graph with web content Once the web connector URLs have been processed successfully, you can query the Knowledge Graph to access the extracted content. ```bash cURL theme={null} curl --location 'https://api.writer.com/v1/graphs/{graph_id}/query' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $WRITER_API_KEY" \ --data '{ "query": "What are the main features described in the documentation?", "subqueries": true }' ``` ```python python theme={null} from writerai import Writer # Initialize the Writer client. If you don't pass the `api_key` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() response = client.graphs.question( graph_ids=["GRAPH_ID"], question="YOUR QUESTION" ) print(f"Answer: {response.answer}") print(f"Sources: {response.sources}") ``` ```javascript javascript theme={null} import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `api_key` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); const response = await client.graphs.question({ graph_ids: ["GRAPH_ID"], question: "YOUR QUESTION" }); console.log(`Answer: ${response.answer}`); console.log(`Sources: ${response.sources}`); ``` ## Next steps By following this guide, you can successfully add web content to your Knowledge Graphs using web connector URLs. Next, learn about other Knowledge Graph capabilities: * [Query a Knowledge Graph](/home/kg-query) * [Use a Knowledge Graph in chat](/home/kg-chat) # WRITER MCP Source: https://dev.writer.com/home/writer-mcp Connect any MCP-compatible client to the WRITER MCP server to run published playbooks and use your Enterprise Brain content. This guide shows you how to connect a Model Context Protocol (MCP) client to the hosted WRITER MCP server. After you connect, you can run published playbooks, work with their outputs, access your WRITER Meet recordings, and use your organization's Enterprise Brain content from your MCP client. ## Connect a client WRITER MCP works with any MCP-compatible client. Every client connects to the same server at `https://api.writer.com/v1/mcp` and signs in with your WRITER account. If your organization is deployed in the EU, use `https://api.eu2.writer.com/v1/mcp` instead. Select your client's tab for its setup steps, or use that URL with your own client's instructions for adding a remote MCP server. > [tab] Cursor > > Install WRITER MCP from the [Cursor Marketplace](https://cursor.com/marketplace/writer), or add the server URL yourself. > > **1. Open the plugin list** > > Open **Cursor Settings**, then **Plugins**. > > **2. Install the plugin** > > Search for **WRITER MCP** and select **Install**. You can also run `/add-plugin writer-mcp` in chat. > > **3. Sign in to WRITER** > > Complete the WRITER sign-in prompt in your browser, then choose one organization on the consent screen. > > To add the server in config, put this entry in a project [`.cursor/mcp.json`](https://cursor.com/docs/context/mcp), or in `~/.cursor/mcp.json` to use it in every project. Cursor asks you to sign in when you enable the server. > > ```json .cursor/mcp.json theme={null} > { > "mcpServers": { > "writer": { > "type": "http", > "url": "https://api.writer.com/v1/mcp" > } > } > } > ``` > > > [!NOTE] > > > > If your organization is deployed in the EU, use `https://api.eu2.writer.com/v1/mcp` instead. > [tab] Grok Bot > > Grok Bot uses the same plugin. See [Connect an app](https://docs.x.ai/grok-bot/computer-and-apps) for how Grok Bot plugins work. > > **1. Open the plugin list** > > Open **Settings**, then **Plugins**. > > **2. Add the plugin** > > Search for **WRITER MCP** and select **Add**. > > **3. Sign in to WRITER** > > Complete WRITER sign-in in your browser if Grok Bot asks you to. > > **4. Attach the plugin** > > In chat, type `@` and attach WRITER MCP to the task. > [tab] Claude > > Add WRITER MCP as a [custom connector](https://support.claude.com/en/articles/11175166-about-custom-connectors-remote-mcp) in Claude on the web, in the desktop app, or in Cowork. > > **1. Open the connector list** > > Go to **Customize**, then **Connectors**. On a Team or Enterprise plan, an owner adds the connector for the organization from **Organization settings**, then **Connectors**. > > **2. Add a custom connector** > > Select **+**, then **Add custom connector**. On a Team or Enterprise plan, the owner selects **Add**, hovers over **Custom**, then selects **Web**. > > **3. Enter the server URL** > > Enter `https://api.writer.com/v1/mcp` and select **Add**. Leave the advanced OAuth fields empty, because the server registers your client for you. > > > [!NOTE] > > > > If your organization is deployed in the EU, use `https://api.eu2.writer.com/v1/mcp` instead. > > **4. Connect and sign in** > > Select **Connect** on the WRITER connector, then complete the WRITER sign-in prompt. Turn the connector on in a conversation with the **+** button, then **Connectors**. > > On Team and Enterprise plans, members can't add the connector themselves. An owner adds it first, and each member connects their own WRITER account. Your client opens a browser so you can sign in. Choose one organization and approve the consent screen, and the connection is ready. Your playbooks, deliverables, meetings, and Enterprise Brain content all come from that organization. To switch organizations, connect again and choose the other one when you sign in. Access tokens last one hour and refresh automatically. Sign in again if your client prompts you, which can happen after a day. ## Try these prompts Ask for what you want in plain language and let the assistant choose the tools. Start with the first prompt to confirm the connection works. You should see a list of your organization's published playbooks. * "List the available WRITER playbooks, then show the inputs for the Board update playbook." * "Run the Board update playbook with the attached Q3 brief and report when it finishes." * "Download the deck from the most recent playbook run into this folder." * "Summarize the WRITER Meet calls about the Q3 launch from the last two weeks." * "Find the brand guidance that applies to a product launch email for Acme, then draft the email." * "Upload these three case studies to the Customer stories collection in the Content Library." ## Use playbooks Run your organization's published [playbooks](https://support.writer.com/articles/1496523599-get-started-with-playbooks) and download the files they produce. ### Run a playbook Start a run, follow it until it finishes, and answer it if it stops to ask you a question. Runs are asynchronous: `run_playbook` returns a `run_id` right away, and the assistant polls `get_run` until the run finishes. | Tool | What it does | | - | - | | `list_playbooks` | Lists the published playbooks you can open | | `get_playbook` | Returns a playbook's inputs and flags the ones a run needs | | `upload_file` | Uploads one file and returns a `file_id` for a file input | | `run_playbook` | Starts a run and returns a `run_id` | | `get_run` | Returns the run's status, including the prompt when it's `awaiting_user` | | `resume_run` | Answers a waiting run and continues it | | `get_run_output` | Returns the final text and the run's deliverables | | `cancel_run` | Cancels a run that's `queued` or `running` | | `list_runs` | Lists the runs you started through WRITER MCP | A typical run follows this sequence: 1. Get the playbook's inputs with `get_playbook`. 2. Upload a file for any input that expects one with `upload_file`. 3. Start the run with `run_playbook`, which returns a `run_id`. 4. Poll `get_run` until the run finishes. 5. If the run stops at `awaiting_user`, answer it with `resume_run`. The run waits until you answer. `resume_run` returns a new `run_id` for the continued run, so poll `get_run` with that ID. If `get_run` shows the run is waiting on connector setup, open its `thread_url` and finish the setup in WRITER instead, because `resume_run` can't answer it. 6. Get the final text and the run's deliverables with `get_run_output`. Run tools also return a `thread_url`. Open it to see the run in WRITER, signed in with an account that can access the thread. A run uses the team that owns the playbook, and you need access to that playbook. Only runs you started through WRITER MCP appear in `list_runs` and `get_run`. ### Download a deliverable A playbook can produce files, which WRITER calls deliverables. The assistant downloads them in chunks and reassembles the file for you. | Tool | What it does | | - | - | | `list_deliverables` | Lists the deliverables you own across runs | | `download_deliverable` | Downloads a file produced by a specific run | | `download_owned_deliverable` | Downloads a file you own, without a run | ## Use WRITER Meet Find your [WRITER Meet](https://support.writer.com/articles/2314203920-how-to-use-writer-meet) recordings and read their transcripts and summaries. The tools cover only the meetings you joined, never your whole organization. | Tool | What it does | | - | - | | `list_meetings` | Finds your recordings by text, attendee, or date range | | `get_meeting` | Returns one meeting's details, transcript, and summary | ## Use your Enterprise Brain Find, read, and add to your organization's Content Library, brand guidance, and compliance packs. The tools appear only when your organization has [Enterprise Brain](https://support.writer.com/collections/6248890235-enterprise_brain?lang=en) turned on, and they show only content you can already open in WRITER. ### Search and transfer Content Library files Search your organization's shared files, upload new ones, and download originals. Search returns names and summaries, so the assistant downloads a file when it needs the contents. | Tool | What it does | | - | - | | `search_library_assets` | Searches shared library files by keyword, or by meaning where your organization has semantic search set up | | `explore_library` | Lists the collections and sections you can upload to, with their IDs | | `upload_library_assets` | Uploads up to 8 files, 10 MiB in total, to a collection | | `get_library_asset_status` | Reports the outcome of an upload, for 24 hours after it starts | | `download_library_assets` | Downloads original files in chunks and reassembles them | Uploads never replace an existing file. If a file with the same name exists, the upload fails unless the assistant asks to keep both. The upload tool appears only if you can add files to at least one collection. The upload result says whether the file is stored, and search indexing and summaries can finish after that. ### Apply brand guidance Apply your brand guidelines and voices to a writing task, or browse the guidance each brand has. | Tool | What it does | | - | - | | `explore_brand_guidance` | Lists the brands you can access, or browses one brand's guidance files and voices | | `discover_brand_files` | Picks the brand guidance likely to apply to a writing or editing task you describe | | `search_brand_files` | Finds specific text in brand files by keyword | | `read_brand_files` | Reads the full text of brand files the assistant has already found | | `read_brand_voice` | Reads a complete voice, with its linked guidance and terms | Finding and searching guidance covers the brands in your team. Ask the assistant to cover your whole organization when you need brands from your other teams. Reading a voice doesn't select it or turn it on anywhere in WRITER. ### Check compliance guidance Check a task against the compliance packs turned on for your team. These tools appear only when your organization has compliance turned on. | Tool | What it does | | - | - | | `explore_compliance_guidance` | Browses the packs turned on for your team, by name or jurisdiction | | `discover_compliance_packs` | Suggests packs that might apply to a task you describe | | `search_compliance_packs` | Finds specific text in pack content by keyword | | `read_compliance_packs` | Reads selected packs in full | A suggestion or a search match means a pack might be relevant, not that it applies to your task. Suggestions match the channels a pack is tagged for and never infer a jurisdiction, so name the jurisdictions you need. Before relying on a pack, check the entities, products, audiences, industries, and jurisdictions it covers. ## Next steps * [Get started with playbooks](https://support.writer.com/articles/1496523599-get-started-with-playbooks): create the playbooks you run from an MCP client. * [Managing and sharing playbooks](https://support.writer.com/articles/8184764896-managing-and-sharing-playbooks): publish a playbook and share it with your team. * [How to use WRITER Meet](https://support.writer.com/articles/2314203920-how-to-use-writer-meet): record meetings and trigger playbooks from them. * [Enterprise Brain](https://support.writer.com/collections/6248890235-enterprise_brain?lang=en): learn more about Enterprise Brain and set up the Content Library, brands, and compliance packs your assistant uses. # AWS Bedrock Source: https://dev.writer.com/providers/aws-bedrock Add AI models from AWS Bedrock to use in Control Center agents This guide shows you how to configure AWS Bedrock as an external model provider in Control Center. After setting up this provider, you can use foundation models from AWS Bedrock when building agents. > [!NOTE] > > Control Center currently supports Bedrock models in `us-east-1`, `us-west-1`, > `us-west-2`, and `eu-west-1` regions only. See [Regional > considerations](#regional-considerations) for details. ## Prerequisites Before adding Bedrock models to Control Center, you need: * An [AWS account](https://aws.amazon.com/) with access to Amazon Bedrock * Credentials for one of the supported authentication methods (see [Configure AWS credentials](#configure-aws-credentials)) * Permission to invoke the models you want to use in your selected region > [!WARNING] > > Control Center supports **text generation** and **embedding** models from Bedrock. > Video, audio, and image generation models are not supported. ## Configure AWS credentials Control Center supports three authentication methods for AWS Bedrock. Choose the method that matches how your organization manages AWS access. > [tab] Bedrock API key > > Amazon Bedrock API keys authenticate requests with a bearer token. Generate a long-term key in the Amazon Bedrock console. > > 1. Sign in to the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/) > > 2. In the left navigation pane, select **API keys** > > 3. Open the **Long-term API keys** tab and select **Generate long-term API keys** > > 4. Choose an expiration period and optional advanced permissions > > 5. Select **Generate**, then copy the key and store it securely > > > [!WARNING] > > > > The API key is only shown once. Short-term API keys expire with your > > console session (up to 12 hours) and are a poor fit for Control Center. Use a > > long-term key for production credentials. > > After you generate the key, copy the value and either enter it when you [add a Bedrock model](#add-bedrock-models-in-control-center), or save it as a reusable credential set on the [LLM Credentials page](/home/external-models#create-credentials-from-the-llm-credentials-page). > [tab] AWS access keys > > Access keys authenticate Control Center with an IAM user. Create a dedicated IAM user for Control Center rather than using personal credentials. > > #### Create an IAM user > > 1. Sign in to the [AWS IAM Console](https://console.aws.amazon.com/iam/) > 2. Navigate to **Users** in the left sidebar > 3. Select **Create user** > 4. Enter a username (for example, `writer-aistudio-bedrock`) > 5. Select **Next** > 6. Choose **Attach policies directly** > 7. Attach a least-privilege Bedrock invoke policy for the models you configure. See [IAM policy example](#iam-policy-example) > 8. Select **Next**, then **Create user** > > #### Generate access keys > > 1. Select the user you created > > 2. Navigate to the **Security credentials** tab > > 3. Under **Access keys**, select **Create access key** > > 4. Choose **Third-party service** as the use case > > 5. Acknowledge the recommendation and select **Next** > > 6. Add an optional description tag (for example, `Control Center Bedrock integration`) > > 7. Select **Create access key** > > 8. Copy the **Access key ID** and **Secret access key** > > > [!WARNING] > > > > The secret access key is only shown once. Copy it immediately and store it > > securely. If you lose the secret key, you must create new access keys. > > After you generate the access keys, copy the values and either enter them when you [add a Bedrock model](#add-bedrock-models-in-control-center), or save them as a reusable credential set on the [LLM Credentials page](/home/external-models#create-credentials-from-the-llm-credentials-page). > > #### IAM policy example > > Scope the policy to the foundation model or inference profile ARNs you use. Replace the region, account ID, and model IDs with your values. For streaming, add `bedrock:InvokeModelWithResponseStream` to the `Action` array. > > ```json theme={null} > { > "Version": "2012-10-17", > "Statement": [ > { > "Effect": "Allow", > "Action": ["bedrock:InvokeModel"], > "Resource": [ > "arn:aws:bedrock:us-west-2::foundation-model/anthropic.claude-opus-5", > "arn:aws:bedrock:us-west-2:123456789012:inference-profile/us.anthropic.claude-opus-5" > ] > } > ] > } > ``` > [tab] AWS assume role > > Use AWS assume role for cross-account access or when your organization requires role-based access. Both sides of the assume-role relationship must allow the call: the role trust policy and the source identity policy. See [Grant a user permissions to switch roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_permissions-to-switch.html) in the AWS documentation. > > #### Create an IAM role > > 1. Sign in to the [AWS IAM Console](https://console.aws.amazon.com/iam/) > 2. Navigate to **Roles** in the left sidebar > 3. Select **Create role** > 4. Configure the role trust policy so the source IAM user or account is allowed as a principal for `sts:AssumeRole` > 5. Attach a least-privilege Bedrock invoke policy for the models you configure. See [IAM policy example](#iam-policy-example-for-assume-role) > 6. Create the role and copy the **Role ARN** > 7. If the role requires an external ID for cross-account access, note the **External ID** > > #### Create source credentials > > 1. Create or select an IAM user that provides the access keys to Control Center > > 2. Attach an identity policy to that user that allows `sts:AssumeRole` on the target role ARN. Creating the user alone is not enough—without this permission, assume-role calls fail > > 3. Navigate to the **Security credentials** tab for that user > > 4. Under **Access keys**, select **Create access key** > > 5. Choose **Third-party service** as the use case > > 6. Acknowledge the recommendation and select **Next** > > 7. Add an optional description tag (for example, `Control Center Bedrock assume role`) > > 8. Select **Create access key** > > 9. Copy the **Access key ID** and **Secret access key** > > > [!WARNING] > > > > The secret access key is only shown once. Copy it immediately and store it > > securely. If you lose the secret key, you must create new access keys. > > After you generate the access keys, copy the values (and the **Role ARN**) and either enter them when you [add a Bedrock model](#add-bedrock-models-in-control-center), or save them as a reusable credential set on the [LLM Credentials page](/home/external-models#create-credentials-from-the-llm-credentials-page). > > #### IAM policy example for assume role > > Attach this policy to the role you assume (not only to the source user). Scope it to the foundation model or inference profile ARNs you use. Replace the region, account ID, and model IDs with your values. For streaming, add `bedrock:InvokeModelWithResponseStream` to the `Action` array. > > ```json theme={null} > { > "Version": "2012-10-17", > "Statement": [ > { > "Effect": "Allow", > "Action": ["bedrock:InvokeModel"], > "Resource": [ > "arn:aws:bedrock:us-west-2::foundation-model/anthropic.claude-opus-5", > "arn:aws:bedrock:us-west-2:123456789012:inference-profile/us.anthropic.claude-opus-5" > ] > } > ] > } > ``` ## Add Bedrock models in Control Center After configuring your AWS credentials, add Bedrock models to Control Center. 1. Navigate to **Build > Models** in [Control Center](https://app.writer.com/controlcenter) 2. Under **Bring your own model**, select **+ Add model** 3. Select **Amazon Bedrock** as the provider, then select **Next** 4. Select the model from the **Model name** dropdown 5. Enter a unique **Display name** for the model 6. Provide credentials using one of the following options (not both): * Select an existing credential set from the **Credentials name** dropdown * Enter a new **Credential name** and the authentication fields for your chosen method, using the values from [Configure AWS credentials](#configure-aws-credentials) 7. Configure team access: * **All teams**: Anyone with builder access can use the model * **Specific teams**: Restrict to selected teams 8. Select **Save** > [!WARNING] > > Use either an existing credential set or new credential fields. Filling both > sides of the credentials section can prevent the form from saving. > [!TIP] > > If the model you need does not appear in the **Model name** dropdown, contact > Writer support. Use a unique display name so the model does not collide with a > WRITER-managed catalog entry in WRITER Agent. ## Regional considerations Control Center supports Bedrock models in the following AWS regions: * **US East** (`us-east-1`) * **US West** (`us-west-1`) * **US West 2** (`us-west-2`) * **EU West** (`eu-west-1`) > [!NOTE] > > Support for additional AWS regions is coming soon. When configuring Bedrock in Control Center: * Select a supported region where your credentials can invoke the model * Ensure your credentials have permissions in the same region you select * Some Bedrock models are only available in specific regions—check the [Amazon Bedrock regional availability](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-regions.html) documentation > [!WARNING] > > Ensure the region you select in Control Center matches the region where your > credentials can invoke the model. ## Monitor costs AWS bills Bedrock usage directly to your AWS account based on the tokens processed. WRITER also charges a [10% pass-through fee](/home/pricing#external-models-byom) on external model usage, paid via credits. Control Center tracks usage and costs for external models, providing visibility into spending across all your models in one place. ## Troubleshoot Bedrock configuration ### Invalid credentials error If you see an "Invalid credentials" or "Authentication failed" error: * Verify credentials are copied correctly without extra spaces * For Bedrock API keys, confirm the key is still active and has not expired * For access keys, check that the keys are still active in the IAM console * For assume role, verify the **Role ARN**, **External ID** (if required), that the role trust policy allows the source principal, and that the source user's identity policy allows `sts:AssumeRole` on the target role ARN * Ensure the credentials allow `bedrock:InvokeModel` on the model or inference profile ARNs you configured * For streaming failures, confirm the policy also allows `bedrock:InvokeModelWithResponseStream` ### Model not available error If a model doesn't appear or returns an error: * Confirm the model appears in the Bedrock **Model catalog** for your region * For Anthropic models, confirm you completed the first-time use form if prompted * Verify you selected the correct region in Control Center * Check that your credentials allow access to the specific model or inference profile ARNs in your IAM policy ### Duplicate model in WRITER Agent If the model dropdown shows a confusing duplicate: * Check whether the same model is already enabled as a WRITER-managed catalog model on the Models page * Use a distinct **Display name** for the BYOM entry, or delete the extra BYOM model if you intended to use the WRITER-managed version ### Form will not save If the Add model form does not save: * Clear either the **Credentials name** dropdown or the new credential fields so only one path is filled * Confirm all required fields for the selected authentication method are complete ## Next steps * [Add external models](/home/external-models): Learn about managing external models in Control Center * [Choose a model](/home/models-overview): Compare Palmyra models with external provider models * [Amazon Bedrock documentation](https://docs.aws.amazon.com/bedrock/): Explore Bedrock's full capabilities # Microsoft Azure Source: https://dev.writer.com/providers/microsoft-azure Add AI models from Microsoft Azure to use in Control Center agents This guide shows you how to configure Microsoft Azure as an external model provider in Control Center. After setting up this provider, you can use Azure OpenAI models or Foundry Models when building agents. > [!WARNING] > > **Deprecation notice**: Microsoft Azure is deprecated as an external model > provider in Control Center. > > **Migration path**: Migrate your existing Azure models to [AWS > Bedrock](/providers/aws-bedrock) or [OpenRouter](/providers/openrouter). Add > your models on the new provider, update any agents that reference the Azure > models, then remove the Azure models from Control Center. > > If you already use Azure external models through the API or SDK, you can > continue to call them with your existing credentials and model IDs until an > alternate path is announced. Find your model IDs on the [Models > page](https://app.writer.com/controlcenter) in Control Center. ## Prerequisites Before adding Microsoft Azure models to Control Center, you need: * An [Azure subscription](https://azure.microsoft.com/pricing/purchase-options/azure-account?cid=msft_learn) with access to Azure OpenAI or Foundry Models * At least one deployed model on your Azure resource (see [setup options](#choose-a-setup-path) below) * The resource endpoint and API key for the deployment you plan to use > [!WARNING] > > Control Center supports **text generation** and **embedding** models from Microsoft > Azure. Video, audio, and image generation models are not supported. > [!NOTE] > > Control Center currently supports the following Azure models, with more coming soon: > > * `gpt-4.1` > * `gpt-4o` > * `gpt-5` > * `mistral-large-3` > > To request a model, reach out to your account manager or [support](mailto:support@writer.com). ## Choose a setup path Choose one of the following setup paths depending on how you deploy models in Azure: * **[Azure OpenAI](#option-1-azure-openai)**: Create an Azure OpenAI resource and deploy models through the Azure portal * **[Foundry Models](#option-2-foundry-models)**: Deploy models through the Foundry portal ## Option 1: Azure OpenAI ### Create a resource Create an Azure OpenAI resource in the Azure portal before deploying models. 1. Sign in to the [Azure portal](https://portal.azure.com) 2. Select **Create a resource** and search for **Azure OpenAI** 3. Select **Create** 4. On the **Basics** tab, provide the following: | Field | Description | | - | - | | **Subscription** | The Azure subscription to use for your Azure OpenAI resource | | **Resource group** | The resource group to contain your Azure OpenAI resource. Create a new group or use an existing one | | **Region** | The location for your resource. Different regions may introduce latency | | **Name** | A descriptive name for the resource, such as `writer-aistudio-openai` | 5. Select **Next** 6. On the **Network** tab, select **All networks, including the internet, can access this resource** (required for Control Center to reach the endpoint) 7. Select **Next** to open the **Tags** tab. Add [tags](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/tag-resources) if your organization requires them 8. Select **Next** to reach **Review + submit** 9. Confirm your settings and select **Create** For more details, see [Create and deploy an Azure OpenAI resource](https://learn.microsoft.com/en-us/azure/foundry-classic/openai/how-to/create-resource?pivots=web-portal) on Microsoft Learn. ### Deploy a model Before you can use a model in Control Center, you need to deploy it on your Azure OpenAI resource. 1. Sign in to [Microsoft Foundry](https://ai.azure.com) 2. Navigate to the Azure OpenAI resource you [created earlier](#create-a-resource) 3. Select **Deployments** from the left pane 4. Select **+ Deploy model** > **Deploy base model** 5. Select the model you want to deploy and select **Confirm** 6. Set the **Deployment name**, which is the name you use in API calls and the value Control Center maps to your model 7. Select **Deploy** 8. Wait until the **Provisioning** state changes to **Succeeded** For more details on deploying models on Azure OpenAI resources, see [Deploy a model](https://learn.microsoft.com/en-us/azure/foundry-classic/openai/how-to/create-resource?pivots=web-portal). ## Option 2: Foundry Models ### Create a Foundry project Foundry Models are deployed within a Foundry project. Create one if you don't already have a project. 1. Sign in to [Microsoft Foundry](https://ai.azure.com). Ensure the **New Foundry** toggle is **on** 2. Select **+ New project** from the top navigation 3. Enter a **Project name** 4. Expand **Advanced options** to configure: | Field | Description | | - | - | | **Foundry resource** | The Foundry resource that manages this project | | **Region** | The Azure region for the project (for example, **East US 2**) | | **Subscription** | The Azure subscription to bill against | | **Resource group** | The resource group to contain the project resources. Select an existing group or create a new one | 5. Select **Create** For more details on creating Foundry projects, see [Create a Foundry project](https://learn.microsoft.com/en-us/azure/foundry/how-to/create-projects?tabs=foundry). ### Deploy a model 1. From the Foundry portal homepage, select **Discover** in the upper navigation, then **Models** in the left pane 2. Select a model and review its details 3. Select **Deploy** > **Custom settings** to configure the deployment (or **Default settings** for quick setup) 4. For partner and community models, read the terms of use and select **Agree and Proceed** to subscribe through Azure Marketplace 5. Set the **Deployment name**, which is used in API calls and the value Control Center maps to your model 6. Select **Deploy** 7. Wait until the deployment status shows **Succeeded** For more details, see [Deploy Foundry Models](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/how-to/deploy-foundry-models) on Microsoft Learn. ## Retrieve the target URI and API key After deploying a model through either setup path, navigate to the deployment to copy your credentials. 1. In the Foundry portal, navigate to the model you deployed 2. Copy the **Target URI** and **API Key** from the deployment details to [use in Control Center](#add-microsoft-azure-models-in-control-center) > [!WARNING] > > Store your API key securely. If a key is compromised, rotate it from the > deployment detail page or the Azure portal. ## Add Microsoft Azure models in Control Center After deploying a model and copying your endpoint and key from either setup path: 1. Navigate to **Build > Models** in [Control Center](https://app.writer.com/controlcenter) 2. Select **+ Add model** 3. Select **Microsoft Azure** as the provider 4. Select your model from the **Model** dropdown 5. Enter your credentials: * **API Base**: The Target URI from your deployment (for example, `https://your-resource.openai.azure.com/`) * **API Version**: The API version to use (for example, `2023-07-01-preview`) * **Azure API Key**: The API key from your deployment 6. Configure team access: * **All teams**: Anyone with builder access can use the model * **Specific teams**: Restrict to selected teams 7. Select **Save** ![](https://mintcdn.com/writer/_0ZlAMCIDfuJgqjY/images/home/azure-openai-config-form.png?fit=max\&auto=format\&n=_0ZlAMCIDfuJgqjY\&q=85\&s=deea2e438a828c77bbf22693170cd999) ## Monitor costs Azure bills usage directly to your Azure subscription based on tokens processed and deployment configuration. WRITER also charges a [10% pass-through fee](/home/pricing#external-models-byom) on external model usage, paid via credits. Control Center tracks usage and costs for external models, providing visibility into spending across all your models in one place. ## Troubleshoot Microsoft Azure configuration ### Invalid credentials error If you see an "Invalid credentials" or "Authentication failed" error: * Verify the API key is copied correctly without extra spaces * Check that the key is still active in the Azure portal * Ensure the key belongs to the same resource as the API Base URL ### Model not available error If a model doesn't appear or returns an error: * Confirm the model deployment shows **Succeeded** in the Azure portal or Foundry portal * Verify the deployment name matches the model selected in Control Center * Check that the API version is supported for your deployment ### Connection failed error If Control Center cannot connect to your Azure resource: * Confirm the API Base URL uses `https://` and matches the endpoint in your portal * Verify the resource network settings allow public access * Check [Azure service health](https://azure.status.microsoft/) for regional incidents ## Next steps * [Add external models](/home/external-models): Learn about managing external models in Control Center * [Choose a model](/home/models-overview): Compare Palmyra models with external provider models * [Configure guardrails](/home/guardrails): Set up content safety and compliance policies for your AI agents * [Deploy Foundry Models (Microsoft Learn)](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/how-to/deploy-foundry-models): Full Foundry Models deployment walkthrough # NVIDIA NIM Source: https://dev.writer.com/providers/nvidia-nim Add AI models from NVIDIA NIM to use in Control Center agents This guide shows you how to configure NVIDIA NIM as an external model provider in Control Center. After setting up this provider, you can use foundation models from NVIDIA's API Catalog or your own self-hosted NIM deployments when building agents. > [!NOTE] > > NVIDIA NIM supports both cloud-hosted models via the [NVIDIA API > Catalog](https://build.nvidia.com/models) and self-hosted deployments via > [NVIDIA Inference > Microservices](https://docs.api.nvidia.com/nim/docs/introduction). See > [Deployment options](#deployment-options) for details on each approach. ## Prerequisites Before adding NVIDIA NIM models to Control Center, you need: * An [NVIDIA Developer account](https://build.nvidia.com) with access to the API Catalog * An NGC API key for authentication (see [Generate an NGC API key](#generate-an-ngc-api-key)) * For self-hosted deployments: A running NIM instance with a reachable endpoint (see [Configure self-hosted endpoints](#configure-self-hosted-endpoints)) > [!WARNING] > > Control Center supports **text generation** and **embedding** models from NVIDIA > NIM. Video, audio, and image generation models are not supported. ## Generate an NGC API key Generate an API key from the NGC console to authenticate with NVIDIA NIM. 1. Navigate to the [NGC API Key page](https://org.ngc.nvidia.com/setup/api-keys) 2. Select **Generate API Key** 3. Enter a description for your key (for example, `Control Center integration`) 4. Under **Key Permissions**, ensure **NGC Catalog** access is included in the **Services Included** list 5. Select **Generate** 6. Copy the API key immediately > [!WARNING] > > The API key is only shown once. Copy it immediately and store it securely. If > you lose the key, you must generate a new one. ## Deployment options NVIDIA NIM offers two deployment approaches. Choose the one that matches your infrastructure requirements. ### Cloud-hosted (NVIDIA API Catalog) Use NVIDIA's cloud-hosted models through the API Catalog for quick setup. This approach: * Requires no infrastructure management * Uses NVIDIA's hosted API endpoint (`https://integrate.api.nvidia.com/v1`) * Provides access to NVIDIA-hosted and partner models available through the API Catalog * Bills usage through your NVIDIA account ### Self-hosted (NVIDIA Inference Microservices) Deploy NIM containers in your own infrastructure for greater control. This approach: * Runs models on your own GPU or cloud instances * Requires a custom API Base URL pointing to your NIM deployment * Provides greater control over where inference runs and how infrastructure is managed * Supports air-gapped or private network deployments > [!NOTE] > > For self-hosted deployments, Control Center must be able to send outbound HTTPS > requests to your NIM endpoint. You may need to configure network rules or use > a public endpoint. ## Add NVIDIA NIM models in Control Center After generating your API key, add NVIDIA NIM models to Control Center. > [!NOTE] > > For self-hosted deployments, configure your NIM instance and note its API Base > URL before proceeding. See [Configure self-hosted > endpoints](#configure-self-hosted-endpoints) for details. 1. Navigate to **Build > Models** in [Control Center](https://app.writer.com/controlcenter) 2. Select **+ Add model** 3. Select **NVIDIA NIM** as the provider 4. Enter your NGC API key 5. Configure the endpoint: * For cloud-hosted models: Leave the API Base URL empty to use the default NVIDIA endpoint * For self-hosted models: Enter your custom API Base URL (for example, `https://your-nim-instance.example.com/v1`) 6. Select the models you want to add from the available list 7. Configure team access: * **All teams**: Anyone with builder access can use the model * **Specific teams**: Restrict to selected teams 8. Select **Add model** ![](https://mintcdn.com/writer/7idqHjGQp6qGXVE0/images/home/nvidia-config-form.png?fit=max\&auto=format\&n=7idqHjGQp6qGXVE0\&q=85\&s=475e393129b260d5edf9e866b4e65660) ## Configure self-hosted endpoints When using self-hosted NIM deployments, provide the base URL where your NIM instance is running. For detailed setup instructions, including hardware requirements and deployment options, see [Get started with NVIDIA NIM for LLMs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html). ### API Base URL format The API Base URL should point to your NIM deployment's API endpoint: ``` https://your-nim-host:port/v1 ``` Replace `your-nim-host` and `port` with your actual NIM instance address. ### Verify your endpoint Before adding to Control Center, verify your NIM endpoint is accessible: ```bash theme={null} curl https://your-nim-instance.example.com/v1/models \ -H "Authorization: Bearer YOUR_API_KEY" ``` A successful response returns a list of available models on your NIM instance. For more information on available endpoints, see the [NVIDIA NIM API reference](https://docs.nvidia.com/nim/large-language-models/latest/api-reference.html). ## Monitor costs For cloud-hosted models, NVIDIA bills usage directly to your NVIDIA account based on the tokens processed. WRITER also charges a 10% pass-through fee on external model usage, paid via credits. Control Center tracks usage and costs for external models, providing visibility into spending across all your models in one place. For self-hosted deployments, costs depend on your infrastructure (compute instances, resources). ## Troubleshoot NVIDIA NIM configuration ### Invalid API key error If you see an "Invalid API key" or "Authentication failed" error: * Verify the API key is copied correctly without extra spaces * Check that the API key is still active in the NGC console * Ensure you're using an NGC API key, not a different NVIDIA credential type ### Model not available error If a model doesn't appear or returns an error: * For cloud-hosted: Confirm the model is available in the NVIDIA API Catalog * For self-hosted: Verify your NIM instance has the model deployed * Check that your API key has access to the specific model ### Connection failed error If Control Center cannot connect to your NIM endpoint: * Verify the API Base URL is correct and includes the protocol (`https://`) * Check that your NIM instance is running and accessible * Ensure network rules allow traffic from Control Center's infrastructure * For self-hosted deployments, verify SSL certificates are valid ## Next steps * [Add external models](/home/external-models): Learn about managing external models in Control Center * [Choose a model](/home/models-overview): Compare Palmyra models with external provider models * [NVIDIA NIM documentation](https://docs.nvidia.com/nim/): Explore NIM capabilities # OpenRouter Source: https://dev.writer.com/providers/openrouter Add AI models from OpenRouter to use in Control Center agents This guide shows you how to configure OpenRouter as an external model provider in Control Center. After setting up this provider, you can use models from OpenRouter's unified catalog when building agents. ## Prerequisites Before adding OpenRouter models to Control Center, you need: * An [OpenRouter account](https://openrouter.ai/) * An OpenRouter API key (starts with `sk-or-...`, see [Get an OpenRouter API key](#get-an-openrouter-api-key)) > [!WARNING] > > Control Center supports **text generation** and **embedding** models from > OpenRouter. Video, audio, and image generation models are not supported. ## Get an OpenRouter API key OpenRouter authenticates requests with a single API key that works across its model catalog. Create one from your OpenRouter account. 1. Sign up or log in at [OpenRouter](https://openrouter.ai/) 2. Navigate to the [API Keys](https://openrouter.ai/keys) page 3. Select **Create Key** 4. Enter a name for the key (for example, `Control Center integration`) 5. Copy the key, which starts with `sk-or-...` For more details, see the [OpenRouter quickstart](https://openrouter.ai/docs/quickstart). > [!WARNING] > > Store your API key securely. If a key is compromised, revoke it from the > [API Keys](https://openrouter.ai/keys) page and create a new one. ## Add OpenRouter models in Control Center After creating your API key, add OpenRouter models to Control Center. 1. Navigate to **Build > Models** in [Control Center](https://app.writer.com/controlcenter) 2. Select **+ Add model** 3. Select **OpenRouter** as the provider 4. Select the model you want to add from the **Model name** dropdown 5. Enter a **Display name** for the model 6. Provide your credentials using one of the following options: * Select an existing credential set from the **Credentials name** dropdown * Enter a new **Credential name** and your **OpenRouter API key** to save credentials for reuse 7. Configure team access: * **All teams**: Anyone with builder access can use the model * **Specific teams**: Restrict to selected teams 8. Select **Save** ![](https://mintcdn.com/writer/iljD9sjySSSg4wwQ/images/home/openrouter-config-form.png?fit=max\&auto=format\&n=iljD9sjySSSg4wwQ\&q=85\&s=f4031eb6a29e54e57eaefd1db79c2a13) ## Monitor costs OpenRouter bills usage directly to your OpenRouter account based on the tokens processed by each model. WRITER also charges a [10% pass-through fee](/home/pricing#external-models-byom) on external model usage, paid via credits. Control Center tracks usage and costs for external models, providing visibility into spending across all your models in one place. ## Troubleshoot OpenRouter configuration ### Invalid API key error If you see an "Invalid API key" or "Authentication failed" error: * Verify the API key is copied correctly without extra spaces * Confirm the key starts with `sk-or-...` * Check that the key is still active on the [API Keys](https://openrouter.ai/keys) page * Ensure your OpenRouter account has sufficient credits ### Model not available error If a model doesn't appear or returns an error: * Confirm the model is available in the [OpenRouter model catalog](https://openrouter.ai/models) * Verify your OpenRouter account has access to the model * Check that your account has credits to run the model ## Next steps * [Add external models](/home/external-models): Learn about managing external models in Control Center * [Choose a model](/home/models-overview): Compare Palmyra models with external provider models * [OpenRouter quickstart](https://openrouter.ai/docs/quickstart): Explore OpenRouter's full capabilities