DeepSeek API Cost-Aware Scheduling in N8N

DeepSeek API Cost-Aware Scheduling in N8N

0
0

Learn how to schedule DeepSeek API calls during off-peak pricing windows using N8N to reduce costs.

Understanding DeepSeek API Pricing Tiers

To implement cost-aware scheduling, you first need to understand how DeepSeek prices its API usage. The official DeepSeek API platform (platform. deepseek.

com) is the authoritative source for pricing details, but as of this writing, the public pages do not display a clear peak/off-peak pricing structure. DeepSeek’s official website (deepseek.

com) provides general product information but does not list specific API rates. This means you must rely on the official pricing documentation and any announcements from DeepSeek for the most current rates and discount windows.

DeepSeek may offer different pricing tiers based on model type, usage volume, or time of day. For example, some providers offer off-peak discounts to encourage usage during low-demand periods.

However, without explicit confirmation from DeepSeek, you should not assume such discounts exist. Instead, treat any pricing information as subject to change and verify it regularly through official channels.

For cost-aware scheduling, the key is to capture the price at the time of your API call. This allows you to calculate the actual cost of each request, regardless of whether DeepSeek introduces time-based pricing in the future.

By storing price snapshots, you can later analyze your spending patterns and adjust your scheduling strategy accordingly.

Remember: prices can change without notice. Always check the official DeepSeek API documentation and announcements for updates. Do not rely on third-party summaries or outdated blog posts.

Setting Up the N8N Workflow Foundation

To build a cost-aware scheduling system, start with a basic N8N workflow that can trigger API calls at specified intervals. The core components are a Schedule Trigger node and an HTTP Request node configured to call the DeepSeek API.

1. **Schedule Trigger**: Add a Schedule Trigger node to your workflow. Configure it to run periodically, for example every hour. This will be the entry point for your workflow.

2. **HTTP Request Node**: Add an HTTP Request node and connect it to the Schedule Trigger. Configure it to call the DeepSeek API endpoint you need. Set the method (e.g., POST for chat completions), URL, headers (including your API key), and body as required. For authentication, use the ‘Predefined Credential’ or ‘Generic Credential’ type and store your API key securely in N8N credentials.

3. **Response Handling**: After the HTTP Request node, add a node to process the response. You might use a Function node to extract relevant data, or simply pass the response to subsequent nodes for storage or further processing.

This foundation allows you to make regular API calls. However, to implement cost-aware scheduling, you need to add logic that decides when to make calls based on pricing windows.

That logic will be built in later steps, but the workflow structure must support conditional execution.

Implementing Preflight Price Snapshots

Before each API call, you should fetch the current pricing information from DeepSeek. This snapshot serves as a baseline for calculating the cost of the upcoming request.

It is important to note that this snapshot is for post-hoc cost accounting, not real-time billing. DeepSeek will bill you based on their internal rates at the time of the call, but by storing the price you saw, you can later reconcile your records.

To implement preflight price snapshots in N8N:

1. **Fetch Pricing**: Add an HTTP Request node before the main API call. Configure it to retrieve pricing data from an official DeepSeek source. This could be a dedicated pricing API endpoint if available, or you might parse the official pricing page. Since the exact endpoint is not documented publicly, you may need to inspect the network requests on the DeepSeek platform or use a web scraping approach. However, be cautious: scraping may violate terms of service. Alternatively, you can manually update a price table in your workflow or database when DeepSeek announces changes.

2. **Store Price Data**: After fetching, store the price data in a variable or a database. In N8N, you can use a Set node to add the price to the workflow data, or write it to a database like SQLite or PostgreSQL for later analysis. For example, you could store the price per million tokens for input and output, along with a timestamp.

3. **Use in Cost Calculation**: After the API call, you can calculate the estimated cost by multiplying the token usage from the response by the stored price. This calculation can be done in a Function node.

To illustrate, consider the following N8N workflow configuration example (JSON):

