This tutorial shows you how to use the Zendesk Help Center API in combination with the OpenAI Responses API to edit any article in your help center to improve its clarity and readability.

Understanding the application workflow

Here's the workflow the application follows to edit a help center article with an AI model.

  1. Ask the user to specify the ID of a help center article they want to edit with the AI.
  2. Make a request to the Show Article endpoint in the Help Center API to retrieve the article’s title and body.
  3. In addition to the article itself, gather any instructions you want the AI to use to edit the article. In the tutorial, you have instructions for editing articles as well as a style guide to follow.
  4. Send the input and instructions to the Create a model response in the OpenAI Responses API. The AI model processes this input and returns an edited version of the article.
  5. Create a diff of the source article and the AI-edited article to help the user quickly see what changed.
  6. Save the results locally.

The user can review, approve, or further update the edited article before updating it in the help center.

Building the AI application

This section shows you how to build a simple console application that uses an AI model to improve the clarity and readability of a specified help center article while preserving its original meaning and structure.

What you need

To complete this tutorial, you'll need the following:

  • an OpenAI API key
  • a Zendesk API token, if applicable
  • a recent Python runtime installed on your system

Getting an OpenAI API key

To get an OpenAI API key

  1. If you don't already have an OpenAI account, register for a free personal account at https://auth.openai.com/log-in-or-create-account.
  2. To create an OpenAI API key after creating an account, go to the API keys section in your OpenAI platform dashboard at https://platform.openai.com/api-keys.

Getting a Zendesk API token

You don't need a Zendesk API token if the help center doesn't require users to sign in to view the articles. If the help center requires users to sign in, you'll need an API token.

To create an API token, you need admin access or somebody who has admin access.

To create a Zendesk API token

  1. In Admin Center, click Apps and integrations in the sidebar, then select APIs > API tokens.
  2. Click Add API token.
  3. (Optional) Enter a Description for the token.
  4. Click Save to generate the token.

Getting the Python runtime

You should use Python 3.9 or greater for this tutorial.

To get the Python runtime

  1. Download and install the latest version of Python from the Python downloads page.
  2. Open Terminal and install the following additional libraries with the pip command:
    • requests, a user-friendly library for making web requests
    • markdownify, a library for converting HTML to Markdown
    • mistune, a library for converting Markdown to HTML
    • python-dotenv, a library designed to make working with environment variables simpler

Setting your environment variables

At runtime the application will need to access certain sensitive values such as your OpenAI API key. You can store these values in environment variables on your system.

You can use the python-dotenv library to set environment variables automatically each time the app starts. The library reads the variables from a file named .env in your project.

To set the environment variables

  1. In your project folder, create a text file named .env (with a leading period).

  2. Use a text editor to paste the environment variables into the file:

    OPENAI_API_KEY=your_openai_api_keyZENDESK_SUBDOMAIN=your_subdomainZENDESK_EMAIL=your_email@example.comZENDESK_API_TOKEN=your_api_token

    Note the following:

    • The values don't use quotes.
    • If your Zendesk URL is "https://mondocam.zendesk.com", then the string "mondocam" is your Zendesk subdomain.
    • If the help center doesn't require users to sign in to view the articles, you can leave the values of ZENDESK_EMAIL and ZENDESK_API_TOKEN blank.
  3. Save the updated .env file in your project folder.

  4. If you're using GitHub for this project, add .env to your .gitignore file to protect sensitive data.

Writing the script

In your project folder, create a file named edit_article.py and paste the following Python script into it. The comments in the script explain what each function does at runtime.

import osimport difflibimport textwrap
from markdownify import markdownifyimport mistuneimport requests
# load environment variables from the .env filefrom dotenv import load_dotenvload_dotenv()

def prompt_for_article_id() -> str:    """    Asks the user for the article they want to edit with the AI model.    """    article_id = input(        "Enter the id of the article to review and press Enter: "    ).strip()    if not article_id.isdigit() or article_id is None:        print("Error: Invalid article ID. Rerun the script to try again.")        exit()    return article_id

def get_article(article_id) -> str:    """    Returns the title and body of the specified help center article    as Markdown text.    """    subdomain = os.environ["ZENDESK_SUBDOMAIN"]    auth = (        f"{os.environ["ZENDESK_EMAIL"]}/token",        os.environ["ZENDESK_API_TOKEN"]    )    response = requests.get(        f"https://{subdomain}.zendesk.com/api/v2/help_center/articles/{article_id}",        auth=auth    )    if response.status_code != 200:        raise requests.HTTPError(f"{response.reason} - {response.text}")    data = response.json()
    # convert the HTML article to Markdown format    article_markdown: str = markdownify(data['article']['body'], heading_style="ATX")    article_markdown = f"# {data['article']['title']}\n\n{article_markdown}"    return article_markdown

