Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • AI
Labs

Token Management and Cost Optimization with OpenAI

An AI feature can produce useful answers while consuming more tokens and budget than the task requires. In this Code Lab, you’ll optimise a Python support-ticket application that uses OpenAI models to classify requests and draft responses. You’ll measure token usage, estimate request costs, tighten prompts, and control response length. You’ll then route tasks to suitable models, adjust reasoning effort, structure prompts for caching, and identify workloads suitable for batch processing. Finally, you’ll compare your changes against a supplied evaluation dataset to check that cost reductions preserve essential information and correct decisions. When you finish, you’ll have a repeatable approach to choosing an appropriate balance of cost, speed, and quality for an OpenAI-powered application.

Lab platform
Lab Info
Level
Intermediate
Last updated
Dec 03, 2026
Duration
1h 20m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. Challenge

    Introduction

    Building an AI application that produces useful answers is only part of the job. As usage grows, long prompts, unnecessarily detailed responses, and expensive model choices can increase operating costs. Before changing these settings, you need a reliable way to measure what the application consumes and check that any savings preserve the quality of its answers.

    What You’ll Learn

    In this lab, you’ll learn how to:

    • Measure input, output, cached input, and reasoning token usage and estimate request costs
    • Tighten prompts and control response length while preserving essential information
    • Decide when to split a complex request into smaller steps
    • Select models and reasoning settings that suit the difficulty of a task
    • Structure repeated prompts for caching and identify workloads suitable for batch processing
    • Compare cost, response time, and task quality before accepting an optimization

    Scenario

    You’ve inherited a working support-ticket application at Globomantics. It reads customer requests, applies an internal support policy, and drafts replies for a human support agent. It handles account access, billing, and technical issues.

    Right now:

    • The application uses a verbose prompt and the same flagship model for every ticket
    • The API returns usage information, but the application does not yet turn it into a useful cost report
    • There is no saved baseline for comparing later changes
    • The team has not yet established whether cheaper configurations preserve correct decisions

    Your task is to make the application’s token usage and costs visible, then improve its efficiency while preserving the required behaviour.

    What You’ll Build

    By the end of the lab, you will have a Python application that:

    1. Records token usage, estimated cost, and elapsed time for model requests
    2. Uses concise prompts and appropriate output limits
    3. Routes different tasks to suitable models and reasoning settings
    4. Supports repeated-prefix caching and identifies suitable batch workloads
    5. Compares optimizations against expected decisions and a response-quality rubric

    The result is still a small support application, but its cost and quality trade-offs will be measurable.

    The Application

    The lab uses Python and the official OpenAI Python SDK. Source files are located in src, and tests are located in tests, both inside the workspace directory.

    The application’s entry point is src/__main__.py. Run commands from the project root, /home/ps-user/workspace.

    The project contains the following files:

    • src/app.py -- Runs the application and writes the baseline report.
    • src/providers.py -- Builds API requests, calls OpenAI, and measures elapsed request time.
    • src/models.py -- Defines the token-usage and pricing objects.
    • src/metrics.py -- Contains the two functions you will complete in the first coding step.
    • src/experiments.py -- Contains the supplied experiments for comparing workflows, routing requests, exploring caching and batch processing, and evaluating quality.
    • src/prompts/baseline.md -- The initial prompt that later tasks will optimize.
    • src/prompts/support_policy.md -- The rules used to decide how tickets should be handled.
    • src/data/tickets.json -- Three synthetic customer support tickets used as inputs.
    • src/data/pricing.json -- Dated model prices used to estimate cost.
    • src/data/expected_decisions.json -- Expected classifications and escalation decisions for later quality comparisons.
    • lab_config.json -- Stores the lab-provided API credential used by the application.
    • tests/ -- pytest checks for the supplied application and your implementation.

    The baseline, workflow, routing, caching and evaluation runs make live API requests. The supplied tickets are synthetic examples, but the model responses, token usage and elapsed request times come from actual calls. Elapsed time includes network time. Reported costs are estimates calculated from the supplied pricing table.

    Automated checks and the final response-quality review run without additional model calls.

    Before Your First Run

    1. Copy the API Key displayed at the top of the lab interface.

    2. Open lab_config.json in the root of workspace.

    3. Set the api_key value to the key you copied:

      {
        "api_key": "PASTE_THE_KEY_FROM_THE_LAB_HEADER"
      }
      

    Prerequisites

    Before starting this lab, you should already be comfortable with:

    • Basic Python, including functions, dictionaries, and conditional logic
    • Reading and modifying existing code
    • Running Python commands and interpreting test results
    • Basic API requests and JSON responses
    • Prompts, model responses, and the purpose of an LLM client library

    You do not need prior experience with token accounting, prompt caching, or reasoning configuration. The lab introduces those concepts through guided implementation.

    Note: Complete the tasks in order. Run commands from the project root, workspace. Run the validation command provided for each task after editing.

    info> If you get stuck on a task, you can find solution files with the completed code for each task in the solution folder of your filetree.

  2. Challenge

    Establish a usage and cost baseline

    OpenAI responses include a usage object that describes the tokens processed and generated for a request. Turning that information into a baseline lets you compare later prompt and model changes on the same tickets. In this step, you will extract the usage fields, calculate an estimated cost, and save a report.

    A token is a piece of text processed by the model. It can be a word, part of a word, or punctuation. Counting words or characters does not give you an exact token count.

    Every application run makes live API requests. The three customer tickets are synthetic inputs, but the replies, usage values, and elapsed request times come from actual model calls. Your results can differ between runs.

    Input tokens include ordinary input and cached input. Where the selected model reports separately billed cache writes, those tokens also form part of the input total. Output tokens already include reasoning tokens. Preserve these details without adding them to the totals again. cached_tokens describes a subset of input usage; reasoning_tokens describes a subset of output usage. Neither is an extra amount to add to total_tokens.

    A missing usage object raises an error because an unknown cost should not be reported as zero. Absent or null optional detail objects do not prevent the function from processing valid input and output totals.

    The next task is to estimate cost. The price file expresses rates in US dollars per one million tokens. You will need to multiply each token category by its applicable rate, add those amounts, and divide by one million. For a request containing 1,000 ordinary input tokens and 200 output tokens, the calculation is:

    (1,000 × input rate + 200 × output rate) / 1,000,000
    

    If 150 of those output tokens are reasoning tokens, the output charge still covers 200 tokens. Adding another charge for the 150 reasoning tokens would count them twice.

    Decimal avoids binary floating-point representation errors when calculating with decimal prices. The result is an estimate of the model-token cost covered by src/data/pricing.json. It excludes charges outside that table and requests for which usage was not returned. A missing response usage object does not establish that a failed request was free.

    In a real-world scenario, use the rates for the actual model and processing tier. The supplied cache-write rates, where applicable, are total rates for those tokens rather than surcharges added to ordinary input pricing.

  3. Challenge

    Tighten prompts and control response length

    You now have a saved usage and cost baseline. The inherited task prompt contains polite filler and asks the model to repeat policy information. In this step, you will shorten those instructions, specify a concise response, and test a smaller output allowance on the same three tickets.

    A compact, telegraphic instruction is sometimes called Caveman prompting. Here it means removing filler and repetition while retaining clear actions, categories, and constraints. The response length requested in the prompt and the API output allowance serve different purposes. The first guides the visible reply. max_output_tokens sets a generation ceiling that also covers reasoning. A smaller ceiling does not force the model to use fewer tokens if its answer already fits below it. Now, after tightening the prompt and placing a ceiling on the number of tokens, it's time to create another token usage report.

  4. Challenge

    Compare single-request and sequential workflows

    So far, you have reduced token usage within a single request. Next, you will measure token usage across a sequential workflow.

    Next, you will separate ticket classification from response drafting and use the classification to select relevant policy material. By comparing response quality, total tokens, cost, and elapsed time, you’ll determine whether the additional step is justified for routine and complex tickets. The supplied runner first asks for classification JSON, then passes every returned category to this function. The second request receives the selected policies and the classification.

    Global instructions and writing rules stay in every draft. A ticket covering billing and account access retains both sections, including the inaccessible recovery-email exception.

  5. Challenge

    Route tasks and adjust reasoning effort

    So far, you have improved prompts and compared single-request and sequential workflows. Next, you will adjust how much reasoning the model uses for different tasks.

    You will route work by reasoning effort instead of switching models. You will then compare minimal, low, and medium effort on the same complex ticket to see whether additional reasoning improves a usable answer within the fixed output budget. Policy exceptions take priority over multiple constraints. Routine work starts at minimal effort. The supplied intake flags identify these conditions without making another classification request.

  6. Challenge

    Explore caching and batch processing

    Prompt caching is a technique that can reduce the billed input cost of repeated prompts. With caching in place, instead of re-processing an entire conversation, system prompt, or long document from scratch on every turn, the model saves the internal working state and only computes the new, changing tokens at the end.

    To implement this, you will place the supplied stable policy and reference before the changing ticket, inspect two real requests, and prepare a small Batch request file for historical classification. The existing support policy and the supplied CACHE_REFERENCE form the stable instruction prefix. The ticket appears later in the input. Keep the unique custom_id, POST method and classification body on each line unchanged.

    JSONL contains one JSON object per line, with no surrounding array.

  7. Challenge

    Evaluate the final configuration

    Lower usage is only useful when answers remain correct, compliant and complete. To guarantee this, you will compare the original and optimised configurations on four tickets, repair a missing policy exception, and select the lowest-cost configuration that meets the quality requirements.

    The dataset reuses the three existing tickets and adds one inaccessible-recovery-email case defined in src/experiments.py. No evaluation-data file needs to be created. This makes up to fourteen requests. Both full candidates receive the same four tickets.

    The original uses the original prompt and flagship model. The optimised workflow uses classification, selected policy, routing, the concise prompt, and your previously chosen reasoning effort.

    A separate two-case diagnostic uses COMPRESSED_POLICY, which deliberately omits the recovery-email exception, as it needs to be repaired, which you will do next. You can compare reports/task06_repair.md with the compressed-policy results in reports/task06.md.

    The same routine and exception cases are rerun with the same model and settings. Check that identity verification is retained and the ordinary reset does not acquire unnecessary escalation.

  8. Challenge

    Conclusion

    Congratulations! You’ve completed the lab.

    Over the course of these exercises, you took a working Python support-ticket application and made its token usage, estimated costs and response times measurable. You then explored how prompt length, workflow design, model selection, reasoning effort, caching and batch processing affect efficiency and answer quality.

    These decisions matter because an AI application must use resources responsibly while following policy and providing useful responses. Measuring savings alongside quality gives you evidence for deciding which changes to keep.

    What You Accomplished

    In this lab, you applied practical techniques for understanding and improving the application’s efficiency.

    • You recorded token usage, estimated request costs and elapsed time
    • You tightened prompts and controlled response length
    • You compared a combined request with separate classification and drafting steps
    • You routed tasks between model tiers and compared reasoning-effort settings
    • You inspected caching behaviour and completed a Batch request file using a supplied result example
    • You evaluated configurations against the same tickets and restored a missing policy exception

    Together, these exercises gave you a repeatable way to assess whether an optimization delivers worthwhile savings while preserving required behaviour.

    Why These Changes Matter Together

    Each part of the lab supports a different decision:

    • Measurement shows where tokens, money and time are being spent
    • Optimization explores ways to reduce that usage
    • Evaluation checks whether the resulting answers still meet requirements

    A shorter prompt, cheaper model or additional workflow step can change how the application handles a ticket. The effect must be checked against the expected decisions and response-quality requirements.

    An efficient support application should:

    • Include every request when calculating workflow usage and cost
    • Preserve policy exceptions and required escalations
    • Provide complete, useful responses
    • Use the lowest-cost configuration that meets its quality requirements

    That is the approach you practised throughout this lab.

    Final Reflection

    This lab focused on a practical principle: reducing token usage is valuable when the application continues to make correct decisions and provide useful answers. Cost, latency and quality need to be assessed together.

    The compression exercise demonstrated why this matters. Removing a small amount of policy text can remove an essential exception, making a cheaper response unsuitable for the customer’s situation.

    You now have hands-on experience collecting usage data, comparing configurations and using evaluation results to guide optimization.

    Next Steps

    After this lab, you could continue exploring:

    • Larger evaluation datasets with more policy exceptions
    • Automated regression checks for prompts and model changes
    • Usage and cost monitoring across real workloads
    • Cache behaviour under repeated production traffic
    • Submitting Batch jobs for historical ticket classification

    Each topic builds on the same goal you practised here: making AI applications useful, efficient and measurable.

    Great work completing the lab.

About the author

Fiodar is a senior software engineer with a focus on cloud development and AI engineering. 3 times Microsoft MVP.

Real skill practice before real-world application

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Learn by doing

Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.

Follow your guide

All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.

Turn time into mastery

On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.

Get started with Pluralsight