“`json
{
"nodes": [
{
"parameters": {},
"id": "schedule-trigger",
"name": "Schedule Trigger",
"type": "n8n-nodes-base.scheduleTrigger",
"typeVersion": 1,
"position": [0, 0]
},
{
"parameters": {
"url": "https://api.deepseek.com/v1/chat/completions",
"method": "POST",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Authorization",
"value": "Bearer YOUR_API_KEY"
}
]
},
"sendBody": true,
"bodyParameters": {
"parameters": [
{
"name": "model",
"value": "deepseek-chat"
},
{
"name": "messages",
"value": "[{\"role\":\"user\",\"content\":\"Hello\"}]"
}
]
},
"options": {}
},
"id": "http-request",
"name": "DeepSeek API Call",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4,
"position": [200, 0]
},
{
"parameters": {
"url": "https://api.deepseek.com/pricing",
"method": "GET",
"authentication": "none",
"options": {}
},
"id": "price-snapshot",
"name": "Fetch Price Snapshot",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4,
"position": [200, -200]
},
{
"parameters": {
"mode": "runOnceForAllItems",
"jsCode": "// Store price data in a variable for later use\nconst priceData = $input.first().json;\n// Assume priceData contains inputPrice and outputPrice per million tokens\nreturn { json: { priceSnapshot: priceData } };"
},
"id": "function-store-price",
"name": "Store Price",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [400, -200]
},
{
"parameters": {
"mode": "runOnceForAllItems",
"jsCode": "// Calculate cost based on usage and price snapshot\nconst usage = $input.first().json.usage;\nconst price = $input.first().json.priceSnapshot;\nconst inputCost = (usage.prompt_tokens / 1000000) * price.inputPrice;\nconst outputCost = (usage.completion_tokens / 1000000) * price.outputPrice;\nconst totalCost = inputCost + outputCost;\nreturn { json: { totalCost } };"
},
"id": "function-calc-cost",
"name": "Calculate Cost",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [400, 200]
}
],
"connections": {
"Schedule Trigger": {
"main": [
[
{
"node": "Fetch Price Snapshot",
"type": "main",
"index": 0
}
]
]
},
"Fetch Price Snapshot": {
"main": [
[
{
"node": "Store Price",
"type": "main",
"index": 0
}
]
]
},
"Store Price": {
"main": [
[
{
"node": "DeepSeek API Call",
"type": "main",
"index": 0
}
]
]
},
"DeepSeek API Call": {
"main": [
[
{
"node": "Calculate Cost",
"type": "main",
"index": 0
}
]
]
}
}
}
“`

In this example, the workflow first fetches a price snapshot, stores it, then makes the API call, and finally calculates the cost.

The price snapshot retrieval method is a GET request to a hypothetical pricing endpoint; you must replace it with the actual method DeepSeek provides.

If no API endpoint exists, you could manually update a price table in a database and retrieve it via a database node.

Remember that the price snapshot is only as accurate as the source. If DeepSeek does not offer a real-time pricing API, you must rely on periodic manual updates. Always timestamp your snapshots and note the source URL for auditability.

By implementing preflight price snapshots, you lay the groundwork for cost tracking and later optimization, such as deferring non-urgent calls to off-peak windows if DeepSeek introduces such pricing.

Weekday and Time Window Checks

To implement cost-aware scheduling, you first need to determine when DeepSeek API calls are cheaper. While DeepSeek’s official pricing page (platform. deepseek.

com/usage) is the authoritative source, it does not always display peak/off-peak windows directly in search snippets. You must check the official documentation for any time-based discounts.

If such windows exist, you can use N8N’s Schedule Trigger and IF nodes to conditionally route tasks.

Start by creating a workflow that triggers on a schedule or when a new task arrives. Use a Schedule Trigger to run a check every minute or hour, depending on your needs. Then, add an IF node to evaluate whether the current time falls within a discount window.

For example, if off-peak hours are from 22:00 to 06:00 on weekdays, you can use a JavaScript expression in the IF node to compare the current hour against these bounds. N8N’s IF node supports custom expressions, so you can write logic like `{{ $now.

getHours() >= 22 || $now. getHours() < 6 }}`.

If your pricing varies by weekday (e. g. , weekends are cheaper), incorporate a workday calendar. You can use N8N’s built-in date functions or a third-party node to check the day of the week.

For instance, you might set a condition that if it’s Saturday or Sunday, treat it as off-peak regardless of time. This requires a more complex expression, but N8N allows you to chain conditions using logical operators.

When the IF node determines it’s peak time, you should mark the task as deferred. You can do this by adding a Set node that adds a field like `status: ‘deferred’` to the task data. This status will be used later when building the queue.

Conversely, if it’s off-peak, you can proceed directly to the API call.

It’s important to validate your time logic. Use N8N’s Execute Command node to run a simple script that outputs the current time and your condition’s result, ensuring your expression works as expected.

Also, consider timezone differences: N8N runs on UTC by default, so you may need to adjust for your local timezone using the `$now` object’s timezone methods or by setting the workflow’s timezone in settings.

Building Deferred Queues and Urgent Overrides

Once you have a mechanism to identify peak periods, you need a queue to hold deferred tasks until off-peak windows. N8N doesn’t have a built-in queue, but you can use a database or N8N’s data storage.

A simple approach is to use a Google Sheets or Airtable base as your queue, but for a more robust solution, consider using a SQLite database via the SQLite node or a Redis instance.

Design your queue with fields like `task_id`, `payload`, `priority`, `status`, and `created_at`. The `status` field can be ‘pending’ or ‘deferred’. When a task is deferred, you insert it into the queue with a status of ‘deferred’.

For urgent tasks, you can set a `priority` field to ‘high’ and bypass the deferral logic entirely.

To implement urgent overrides, modify your workflow to check the priority before applying the time condition. For example, if a task arrives with `priority: ‘high’`, you can skip the IF node and execute the API call immediately.

This ensures that time-sensitive operations are not delayed.

Periodically, you need to process the queue during low-cost windows. Set up a separate workflow triggered by a Schedule Trigger that runs every minute.