def get_model_dependencies(source_article) -> dict:    """    Gets the model input and instructions.    """    system_prompt = 'You are a technical editor assigned to edit a help center article.\n'
    prompt = textwrap.dedent("""\        Edit the article that follows to improve clarity and readability.        Here\'s the full text of the article:
    """)
    editorial_guidelines = textwrap.dedent("""\        ## Editorial guidelines
        - Do not omit, combine, or significantly rewrite any information in the article.        - Preserve all original introductory text, headings, steps, and instructions.        - Only make light edits to fix grammar or punctuation, and to make explanations easier to follow.        - Keep the order and structure of the original content.
    """)
    style_guide = textwrap.dedent("""\        ## Style guide
        - Use a conversational tone.        - Avoid technical jargon.        - Capitalize only the first word of headings or titles.
    """)
    return {        'model_input': system_prompt + prompt + source_article,        'instructions': editorial_guidelines + style_guide    }

def edit_article_with_ai_model(dependencies) -> str:    """    Takes the model input and instructions and returns the    AI-edited article.    """    response = requests.post(        url='https://api.openai.com/v1/responses',        headers={            'Authorization': f'Bearer {os.environ["OPENAI_API_KEY"]}',            'Content-Type': 'application/json'        },        json={            'model': 'gpt-4o',            'temperature': 0.2,            'instructions': dependencies['instructions'],            'input': dependencies['model_input']        }    )    if response.status_code != 200:        raise requests.HTTPError(f"{response.reason} - {response.text}")    data = response.json()    return data['output'][0]['content'][0]['text']

def get_diff(source_article, edited_article) -> str:    """    Creates a diff of the source article and the edited article.    """    diff_lines = list(difflib.unified_diff(        source_article.splitlines(),        edited_article.splitlines(),        fromfile='source article',        tofile='edited article',        lineterm=''    ))    return '\n'.join(diff_lines)

def write_results(edited_article, article_diff, article_id) -> None:    """     Writes two files:     - An HTML version of the edited article     - A Markdown version of the article diff with diff highlighting    """    edited_article_html = mistune.html(edited_article)  # converts Markdown to HTML    file_name = f"{article_id}_edited.html"    with open(file_name, "w") as f:        f.write(edited_article_html)        print(f"Edited article saved to {file_name}")
    article_diff = f"```diff\n\n{article_diff}\n```"    # adds Markdown diff highlighting    file_name = f"{article_id}_diff.md"    with open(file_name, "w") as f:        f.write(article_diff)        print(f"Article diff saved to {file_name}")

def main():    """    Runs the workflow for editing an article with the AI model.    """    article_id = prompt_for_article_id()    source_article = get_article(article_id)    model_dependencies = get_model_dependencies(source_article)    edited_article = edit_article_with_ai_model(model_dependencies)    article_diff = get_diff(source_article, edited_article)    write_results(edited_article, article_diff, article_id)    print("Done.")

if __name__ == "__main__":    main()

Using the script to edit an article

To edit an article with script

  1. Navigate to your project folder with your command line interface and run:

    python3 edit_article.py

    If you're working in a virtual environment, you can run python edit_article.py.

  2. Enter the ID of the article when prompted and press Enter.

    If you encounter HTTP errors or failures, verify network connectivity and that your keys are valid.

The script:

  • Retrieves the specified article from Zendesk
  • Converts the article HTML content to Markdown
  • Sends the content to the AI model with instructions to improve clarity and readability
  • Receives the AI-edited version of the article
  • Generates a diff highlighting edits compared to the original

The script saves the following two files in the current folder, named with the article ID:

  • <article_id>_edited.html: The AI-edited article in HTML format, ready for review and publishing.
  • <article_id>_diff.md: A Markdown file showing a line-by-line diff of changes with syntax highlighting for easy comparison.

Review the diff file before publishing the changes to your help center.

Understanding the diff file

You can view the diff file in any text editor. However, it's best viewed in a Markdown editor that supports Markdown diff highlighting. One editor that supports diff highlighting is Visual Studio Code.

In the diff file, expressions between double-@ characters, such as @@ -10,7 +11,7 @@, are called chunk headers. They specify the line number where the diff occurs in the source and destination files and how many lines are affected.

For example, @@ -10,7 +11,7 @@ means that changes, additions, or deletions occur near line 10 in the original and line 11 in the new file. The chunk in both files covers 7 lines.

Next steps

Congratulations on building a working AI application! Here are some possible next steps:

  • Change or expand the model input and instructions to suit your own requirements.
  • Move the input and instructions to Markdown files or to a database and then import them into the script. This lets you edit and fine-tune the input and instructions without editing the script.
  • Establish a process for reviewing, approving, or further updating the edited article before publishing it to the help center.
  • Automate further by using the Update Article endpoint in the Help Center API to update the original article with the updated version.