This workflow should query the queue for tasks with `status: ‘deferred’` and check if the current time is now off-peak. If so, it retrieves the task payload and executes the API call, then updates the queue to mark the task as ‘completed’.

When building the queue, consider failure handling. If an API call fails, you might want to retry it later. You can add a `retry_count` field and increment it on failure.

After a maximum number of retries, you can move the task to a ‘failed’ status for manual review.

Here’s an example of a queue structure in JSON:

“`json
{
"task_id": "uuid",
"payload": { "prompt": "…", "model": "deepseek-chat" },
"priority": "normal",
"status": "deferred",
"created_at": "2025-01-01T00:00:00Z",
"retry_count": 0
}
“`

Token Ledger and Cost Review

To track costs accurately, you need to record token usage for each API call and calculate the cost based on the pricing at the time of the call.

DeepSeek’s API responses include usage information, typically in the `usage` field, with `prompt_tokens` and `completion_tokens`. You can extract these values using a Set node or a Function node.

Before making a call, capture a price snapshot. Since pricing may change, you should retrieve the latest pricing from the official API or documentation. You can store this in a separate database or as a static configuration.

For example, you might have a table with `model`, `input_price_per_million`, `output_price_per_million`, and `effective_date`. When you make a call, you look up the current price and store it with the usage data.

After each API call, calculate the cost using the formula: `cost = (input_tokens / 1,000,000) * input_price + (output_tokens / 1,000,000) * output_price`.

Then, insert a record into a ledger table with fields like `timestamp`, `model`, `input_tokens`, `output_tokens`, `cost`, and `peak_or_offpeak`. This ledger allows you to analyze spending patterns.

To generate periodic cost reports, you can create a workflow that runs weekly or monthly. Use an Aggregate node to sum costs by day or by peak/off-peak status. You can then output the report to a file or send it via email.

For example, you might want to see how much you saved by deferring tasks.

It’s crucial to validate the accuracy of your price snapshots. Since pricing can change, you should periodically check the official DeepSeek API documentation for updates.

You can automate this by having a workflow that fetches the latest pricing and updates your configuration. However, be aware that the official pricing page may not always be accessible via API, so you might need to manually update the snapshot.

To ensure ledger integrity, implement error handling. If an API call fails, you should not record a cost. Also, consider using idempotency keys to avoid duplicate entries. You can use N8N’s built-in error workflow to log failures and retry if necessary.

By maintaining a token ledger, you can identify which tasks are most expensive and adjust your scheduling strategy accordingly.

For example, if you notice that certain types of requests are more token-intensive, you might prioritize them for off-peak execution.

### Required Artifact: N8N Workflow Configuration Example

Below is a simplified N8N workflow configuration that demonstrates the key nodes and logic for cost-aware scheduling. This is a template; replace placeholder values with your actual data.

| Node | Type | Configuration |
|——|——|—————|
| Schedule Trigger | Trigger | Cron: `*/5 * * * *` (every 5 minutes) |
| IF (Time Check) | IF | Condition: `{{ $now.getHours() >= 22 || $now.getHours() < 6 }}` (adjust for your off-peak hours) |
| Set (Defer) | Set | Set `status` to `deferred` |
| Insert Queue | Database (e.g., MySQL) | Insert into `task_queue` table |
| Process Queue | Schedule Trigger | Cron: `*/1 * * * *` (every minute) |
| Read Queue | Database | Select from `task_queue` where `status = ‘deferred’` |
| IF (Time Check for Queue) | IF | Same as above |
| Call DeepSeek API | HTTP Request | Method: POST, URL: `https://api.deepseek.com/chat/completions` |
| Extract Usage | Function | Extract `usage.prompt_tokens` and `usage.completion_tokens` |
| Calculate Cost | Function | Compute cost using price snapshot |
| Insert Ledger | Database | Insert into `token_ledger` table |
| Update Queue | Database | Update `status` to `completed` |

**Queue Storage Structure** (SQLite example):

“`sql
CREATE TABLE task_queue (
task_id TEXT PRIMARY KEY,
payload TEXT,
priority TEXT DEFAULT ‘normal’,
status TEXT DEFAULT ‘pending’,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
retry_count INTEGER DEFAULT 0
);
“`

**Price Snapshot Retrieval Method**:

– Store pricing in a `pricing` table with fields: `model`, `input_price_per_million`, `output_price_per_million`, `effective_date`.
– Before each API call, query the latest pricing for the model being used.
– If pricing changes, update the table manually or via a scheduled workflow that checks the official docs.

**Conditional Logic**:

– In the IF node, use JavaScript expressions to evaluate time and weekday.
– For urgent overrides, check a `priority` field in the incoming data; if it equals ‘high’, skip the deferral.

This configuration provides a foundation. You will need to adapt it to your specific database and API endpoints.

Next step

Download the N8N workflow template and start configuring

Related services and further reading

Official references and sources

Comments (0)

No comments yet. Be the first!

Please Log in to post comments.