mirror of
https://github.com/wassname/openrouter-python-sdk-retry-errors.git
synced 2026-07-31 12:30:30 +08:00
Compare commits
178
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
778e2e36fb | ||
|
|
14f262fa66 | ||
|
|
10f2890d75 | ||
|
|
ad1cfda1f4 | ||
|
|
21020fb334 | ||
|
|
a243d78d32 | ||
|
|
66512fa808 | ||
|
|
7efd03fb3b | ||
|
|
e1b89f5aaf | ||
|
|
32dd522d5a | ||
|
|
eeb0373033 | ||
|
|
facade7d00 | ||
|
|
08e796401a | ||
|
|
f8e8ab669d | ||
|
|
5e0b1a2b69 | ||
|
|
667941aaa8 | ||
|
|
011fb81cc3 | ||
|
|
5c06b57cea | ||
|
|
0680f01bf7 | ||
|
|
186c1075ce | ||
|
|
b161a5c288 | ||
|
|
4f018c91d7 | ||
|
|
63949d45e2 | ||
|
|
399c1d0e02 | ||
|
|
89717dca56 | ||
|
|
c8bf74a516 | ||
|
|
4e551e432f | ||
|
|
60add6da49 | ||
|
|
ddcadce542 | ||
|
|
5cefd3a108 | ||
|
|
713dd5c71a | ||
|
|
678d5aacc5 | ||
|
|
b3f4ab7452 | ||
|
|
7b4b9feaa5 | ||
|
|
add423f762 | ||
|
|
c34ce15fa2 | ||
|
|
8e637041c4 | ||
|
|
146cec3c08 | ||
|
|
14a62e3451 | ||
|
|
7e29e408af | ||
|
|
30bc131b97 | ||
|
|
1b0118c365 | ||
|
|
cda73e5ebf | ||
|
|
b0eda78d3f | ||
|
|
bf682bdb62 | ||
|
|
b322622117 | ||
|
|
415450e785 | ||
|
|
1d488f0117 | ||
|
|
4e789208b4 | ||
|
|
cdd4dc7302 | ||
|
|
60708e1e8b | ||
|
|
5a324f99ae | ||
|
|
d5778dfafb | ||
|
|
68c251830c | ||
|
|
2aa2d73d2d | ||
|
|
58bd390fbd | ||
|
|
2707901239 | ||
|
|
a5ed2de8a8 | ||
|
|
21893dda58 | ||
|
|
758a2f3d49 | ||
|
|
0331f14f19 | ||
|
|
138b131a35 | ||
|
|
55c0d5c7fd | ||
|
|
e98a7a8260 | ||
|
|
7e7787cb23 | ||
|
|
c4b508f045 | ||
|
|
52e7853d21 | ||
|
|
d43061f722 | ||
|
|
7b10fd47d8 | ||
|
|
95f2c87bfa | ||
|
|
c756fc51e0 | ||
|
|
386db75669 | ||
|
|
e3dc2e6f4c | ||
|
|
70c8757fc0 | ||
|
|
b794150ed9 | ||
|
|
0f116c9792 | ||
|
|
0c735989c1 | ||
|
|
3b2f5b2316 | ||
|
|
3883438f02 | ||
|
|
1cd1e66e2d | ||
|
|
f29a61de7e | ||
|
|
1725abad89 | ||
|
|
8df520997d | ||
|
|
c4843278fd | ||
|
|
ccbd6d16f8 | ||
|
|
80646bd8a6 | ||
|
|
68fc6f0ee9 | ||
|
|
23ee599564 | ||
|
|
2203de96b4 | ||
|
|
b7d5098042 | ||
|
|
b9f588d84b | ||
|
|
5caa85a52c | ||
|
|
fc328cd45d | ||
|
|
234901509f | ||
|
|
771a5b1a52 | ||
|
|
93dd1b59fd | ||
|
|
698e7d6d7e | ||
|
|
fe4080dfda | ||
|
|
1090ab30b2 | ||
|
|
51a8873f33 | ||
|
|
a95178f8b3 | ||
|
|
63b73f57d4 | ||
|
|
6ceb25ca84 | ||
|
|
b5aca7806b | ||
|
|
4610ea4719 | ||
|
|
67bd50597a | ||
|
|
859e89d545 | ||
|
|
f94fcc1eb1 | ||
|
|
c361f61f5b | ||
|
|
f119275b26 | ||
|
|
460658428f | ||
|
|
5d441447a9 | ||
|
|
d549103228 | ||
|
|
3e77e61a5c | ||
|
|
e0dddac466 | ||
|
|
32c6c506cf | ||
|
|
59a8775ed7 | ||
|
|
e7a06917b2 | ||
|
|
d8c617dfd2 | ||
|
|
752156a9ad | ||
|
|
688c063276 | ||
|
|
da19555f7f | ||
|
|
0ecf2ef253 | ||
|
|
a7fd661299 | ||
|
|
c5e2532cc4 | ||
|
|
0aa6eabffd | ||
|
|
205749ae6b | ||
|
|
bf8a2c6adc | ||
|
|
9312cabf22 | ||
|
|
ec85ab283b | ||
|
|
4c5911ffee | ||
|
|
882f4a0811 | ||
|
|
90f661ff73 | ||
|
|
bb74b7fabc | ||
|
|
a7bb403311 | ||
|
|
522b03abf3 | ||
|
|
be479e24fd | ||
|
|
a4197ac1db | ||
|
|
f587c3ce45 | ||
|
|
a4ae8297ce | ||
|
|
4664c73492 | ||
|
|
e150991aa7 | ||
|
|
5f18dd0131 | ||
|
|
5441e86fee | ||
|
|
bb505b71e5 | ||
|
|
45c3ace681 | ||
|
|
d208cc6cf8 | ||
|
|
fb31150e8f | ||
|
|
e0e80c538a | ||
|
|
7db74e51d1 | ||
|
|
27c12d4d59 | ||
|
|
cd24443470 | ||
|
|
2fc0ea8084 | ||
|
|
330cff1158 | ||
|
|
8ac9dede84 | ||
|
|
c10bbfe084 | ||
|
|
3d1fdef97a | ||
|
|
067cdc027a | ||
|
|
5bad276c29 | ||
|
|
f3699017d5 | ||
|
|
b202e599ae | ||
|
|
be9056bcbe | ||
|
|
cb23cec150 | ||
|
|
312ffce1c5 | ||
|
|
c5e87b6ab2 | ||
|
|
a23c20f60b | ||
|
|
e6703a5038 | ||
|
|
9ce403745a | ||
|
|
175b135377 | ||
|
|
0503928934 | ||
|
|
6006c3a84f | ||
|
|
c2a933ff6b | ||
|
|
a34a1456a1 | ||
|
|
a40c0019c1 | ||
|
|
5881e47375 | ||
|
|
6989ad4f40 | ||
|
|
b2386114cd | ||
|
|
2bba049182 |
@@ -0,0 +1,225 @@
|
||||
name: Auto-merge Speakeasy PR
|
||||
|
||||
# Called as a follow-up job after Speakeasy Generate (mode: pr). Merges the
|
||||
# regen PR opened/updated in the same workflow run so sdk_publish.yaml can run.
|
||||
# Prefer branch_name from Generate logs; fall back to run_started_at heuristics.
|
||||
# Uses GH_DOCS_SYNC GitHub App token (not a PAT) so merges trigger downstream push.
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
run_started_at:
|
||||
description: ISO timestamp when the parent Generate workflow run started
|
||||
required: true
|
||||
type: string
|
||||
branch_name:
|
||||
description: Speakeasy regen branch from the parent Generate run (optional)
|
||||
required: false
|
||||
type: string
|
||||
default: ""
|
||||
secrets:
|
||||
GH_DOCS_SYNC_APP_ID:
|
||||
required: true
|
||||
GH_DOCS_SYNC_APP_PRIVATE_KEY:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: auto-merge-speakeasy
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
auto-merge:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Generate GitHub App token
|
||||
id: app-token
|
||||
# actions/create-github-app-token@v3.2.0 (immutable SHA)
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1
|
||||
with:
|
||||
app-id: ${{ secrets.GH_DOCS_SYNC_APP_ID }}
|
||||
private-key: ${{ secrets.GH_DOCS_SYNC_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Resolve Speakeasy regen PR
|
||||
id: pr
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
REPO="${{ github.repository }}"
|
||||
RUN_STARTED="${{ inputs.run_started_at }}"
|
||||
BRANCH="${{ inputs.branch_name }}"
|
||||
|
||||
PR_JSON=$(gh pr list \
|
||||
--repo "$REPO" \
|
||||
--state open \
|
||||
--search "head:speakeasy-sdk-regen-" \
|
||||
--limit 500 \
|
||||
--json number,updatedAt,title,labels,author,headRefName)
|
||||
|
||||
PR_NUM=""
|
||||
if [ -n "$BRANCH" ]; then
|
||||
CANDIDATE=$(echo "$PR_JSON" | jq -r --arg branch "$BRANCH" \
|
||||
'[.[] | select(.headRefName == $branch)] | .[0] // empty')
|
||||
if [ -n "$CANDIDATE" ] && echo "$CANDIDATE" | jq -e '
|
||||
(.headRefName | startswith("speakeasy-sdk-regen-"))
|
||||
and (.title | contains("🐝 Update SDK"))
|
||||
and ([.labels[].name] | any(. == "patch" or . == "minor" or . == "major"))
|
||||
and (.author.is_bot == true)
|
||||
' > /dev/null; then
|
||||
PR_NUM=$(echo "$CANDIDATE" | jq -r '.number')
|
||||
echo "Resolved Speakeasy regen PR #$PR_NUM from branch $BRANCH"
|
||||
else
|
||||
echo "::warning::branch_name=$BRANCH did not match a valid open regen PR — falling back to run_started_at"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$PR_NUM" ]; then
|
||||
PR_NUM=$(echo "$PR_JSON" | jq -r --arg started "$RUN_STARTED" '
|
||||
[.[]
|
||||
| select(.headRefName | startswith("speakeasy-sdk-regen-"))
|
||||
| select(.title | contains("🐝 Update SDK"))
|
||||
| select([.labels[].name] | any(. == "patch" or . == "minor" or . == "major"))
|
||||
| select(.author.is_bot == true)
|
||||
| select(.updatedAt >= $started)
|
||||
] | sort_by(.updatedAt) | last | .number // empty')
|
||||
fi
|
||||
|
||||
if [ -z "$PR_NUM" ]; then
|
||||
echo "No Speakeasy regen PR for this Generate run — skipping auto-merge"
|
||||
echo "::notice title=auto-merge-skipped::No qualifying Speakeasy regen PR to merge"
|
||||
{
|
||||
echo "## Auto-merge skipped"
|
||||
echo "No qualifying \`speakeasy-sdk-regen-*\` PR was found."
|
||||
echo "- branch_name input: \`${BRANCH:-<empty>}\`"
|
||||
echo "- run_started_at: \`$RUN_STARTED\`"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "pr_num=" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "pr_num=$PR_NUM" >> "$GITHUB_OUTPUT"
|
||||
echo "$PR_JSON" > /tmp/speakeasy_pr_json.json
|
||||
|
||||
- name: Close superseded Speakeasy PRs
|
||||
if: steps.pr.outputs.pr_num != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
CURRENT_PR="${{ steps.pr.outputs.pr_num }}"
|
||||
PR_JSON=$(cat /tmp/speakeasy_pr_json.json)
|
||||
|
||||
PRIOR_JSON=$(echo "$PR_JSON" | jq -r --arg current_pr "$CURRENT_PR" \
|
||||
'[.[].number | select(tostring != $current_pr)] | .[]')
|
||||
|
||||
if [ -z "$PRIOR_JSON" ]; then
|
||||
echo "No superseded Speakeasy PRs to close"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
mapfile -t PRIOR <<< "$PRIOR_JSON"
|
||||
|
||||
echo "Closing ${#PRIOR[@]} superseded Speakeasy PR(s)"
|
||||
for N in "${PRIOR[@]}"; do
|
||||
gh pr close "$N" --repo "${{ github.repository }}" --delete-branch \
|
||||
--comment "Superseded by newer Speakeasy SDK generation PR #${CURRENT_PR}" \
|
||||
|| echo "::warning::Failed to close PR #$N (continuing)"
|
||||
sleep 1
|
||||
done
|
||||
|
||||
- name: Auto-merge Speakeasy PR
|
||||
if: steps.pr.outputs.pr_num != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
PR_NUM="${{ steps.pr.outputs.pr_num }}"
|
||||
REPO="${{ github.repository }}"
|
||||
|
||||
wait_for_checks() {
|
||||
local pr=$1
|
||||
local timeout=600
|
||||
local interval=15
|
||||
local elapsed=0
|
||||
|
||||
echo "Waiting for PR #$pr checks (timeout ${timeout}s)..."
|
||||
while [ "$elapsed" -lt "$timeout" ]; do
|
||||
TOTAL=$(gh pr view "$pr" --repo "$REPO" --json statusCheckRollup --jq \
|
||||
'.statusCheckRollup | length')
|
||||
PENDING=$(gh pr view "$pr" --repo "$REPO" --json statusCheckRollup --jq \
|
||||
'[.statusCheckRollup[]? | select(.status != "COMPLETED")] | length')
|
||||
FAILED=$(gh pr view "$pr" --repo "$REPO" --json statusCheckRollup --jq \
|
||||
'[.statusCheckRollup[]? | select(.status == "COMPLETED") | select(.conclusion != "SUCCESS" and .conclusion != "SKIPPED" and .conclusion != "NEUTRAL")] | length')
|
||||
|
||||
if [ "$TOTAL" -eq 0 ]; then
|
||||
# GITHUB_TOKEN-authored regen PRs get no pull_request checks at all,
|
||||
# so TOTAL stays 0 forever. Wait a short grace window in case checks
|
||||
# are merely slow to register, then proceed rather than time out.
|
||||
if [ "$elapsed" -ge 60 ]; then
|
||||
echo "No checks registered after ${elapsed}s — proceeding (checkless PR)"
|
||||
return 0
|
||||
fi
|
||||
echo "Checks not yet registered — waiting ${interval}s..."
|
||||
sleep "$interval"
|
||||
elapsed=$((elapsed + interval))
|
||||
continue
|
||||
fi
|
||||
|
||||
if [ "$PENDING" -eq 0 ]; then
|
||||
if [ "$FAILED" -gt 0 ]; then
|
||||
echo "::error::PR #$pr has failing checks — refusing direct merge"
|
||||
gh pr checks "$pr" --repo "$REPO" || true
|
||||
exit 1
|
||||
fi
|
||||
echo "All checks completed"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "Checks pending ($PENDING) — waiting ${interval}s..."
|
||||
sleep "$interval"
|
||||
elapsed=$((elapsed + interval))
|
||||
done
|
||||
|
||||
echo "::error::Timed out waiting for PR #$pr checks"
|
||||
exit 1
|
||||
}
|
||||
|
||||
STATE=$(gh pr view "$PR_NUM" --repo "$REPO" --json state --jq .state)
|
||||
if [ "$STATE" != "OPEN" ]; then
|
||||
echo "PR #$PR_NUM is $STATE — skipping merge"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
MERGE_METHOD=""
|
||||
# Prefer GitHub auto-merge when required checks exist; otherwise
|
||||
# squash-merge directly after checks pass (sdk-release-prs.yaml pattern).
|
||||
AUTO_MERGE_NOOP_PATTERN='is in clean status|protected branch rules|Branch does not have required protected branch rules'
|
||||
if gh pr merge "$PR_NUM" --repo "$REPO" --squash --auto --delete-branch 2> /tmp/gh-merge.err; then
|
||||
MERGE_METHOD="auto-merge queued"
|
||||
echo "Auto-merge enabled for Speakeasy PR #$PR_NUM"
|
||||
elif grep -qiE "$AUTO_MERGE_NOOP_PATTERN" /tmp/gh-merge.err; then
|
||||
echo "Auto-merge not applicable — waiting for checks, then merging PR #$PR_NUM directly"
|
||||
cat /tmp/gh-merge.err >&2
|
||||
wait_for_checks "$PR_NUM"
|
||||
gh pr merge "$PR_NUM" --repo "$REPO" --squash --delete-branch
|
||||
MERGE_METHOD="direct squash (checks passed)"
|
||||
else
|
||||
echo "::error::Failed to enable auto-merge on Speakeasy PR #$PR_NUM"
|
||||
cat /tmp/gh-merge.err >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "::notice title=auto-merge-pr::Merged Speakeasy PR #$PR_NUM ($MERGE_METHOD)"
|
||||
{
|
||||
echo "## Auto-merge complete"
|
||||
echo "- PR: #$PR_NUM"
|
||||
echo "- Method: $MERGE_METHOD"
|
||||
echo "- Token: GH_DOCS_SYNC GitHub App"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -0,0 +1,37 @@
|
||||
name: PR Validation
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths-ignore:
|
||||
- .speakeasy/in.openapi.yaml
|
||||
|
||||
concurrency:
|
||||
group: pr-validation-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
|
||||
- name: Build SDK
|
||||
run: uv build
|
||||
|
||||
- name: Type check (mypy)
|
||||
run: uv run --group dev mypy src
|
||||
|
||||
- name: Type check (pyright)
|
||||
run: uv run --group dev pyright src
|
||||
|
||||
- name: Lint (pylint)
|
||||
run: uv run --group dev pylint src --rcfile pylintrc
|
||||
@@ -21,6 +21,11 @@ permissions:
|
||||
types:
|
||||
- labeled
|
||||
- unlabeled
|
||||
|
||||
concurrency:
|
||||
group: speakeasy-generate
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
generate:
|
||||
uses: speakeasy-api/sdk-generation-action/.github/workflows/workflow-executor.yaml@v15
|
||||
@@ -32,3 +37,67 @@ jobs:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
pypi_token: ${{ secrets.PYPI_TOKEN }}
|
||||
speakeasy_api_key: ${{ secrets.SPEAKEASY_API_KEY }}
|
||||
|
||||
resolve-branch:
|
||||
needs: generate
|
||||
if: ${{ !cancelled() && needs.generate.result == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
branch_name: ${{ steps.branch.outputs.branch_name }}
|
||||
run_started_at: ${{ steps.branch.outputs.run_started_at }}
|
||||
steps:
|
||||
- name: Extract branch from Generate logs
|
||||
id: branch
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
REPO="${{ github.repository }}"
|
||||
RUN_ID="${{ github.run_id }}"
|
||||
|
||||
RUN_STARTED="${{ github.run_started_at }}"
|
||||
if [ -z "$RUN_STARTED" ]; then
|
||||
RUN_STARTED=$(gh run view "$RUN_ID" --repo "$REPO" --json startedAt --jq '.startedAt')
|
||||
echo "Resolved run_started_at from API: $RUN_STARTED"
|
||||
fi
|
||||
echo "run_started_at=$RUN_STARTED" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Full-run logs are unavailable while the workflow is in progress;
|
||||
# fetch logs from the completed generate job instead.
|
||||
JOB_ID=$(gh run view "$RUN_ID" --repo "$REPO" --json jobs --jq \
|
||||
'[.jobs[] | select(.name == "generate / Generate Target")] | .[0].databaseId // empty')
|
||||
|
||||
BRANCH=""
|
||||
if [ -z "$JOB_ID" ]; then
|
||||
echo "::warning::Could not find generate job id — auto-merge will use run_started_at fallback"
|
||||
else
|
||||
MAX_ATTEMPTS=12
|
||||
INTERVAL=10
|
||||
for attempt in $(seq 1 "$MAX_ATTEMPTS"); do
|
||||
BRANCH=$(gh run view "$RUN_ID" --repo "$REPO" --job "$JOB_ID" --log 2>/dev/null \
|
||||
| grep -oE 'branch_name=speakeasy-sdk-regen-[0-9]+' | tail -1 | cut -d= -f2 || true)
|
||||
if [ -n "$BRANCH" ]; then
|
||||
echo "Extracted branch_name=$BRANCH (attempt $attempt)"
|
||||
break
|
||||
fi
|
||||
if [ "$attempt" -lt "$MAX_ATTEMPTS" ]; then
|
||||
echo "Job logs not ready — waiting ${INTERVAL}s (attempt $attempt/$MAX_ATTEMPTS)..."
|
||||
sleep "$INTERVAL"
|
||||
fi
|
||||
done
|
||||
if [ -z "$BRANCH" ]; then
|
||||
echo "::warning::Could not extract branch_name from Generate logs after ${MAX_ATTEMPTS} attempts — auto-merge will use run_started_at fallback"
|
||||
fi
|
||||
fi
|
||||
echo "branch_name=$BRANCH" >> "$GITHUB_OUTPUT"
|
||||
|
||||
auto-merge:
|
||||
needs: [generate, resolve-branch]
|
||||
if: ${{ !cancelled() && needs.generate.result == 'success' }}
|
||||
uses: ./.github/workflows/auto-merge-speakeasy-pr.yaml
|
||||
with:
|
||||
run_started_at: ${{ needs.resolve-branch.outputs.run_started_at }}
|
||||
branch_name: ${{ needs.resolve-branch.outputs.branch_name }}
|
||||
secrets:
|
||||
GH_DOCS_SYNC_APP_ID: ${{ secrets.GH_DOCS_SYNC_APP_ID }}
|
||||
GH_DOCS_SYNC_APP_PRIVATE_KEY: ${{ secrets.GH_DOCS_SYNC_APP_PRIVATE_KEY }}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
name: Generate (spec change merged)
|
||||
permissions:
|
||||
checks: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
statuses: write
|
||||
id-token: write
|
||||
"on":
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force:
|
||||
description: Force generation of SDKs
|
||||
type: boolean
|
||||
default: false
|
||||
set_version:
|
||||
description: optionally set a specific SDK version
|
||||
type: string
|
||||
pull_request:
|
||||
types: [closed]
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- .speakeasy/in.openapi.yaml
|
||||
|
||||
concurrency:
|
||||
group: speakeasy-generate-spec-change
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
generate:
|
||||
if: github.event.pull_request.merged == true || github.event_name == 'workflow_dispatch'
|
||||
uses: speakeasy-api/sdk-generation-action/.github/workflows/workflow-executor.yaml@v15
|
||||
with:
|
||||
force: ${{ github.event.inputs.force }}
|
||||
mode: pr
|
||||
set_version: ${{ github.event.inputs.set_version }}
|
||||
secrets:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
pypi_token: ${{ secrets.PYPI_TOKEN }}
|
||||
speakeasy_api_key: ${{ secrets.SPEAKEASY_API_KEY }}
|
||||
|
||||
resolve-branch:
|
||||
needs: generate
|
||||
if: ${{ !cancelled() && needs.generate.result == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
branch_name: ${{ steps.branch.outputs.branch_name }}
|
||||
run_started_at: ${{ steps.branch.outputs.run_started_at }}
|
||||
steps:
|
||||
- name: Extract branch from Generate logs
|
||||
id: branch
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
REPO="${{ github.repository }}"
|
||||
RUN_ID="${{ github.run_id }}"
|
||||
|
||||
RUN_STARTED="${{ github.run_started_at }}"
|
||||
if [ -z "$RUN_STARTED" ]; then
|
||||
RUN_STARTED=$(gh run view "$RUN_ID" --repo "$REPO" --json startedAt --jq '.startedAt')
|
||||
echo "Resolved run_started_at from API: $RUN_STARTED"
|
||||
fi
|
||||
echo "run_started_at=$RUN_STARTED" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Full-run logs are unavailable while the workflow is in progress;
|
||||
# fetch logs from the completed generate job instead.
|
||||
JOB_ID=$(gh run view "$RUN_ID" --repo "$REPO" --json jobs --jq \
|
||||
'[.jobs[] | select(.name == "generate / Generate Target")] | .[0].databaseId // empty')
|
||||
|
||||
BRANCH=""
|
||||
if [ -z "$JOB_ID" ]; then
|
||||
echo "::warning::Could not find generate job id — auto-merge will use run_started_at fallback"
|
||||
else
|
||||
MAX_ATTEMPTS=12
|
||||
INTERVAL=10
|
||||
for attempt in $(seq 1 "$MAX_ATTEMPTS"); do
|
||||
BRANCH=$(gh run view "$RUN_ID" --repo "$REPO" --job "$JOB_ID" --log 2>/dev/null \
|
||||
| grep -oE 'branch_name=speakeasy-sdk-regen-[0-9]+' | tail -1 | cut -d= -f2 || true)
|
||||
if [ -n "$BRANCH" ]; then
|
||||
echo "Extracted branch_name=$BRANCH (attempt $attempt)"
|
||||
break
|
||||
fi
|
||||
if [ "$attempt" -lt "$MAX_ATTEMPTS" ]; then
|
||||
echo "Job logs not ready — waiting ${INTERVAL}s (attempt $attempt/$MAX_ATTEMPTS)..."
|
||||
sleep "$INTERVAL"
|
||||
fi
|
||||
done
|
||||
if [ -z "$BRANCH" ]; then
|
||||
echo "::warning::Could not extract branch_name from Generate logs after ${MAX_ATTEMPTS} attempts — auto-merge will use run_started_at fallback"
|
||||
fi
|
||||
fi
|
||||
echo "branch_name=$BRANCH" >> "$GITHUB_OUTPUT"
|
||||
|
||||
auto-merge:
|
||||
needs: [generate, resolve-branch]
|
||||
if: ${{ !cancelled() && needs.generate.result == 'success' }}
|
||||
uses: ./.github/workflows/auto-merge-speakeasy-pr.yaml
|
||||
with:
|
||||
run_started_at: ${{ needs.resolve-branch.outputs.run_started_at }}
|
||||
branch_name: ${{ needs.resolve-branch.outputs.branch_name }}
|
||||
secrets:
|
||||
GH_DOCS_SYNC_APP_ID: ${{ secrets.GH_DOCS_SYNC_APP_ID }}
|
||||
GH_DOCS_SYNC_APP_PRIVATE_KEY: ${{ secrets.GH_DOCS_SYNC_APP_PRIVATE_KEY }}
|
||||
+5684
-649
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -32,7 +32,7 @@ generation:
|
||||
skipResponseBodyAssertions: false
|
||||
preApplyUnionDiscriminators: true
|
||||
python:
|
||||
version: 0.9.0
|
||||
version: 0.10.8
|
||||
additionalDependencies:
|
||||
dev: {}
|
||||
main: {}
|
||||
|
||||
+15876
-979
File diff suppressed because it is too large
Load Diff
+15662
-959
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,10 @@
|
||||
overlay: 1.0.0
|
||||
x-speakeasy-jsonpath: rfc9535
|
||||
info:
|
||||
title: Fix nullable pagination params
|
||||
version: 0.0.0
|
||||
actions:
|
||||
- target: $..parameters[?@.name == "offset" && @.in == "query"].schema
|
||||
description: Remove nullable from offset query params to fix mypy errors in pagination helpers
|
||||
update:
|
||||
nullable: false
|
||||
@@ -2,20 +2,20 @@ speakeasyVersion: 1.680.0
|
||||
sources:
|
||||
OpenRouter API:
|
||||
sourceNamespace: open-router-chat-completions-api
|
||||
sourceRevisionDigest: sha256:17976e34475ee87867828c00c8e2d0c66ebb004832cf9c34b937c70b2887fafb
|
||||
sourceBlobDigest: sha256:1e517208c3664b60ade61442469e33564727eb61906514aab26d32cac4cd8ebe
|
||||
sourceRevisionDigest: sha256:ed6981b24a0f8df827afac0f83d7dae4d8f7df331ae6e72664e03800cb7a0244
|
||||
sourceBlobDigest: sha256:5961e537bd3160eb3f541232a5e7cb43704fed5e9ce76b342c08f6c52d4fefe9
|
||||
tags:
|
||||
- latest
|
||||
- speakeasy-sdk-regen-1775954251
|
||||
- speakeasy-sdk-regen-1782660460
|
||||
- 1.0.0
|
||||
targets:
|
||||
open-router:
|
||||
source: OpenRouter API
|
||||
sourceNamespace: open-router-chat-completions-api
|
||||
sourceRevisionDigest: sha256:17976e34475ee87867828c00c8e2d0c66ebb004832cf9c34b937c70b2887fafb
|
||||
sourceBlobDigest: sha256:1e517208c3664b60ade61442469e33564727eb61906514aab26d32cac4cd8ebe
|
||||
sourceRevisionDigest: sha256:ed6981b24a0f8df827afac0f83d7dae4d8f7df331ae6e72664e03800cb7a0244
|
||||
sourceBlobDigest: sha256:5961e537bd3160eb3f541232a5e7cb43704fed5e9ce76b342c08f6c52d4fefe9
|
||||
codeSamplesNamespace: open-router-python-code-samples
|
||||
codeSamplesRevisionDigest: sha256:51de2c56d26b7522fc0e0774cfc6eb2e7d79a32d463ab345c7b5194e513e9060
|
||||
codeSamplesRevisionDigest: sha256:d3f20480ea1c0bcb8d872ae696b7a8b2c16d1469ee95b6df12b03b7004ce1c9c
|
||||
workflow:
|
||||
workflowVersion: 1.0.0
|
||||
speakeasyVersion: 1.680.0
|
||||
@@ -29,6 +29,7 @@ workflow:
|
||||
- location: .speakeasy/overlays/add-headers.overlay.yaml
|
||||
- location: .speakeasy/overlays/allof-simplify.overlay.yaml
|
||||
- location: .speakeasy/overlays/boolean-query-params.overlay.yaml
|
||||
- location: .speakeasy/overlays/fix-nullable-pagination.overlay.yaml
|
||||
output: .speakeasy/out.openapi.yaml
|
||||
registry:
|
||||
location: registry.speakeasyapi.dev/openrouter/sdk/open-router-chat-completions-api
|
||||
|
||||
@@ -10,6 +10,7 @@ sources:
|
||||
- location: .speakeasy/overlays/add-headers.overlay.yaml
|
||||
- location: .speakeasy/overlays/allof-simplify.overlay.yaml
|
||||
- location: .speakeasy/overlays/boolean-query-params.overlay.yaml
|
||||
- location: .speakeasy/overlays/fix-nullable-pagination.overlay.yaml
|
||||
output: .speakeasy/out.openapi.yaml
|
||||
registry:
|
||||
location: registry.speakeasyapi.dev/openrouter/sdk/open-router-chat-completions-api
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# OpenRouter Python SDK
|
||||
|
||||
The OpenRouter Python SDK is a type-safe toolkit for building AI applications with access to 300+ language models through a unified API.
|
||||
The OpenRouter Python SDK is a type-safe toolkit for building AI applications with access to 400+ language models through a unified API.
|
||||
|
||||
## Why use the OpenRouter SDK?
|
||||
|
||||
|
||||
+37
-10
@@ -1,6 +1,6 @@
|
||||
# OpenRouter SDK (Beta)
|
||||
# OpenRouter SDK
|
||||
|
||||
The [OpenRouter SDK](https://openrouter.ai/docs/sdks/python) is a Python toolkit designed to help you build AI-powered features and solutions. Giving you easy access to over 300 models across providers in an easy and type-safe way.
|
||||
The [OpenRouter SDK](https://openrouter.ai/docs/sdks/python) is a Python toolkit designed to help you build AI-powered features and solutions. Giving you easy access to 400+ models across providers in an easy and type-safe way.
|
||||
|
||||
To learn more about how to use the OpenRouter SDK, check out our [API Reference](https://openrouter.ai/docs/sdks/python/reference) and [Documentation](https://openrouter.ai/docs/sdks/python).
|
||||
|
||||
@@ -189,7 +189,7 @@ with OpenRouter(
|
||||
api_key=os.getenv("OPENROUTER_API_KEY", ""),
|
||||
) as open_router:
|
||||
|
||||
res = open_router.guardrails.list()
|
||||
res = open_router.byok.list()
|
||||
|
||||
while res is not None:
|
||||
# Handle items
|
||||
@@ -199,6 +199,39 @@ with OpenRouter(
|
||||
```
|
||||
<!-- End Pagination [pagination] -->
|
||||
|
||||
<!-- Start File uploads [file-upload] -->
|
||||
## File uploads
|
||||
|
||||
Certain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
|
||||
|
||||
> [!TIP]
|
||||
>
|
||||
> For endpoints that handle file uploads bytes arrays can also be used. However, using streams is recommended for large files.
|
||||
>
|
||||
|
||||
```python
|
||||
from openrouter import OpenRouter
|
||||
import os
|
||||
|
||||
|
||||
with OpenRouter(
|
||||
http_referer="<value>",
|
||||
x_open_router_title="<value>",
|
||||
x_open_router_categories="<value>",
|
||||
api_key=os.getenv("OPENROUTER_API_KEY", ""),
|
||||
) as open_router:
|
||||
|
||||
res = open_router.files.upload(file={
|
||||
"file_name": "example.file",
|
||||
"content": open("example.file", "rb"),
|
||||
})
|
||||
|
||||
# Handle response
|
||||
print(res)
|
||||
|
||||
```
|
||||
<!-- End File uploads [file-upload] -->
|
||||
|
||||
<!-- Start Resource Management [resource-management] -->
|
||||
## Resource Management
|
||||
|
||||
@@ -276,10 +309,4 @@ To run the test suite, you'll need to set up your environment with an OpenRouter
|
||||
|
||||
```bash
|
||||
pytest
|
||||
```
|
||||
|
||||
## Maturity
|
||||
|
||||
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage
|
||||
to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally
|
||||
looking for the latest version.
|
||||
```
|
||||
@@ -1,6 +1,6 @@
|
||||
# OpenRouter SDK (Beta)
|
||||
# OpenRouter SDK
|
||||
|
||||
The [OpenRouter SDK](https://openrouter.ai/docs/sdks/python) is a Python toolkit designed to help you build AI-powered features and solutions. Giving you easy access to over 300 models across providers in an easy and type-safe way.
|
||||
The [OpenRouter SDK](https://openrouter.ai/docs/sdks/python) is a Python toolkit designed to help you build AI-powered features and solutions. Giving you easy access to 400+ models across providers in an easy and type-safe way.
|
||||
|
||||
To learn more about how to use the OpenRouter SDK, check out our [API Reference](https://openrouter.ai/docs/sdks/python/reference) and [Documentation](https://openrouter.ai/docs/sdks/python).
|
||||
|
||||
@@ -189,7 +189,7 @@ with OpenRouter(
|
||||
api_key=os.getenv("OPENROUTER_API_KEY", ""),
|
||||
) as open_router:
|
||||
|
||||
res = open_router.guardrails.list()
|
||||
res = open_router.byok.list()
|
||||
|
||||
while res is not None:
|
||||
# Handle items
|
||||
@@ -199,6 +199,39 @@ with OpenRouter(
|
||||
```
|
||||
<!-- End Pagination [pagination] -->
|
||||
|
||||
<!-- Start File uploads [file-upload] -->
|
||||
## File uploads
|
||||
|
||||
Certain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
|
||||
|
||||
> [!TIP]
|
||||
>
|
||||
> For endpoints that handle file uploads bytes arrays can also be used. However, using streams is recommended for large files.
|
||||
>
|
||||
|
||||
```python
|
||||
from openrouter import OpenRouter
|
||||
import os
|
||||
|
||||
|
||||
with OpenRouter(
|
||||
http_referer="<value>",
|
||||
x_open_router_title="<value>",
|
||||
x_open_router_categories="<value>",
|
||||
api_key=os.getenv("OPENROUTER_API_KEY", ""),
|
||||
) as open_router:
|
||||
|
||||
res = open_router.files.upload(file={
|
||||
"file_name": "example.file",
|
||||
"content": open("example.file", "rb"),
|
||||
})
|
||||
|
||||
# Handle response
|
||||
print(res)
|
||||
|
||||
```
|
||||
<!-- End File uploads [file-upload] -->
|
||||
|
||||
<!-- Start Resource Management [resource-management] -->
|
||||
## Resource Management
|
||||
|
||||
@@ -276,10 +309,4 @@ To run the test suite, you'll need to set up your environment with an OpenRouter
|
||||
|
||||
```bash
|
||||
pytest
|
||||
```
|
||||
|
||||
## Maturity
|
||||
|
||||
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage
|
||||
to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally
|
||||
looking for the latest version.
|
||||
```
|
||||
+93
-3
@@ -10,12 +10,102 @@ Based on:
|
||||
### Releases
|
||||
- [PyPI v0.0.16] https://pypi.org/project/openrouter/0.0.16 - .
|
||||
|
||||
## 2026-04-14 00:39:13
|
||||
## 2026-06-11 00:55:55
|
||||
### Changes
|
||||
Based on:
|
||||
- OpenAPI Doc
|
||||
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
|
||||
### Generated
|
||||
- [python v0.9.0] .
|
||||
- [python v0.9.2] .
|
||||
### Releases
|
||||
- [PyPI v0.9.0] https://pypi.org/project/openrouter/0.9.0 - .
|
||||
- [PyPI v0.9.2] https://pypi.org/project/openrouter/0.9.2 - .
|
||||
|
||||
## 2026-06-17 00:59:07
|
||||
### Changes
|
||||
Based on:
|
||||
- OpenAPI Doc
|
||||
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
|
||||
### Generated
|
||||
- [python v0.10.0] .
|
||||
### Releases
|
||||
- [PyPI v0.10.0] https://pypi.org/project/openrouter/0.10.0 - .
|
||||
|
||||
## 2026-06-25 21:56:51
|
||||
### Changes
|
||||
Based on:
|
||||
- OpenAPI Doc
|
||||
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
|
||||
### Generated
|
||||
- [python v0.10.1] .
|
||||
### Releases
|
||||
- [PyPI v0.10.1] https://pypi.org/project/openrouter/0.10.1 - .
|
||||
|
||||
## 2026-06-25 22:28:38
|
||||
### Changes
|
||||
Based on:
|
||||
- OpenAPI Doc
|
||||
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
|
||||
### Generated
|
||||
- [python v0.10.2] .
|
||||
### Releases
|
||||
- [PyPI v0.10.2] https://pypi.org/project/openrouter/0.10.2 - .
|
||||
|
||||
## 2026-06-26 00:15:50
|
||||
### Changes
|
||||
Based on:
|
||||
- OpenAPI Doc
|
||||
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
|
||||
### Generated
|
||||
- [python v0.10.3] .
|
||||
### Releases
|
||||
- [PyPI v0.10.3] https://pypi.org/project/openrouter/0.10.3 - .
|
||||
|
||||
## 2026-06-26 12:06:01
|
||||
### Changes
|
||||
Based on:
|
||||
- OpenAPI Doc
|
||||
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
|
||||
### Generated
|
||||
- [python v0.10.4] .
|
||||
### Releases
|
||||
- [PyPI v0.10.4] https://pypi.org/project/openrouter/0.10.4 - .
|
||||
|
||||
## 2026-06-26 14:36:56
|
||||
### Changes
|
||||
Based on:
|
||||
- OpenAPI Doc
|
||||
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
|
||||
### Generated
|
||||
- [python v0.10.5] .
|
||||
### Releases
|
||||
- [PyPI v0.10.5] https://pypi.org/project/openrouter/0.10.5 - .
|
||||
|
||||
## 2026-06-26 18:19:11
|
||||
### Changes
|
||||
Based on:
|
||||
- OpenAPI Doc
|
||||
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
|
||||
### Generated
|
||||
- [python v0.10.6] .
|
||||
### Releases
|
||||
- [PyPI v0.10.6] https://pypi.org/project/openrouter/0.10.6 - .
|
||||
|
||||
## 2026-06-26 23:43:40
|
||||
### Changes
|
||||
Based on:
|
||||
- OpenAPI Doc
|
||||
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
|
||||
### Generated
|
||||
- [python v0.10.7] .
|
||||
### Releases
|
||||
- [PyPI v0.10.7] https://pypi.org/project/openrouter/0.10.7 - .
|
||||
|
||||
## 2026-06-28 15:27:21
|
||||
### Changes
|
||||
Based on:
|
||||
- OpenAPI Doc
|
||||
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
|
||||
### Generated
|
||||
- [python v0.10.8] .
|
||||
### Releases
|
||||
- [PyPI v0.10.8] https://pypi.org/project/openrouter/0.10.8 - .
|
||||
@@ -1,13 +0,0 @@
|
||||
# CompletionTokensDetails
|
||||
|
||||
Detailed completion token usage
|
||||
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ---------------------------- | ---------------------------- | ---------------------------- | ---------------------------- |
|
||||
| `accepted_prediction_tokens` | *Optional[int]* | :heavy_minus_sign: | Accepted prediction tokens |
|
||||
| `audio_tokens` | *Optional[int]* | :heavy_minus_sign: | Tokens used for audio output |
|
||||
| `reasoning_tokens` | *Optional[int]* | :heavy_minus_sign: | Tokens used for reasoning |
|
||||
| `rejected_prediction_tokens` | *Optional[int]* | :heavy_minus_sign: | Rejected prediction tokens |
|
||||
@@ -1,10 +1,12 @@
|
||||
# CostDetails
|
||||
|
||||
Breakdown of upstream inference costs
|
||||
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- |
|
||||
| `upstream_inference_cost` | *Optional[float]* | :heavy_minus_sign: | N/A |
|
||||
| `upstream_inference_input_cost` | *float* | :heavy_check_mark: | N/A |
|
||||
| `upstream_inference_output_cost` | *float* | :heavy_check_mark: | N/A |
|
||||
| Field | Type | Required | Description |
|
||||
| ------------------------------------- | ------------------------------------- | ------------------------------------- | ------------------------------------- |
|
||||
| `upstream_inference_completions_cost` | *float* | :heavy_check_mark: | N/A |
|
||||
| `upstream_inference_cost` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
|
||||
| `upstream_inference_prompt_cost` | *float* | :heavy_check_mark: | N/A |
|
||||
@@ -1,10 +0,0 @@
|
||||
# Data
|
||||
|
||||
Model count data
|
||||
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- |
|
||||
| `count` | *int* | :heavy_check_mark: | Total number of available models | 150 |
|
||||
@@ -5,11 +5,11 @@ Default parameters for this model
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ----------------------- | ----------------------- | ----------------------- | ----------------------- |
|
||||
| `frequency_penalty` | *Optional[float]* | :heavy_minus_sign: | N/A |
|
||||
| `presence_penalty` | *Optional[float]* | :heavy_minus_sign: | N/A |
|
||||
| `repetition_penalty` | *Optional[float]* | :heavy_minus_sign: | N/A |
|
||||
| `temperature` | *Optional[float]* | :heavy_minus_sign: | N/A |
|
||||
| `top_k` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A |
|
||||
| `top_p` | *Optional[float]* | :heavy_minus_sign: | N/A |
|
||||
| Field | Type | Required | Description |
|
||||
| ------------------------- | ------------------------- | ------------------------- | ------------------------- |
|
||||
| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
|
||||
| `presence_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
|
||||
| `repetition_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
|
||||
| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
|
||||
| `top_k` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A |
|
||||
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
|
||||
@@ -1,15 +0,0 @@
|
||||
# Effort
|
||||
|
||||
Constrains effort on reasoning for reasoning models
|
||||
|
||||
|
||||
## Values
|
||||
|
||||
| Name | Value |
|
||||
| --------- | --------- |
|
||||
| `XHIGH` | xhigh |
|
||||
| `HIGH` | high |
|
||||
| `MEDIUM` | medium |
|
||||
| `LOW` | low |
|
||||
| `MINIMAL` | minimal |
|
||||
| `NONE` | none |
|
||||
@@ -1,11 +0,0 @@
|
||||
# Error
|
||||
|
||||
Error information
|
||||
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------- | ------------------- | ------------------- | ------------------- | ------------------- |
|
||||
| `code` | *int* | :heavy_check_mark: | Error code | 429 |
|
||||
| `message` | *str* | :heavy_check_mark: | Error message | Rate limit exceeded |
|
||||
+21
-18
@@ -5,21 +5,24 @@ Information about an AI model available on OpenRouter
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `architecture` | [components.ModelArchitecture](../components/modelarchitecture.md) | :heavy_check_mark: | Model architecture information | {<br/>"input_modalities": [<br/>"text"<br/>],<br/>"instruct_type": "chatml",<br/>"modality": "text-\u003etext",<br/>"output_modalities": [<br/>"text"<br/>],<br/>"tokenizer": "GPT"<br/>} |
|
||||
| `canonical_slug` | *str* | :heavy_check_mark: | Canonical slug for the model | openai/gpt-4 |
|
||||
| `context_length` | *int* | :heavy_check_mark: | Maximum context length in tokens | 8192 |
|
||||
| `created` | *int* | :heavy_check_mark: | Unix timestamp of when the model was created | 1692901234 |
|
||||
| `default_parameters` | [Nullable[components.DefaultParameters]](../components/defaultparameters.md) | :heavy_check_mark: | Default parameters for this model | {<br/>"frequency_penalty": 0,<br/>"presence_penalty": 0,<br/>"repetition_penalty": 1,<br/>"temperature": 0.7,<br/>"top_k": 0,<br/>"top_p": 0.9<br/>} |
|
||||
| `description` | *Optional[str]* | :heavy_minus_sign: | Description of the model | GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. |
|
||||
| `expiration_date` | *OptionalNullable[str]* | :heavy_minus_sign: | The date after which the model may be removed. ISO 8601 date string (YYYY-MM-DD) or null if no expiration. | 2025-06-01 |
|
||||
| `hugging_face_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Hugging Face model identifier, if applicable | microsoft/DialoGPT-medium |
|
||||
| `id` | *str* | :heavy_check_mark: | Unique identifier for the model | openai/gpt-4 |
|
||||
| `knowledge_cutoff` | *OptionalNullable[str]* | :heavy_minus_sign: | The date up to which the model was trained on data. ISO 8601 date string (YYYY-MM-DD) or null if unknown. | 2024-10-01 |
|
||||
| `links` | [components.ModelLinks](../components/modellinks.md) | :heavy_check_mark: | Related API endpoints and resources for this model. | {<br/>"details": "/api/v1/models/openai/gpt-5.4/endpoints"<br/>} |
|
||||
| `name` | *str* | :heavy_check_mark: | Display name of the model | GPT-4 |
|
||||
| `per_request_limits` | [Nullable[components.PerRequestLimits]](../components/perrequestlimits.md) | :heavy_check_mark: | Per-request token limits | {<br/>"completion_tokens": 1000,<br/>"prompt_tokens": 1000<br/>} |
|
||||
| `pricing` | [components.PublicPricing](../components/publicpricing.md) | :heavy_check_mark: | Pricing information for the model | {<br/>"completion": "0.00006",<br/>"image": "0",<br/>"prompt": "0.00003",<br/>"request": "0"<br/>} |
|
||||
| `supported_parameters` | List[[components.Parameter](../components/parameter.md)] | :heavy_check_mark: | List of supported parameters for this model | |
|
||||
| `top_provider` | [components.TopProviderInfo](../components/topproviderinfo.md) | :heavy_check_mark: | Information about the top provider for this model | {<br/>"context_length": 8192,<br/>"is_moderated": true,<br/>"max_completion_tokens": 4096<br/>} |
|
||||
| Field | Type | Required | Description | Example |
|
||||
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `architecture` | [components.ModelArchitecture](../components/modelarchitecture.md) | :heavy_check_mark: | Model architecture information | {<br/>"input_modalities": [<br/>"text"<br/>],<br/>"instruct_type": "chatml",<br/>"modality": "text-\u003etext",<br/>"output_modalities": [<br/>"text"<br/>],<br/>"tokenizer": "GPT"<br/>} |
|
||||
| `benchmarks` | [Optional[components.ModelBenchmarks]](../components/modelbenchmarks.md) | :heavy_minus_sign: | Third-party benchmark rankings for this model. Omitted when no benchmark data is available. | {<br/>"artificial_analysis": {<br/>"agentic_index": 55.8,<br/>"coding_index": 63.2,<br/>"intelligence_index": 71.4<br/>},<br/>"design_arena": [<br/>{<br/>"arena": "models",<br/>"category": "website",<br/>"elo": 1385.2,<br/>"rank": 5,<br/>"win_rate": 62.5<br/>}<br/>]<br/>} |
|
||||
| `canonical_slug` | *str* | :heavy_check_mark: | Canonical slug for the model | openai/gpt-4 |
|
||||
| `context_length` | *Nullable[int]* | :heavy_check_mark: | Maximum context length in tokens | 8192 |
|
||||
| `created` | *int* | :heavy_check_mark: | Unix timestamp of when the model was created | 1692901234 |
|
||||
| `default_parameters` | [Nullable[components.DefaultParameters]](../components/defaultparameters.md) | :heavy_check_mark: | Default parameters for this model | {<br/>"frequency_penalty": 0,<br/>"presence_penalty": 0,<br/>"repetition_penalty": 1,<br/>"temperature": 0.7,<br/>"top_k": 0,<br/>"top_p": 0.9<br/>} |
|
||||
| `description` | *Optional[str]* | :heavy_minus_sign: | Description of the model | GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. |
|
||||
| `expiration_date` | *OptionalNullable[str]* | :heavy_minus_sign: | The date after which the model may be removed. ISO 8601 date string (YYYY-MM-DD) or null if no expiration. | 2025-06-01 |
|
||||
| `hugging_face_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Hugging Face model identifier, if applicable | microsoft/DialoGPT-medium |
|
||||
| `id` | *str* | :heavy_check_mark: | Unique identifier for the model | openai/gpt-4 |
|
||||
| `knowledge_cutoff` | *OptionalNullable[str]* | :heavy_minus_sign: | The date up to which the model was trained on data. ISO 8601 date string (YYYY-MM-DD) or null if unknown. | 2024-10-01 |
|
||||
| `links` | [components.ModelLinks](../components/modellinks.md) | :heavy_check_mark: | Related API endpoints and resources for this model. | {<br/>"details": "/api/v1/models/openai/gpt-5.4/endpoints"<br/>} |
|
||||
| `name` | *str* | :heavy_check_mark: | Display name of the model | GPT-4 |
|
||||
| `per_request_limits` | [Nullable[components.PerRequestLimits]](../components/perrequestlimits.md) | :heavy_check_mark: | Per-request token limits | {<br/>"completion_tokens": 1000,<br/>"prompt_tokens": 1000<br/>} |
|
||||
| `pricing` | [components.PublicPricing](../components/publicpricing.md) | :heavy_check_mark: | Pricing information for the model | {<br/>"completion": "0.00006",<br/>"image": "0",<br/>"prompt": "0.00003",<br/>"request": "0"<br/>} |
|
||||
| `reasoning` | [Optional[components.ModelReasoning]](../components/modelreasoning.md) | :heavy_minus_sign: | Reasoning effort configuration. Omitted for non-reasoning models and dynamic router models. | {<br/>"default_effort": "medium",<br/>"default_enabled": true,<br/>"mandatory": false,<br/>"supported_efforts": [<br/>"high",<br/>"medium",<br/>"low",<br/>"minimal"<br/>]<br/>} |
|
||||
| `supported_parameters` | List[[components.Parameter](../components/parameter.md)] | :heavy_check_mark: | List of supported parameters for this model | |
|
||||
| `supported_voices` | List[*str*] | :heavy_check_mark: | List of supported voice identifiers for TTS models. Null for non-TTS models. | <nil> |
|
||||
| `top_provider` | [components.TopProviderInfo](../components/topproviderinfo.md) | :heavy_check_mark: | Information about the top provider for this model | {<br/>"context_length": 8192,<br/>"is_moderated": true,<br/>"max_completion_tokens": 4096<br/>} |
|
||||
@@ -5,6 +5,6 @@ Model count data
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
|
||||
| `data` | [components.Data](../components/data.md) | :heavy_check_mark: | Model count data | {<br/>"count": 150<br/>} |
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
|
||||
| `data` | [components.ModelsCountResponseData](../components/modelscountresponsedata.md) | :heavy_check_mark: | Model count data | {<br/>"count": 150<br/>} |
|
||||
@@ -5,6 +5,6 @@ List of available models
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `data` | List[[components.Model](../components/model.md)] | :heavy_check_mark: | List of available models | [<br/>{<br/>"architecture": {<br/>"input_modalities": [<br/>"text"<br/>],<br/>"instruct_type": "chatml",<br/>"modality": "text-\u003etext",<br/>"output_modalities": [<br/>"text"<br/>],<br/>"tokenizer": "GPT"<br/>},<br/>"canonical_slug": "openai/gpt-4",<br/>"context_length": 8192,<br/>"created": 1692901234,<br/>"default_parameters": null,<br/>"description": "GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy.",<br/>"expiration_date": null,<br/>"id": "openai/gpt-4",<br/>"knowledge_cutoff": null,<br/>"links": {<br/>"details": "/api/v1/models/openai/gpt-5.4/endpoints"<br/>},<br/>"name": "GPT-4",<br/>"per_request_limits": null,<br/>"pricing": {<br/>"completion": "0.00006",<br/>"image": "0",<br/>"prompt": "0.00003",<br/>"request": "0"<br/>},<br/>"supported_parameters": [<br/>"temperature",<br/>"top_p",<br/>"max_tokens"<br/>],<br/>"top_provider": {<br/>"context_length": 8192,<br/>"is_moderated": true,<br/>"max_completion_tokens": 4096<br/>}<br/>}<br/>] |
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `data` | List[[components.Model](../components/model.md)] | :heavy_check_mark: | List of available models | [<br/>{<br/>"architecture": {<br/>"input_modalities": [<br/>"text"<br/>],<br/>"instruct_type": "chatml",<br/>"modality": "text-\u003etext",<br/>"output_modalities": [<br/>"text"<br/>],<br/>"tokenizer": "GPT"<br/>},<br/>"canonical_slug": "openai/gpt-4",<br/>"context_length": 8192,<br/>"created": 1692901234,<br/>"default_parameters": null,<br/>"description": "GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy.",<br/>"expiration_date": null,<br/>"id": "openai/gpt-4",<br/>"knowledge_cutoff": null,<br/>"links": {<br/>"details": "/api/v1/models/openai/gpt-5.4/endpoints"<br/>},<br/>"name": "GPT-4",<br/>"per_request_limits": null,<br/>"pricing": {<br/>"completion": "0.00006",<br/>"image": "0",<br/>"prompt": "0.00003",<br/>"request": "0"<br/>},<br/>"supported_parameters": [<br/>"temperature",<br/>"top_p",<br/>"max_tokens"<br/>],<br/>"supported_voices": null,<br/>"top_provider": {<br/>"context_length": 8192,<br/>"is_moderated": true,<br/>"max_completion_tokens": 4096<br/>}<br/>}<br/>] |
|
||||
@@ -39,3 +39,15 @@ value: components.OpenAIResponsesToolChoice = /* values here */
|
||||
value: components.ToolChoiceAllowed = /* values here */
|
||||
```
|
||||
|
||||
### `components.OpenAIResponsesToolChoiceApplyPatch`
|
||||
|
||||
```python
|
||||
value: components.OpenAIResponsesToolChoiceApplyPatch = /* values here */
|
||||
```
|
||||
|
||||
### `components.OpenAIResponsesToolChoiceShell`
|
||||
|
||||
```python
|
||||
value: components.OpenAIResponsesToolChoiceShell = /* values here */
|
||||
```
|
||||
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
|
||||
## Values
|
||||
|
||||
| Name | Value |
|
||||
| ------------ | ------------ |
|
||||
| `TEXT` | text |
|
||||
| `IMAGE` | image |
|
||||
| `EMBEDDINGS` | embeddings |
|
||||
| `AUDIO` | audio |
|
||||
| `VIDEO` | video |
|
||||
| `RERANK` | rerank |
|
||||
| Name | Value |
|
||||
| --------------- | --------------- |
|
||||
| `TEXT` | text |
|
||||
| `IMAGE` | image |
|
||||
| `EMBEDDINGS` | embeddings |
|
||||
| `AUDIO` | audio |
|
||||
| `VIDEO` | video |
|
||||
| `RERANK` | rerank |
|
||||
| `SPEECH` | speech |
|
||||
| `TRANSCRIPTION` | transcription |
|
||||
@@ -7,7 +7,7 @@ Percentile-based latency cutoffs. All specified cutoffs must be met for an endpo
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ----------------------------- | ----------------------------- | ----------------------------- | ----------------------------- |
|
||||
| `p50` | *Optional[float]* | :heavy_minus_sign: | Maximum p50 latency (seconds) |
|
||||
| `p75` | *Optional[float]* | :heavy_minus_sign: | Maximum p75 latency (seconds) |
|
||||
| `p90` | *Optional[float]* | :heavy_minus_sign: | Maximum p90 latency (seconds) |
|
||||
| `p99` | *Optional[float]* | :heavy_minus_sign: | Maximum p99 latency (seconds) |
|
||||
| `p50` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum p50 latency (seconds) |
|
||||
| `p75` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum p75 latency (seconds) |
|
||||
| `p90` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum p90 latency (seconds) |
|
||||
| `p99` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum p99 latency (seconds) |
|
||||
@@ -7,7 +7,7 @@ Percentile-based throughput cutoffs. All specified cutoffs must be met for an en
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ----------------------------------- | ----------------------------------- | ----------------------------------- | ----------------------------------- |
|
||||
| `p50` | *Optional[float]* | :heavy_minus_sign: | Minimum p50 throughput (tokens/sec) |
|
||||
| `p75` | *Optional[float]* | :heavy_minus_sign: | Minimum p75 throughput (tokens/sec) |
|
||||
| `p90` | *Optional[float]* | :heavy_minus_sign: | Minimum p90 throughput (tokens/sec) |
|
||||
| `p99` | *Optional[float]* | :heavy_minus_sign: | Minimum p99 throughput (tokens/sec) |
|
||||
| `p50` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum p50 throughput (tokens/sec) |
|
||||
| `p75` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum p75 throughput (tokens/sec) |
|
||||
| `p90` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum p90 throughput (tokens/sec) |
|
||||
| `p99` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum p99 throughput (tokens/sec) |
|
||||
+17
-16
@@ -3,19 +3,20 @@
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| -------------------- | -------------------- | -------------------- | -------------------- | -------------------- |
|
||||
| `audio` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `audio_output` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `completion` | *str* | :heavy_check_mark: | N/A | 1000 |
|
||||
| `discount` | *Optional[float]* | :heavy_minus_sign: | N/A | |
|
||||
| `image` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `image_output` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `image_token` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `input_audio_cache` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `input_cache_read` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `input_cache_write` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `internal_reasoning` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `prompt` | *str* | :heavy_check_mark: | N/A | 1000 |
|
||||
| `request` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `web_search` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| Field | Type | Required | Description |
|
||||
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `audio` | *Optional[str]* | :heavy_minus_sign: | Price in USD per audio input token |
|
||||
| `audio_output` | *Optional[str]* | :heavy_minus_sign: | Price in USD per audio output token |
|
||||
| `completion` | *str* | :heavy_check_mark: | Price in USD per token for completion (output) generation |
|
||||
| `discount` | *Optional[float]* | :heavy_minus_sign: | Fractional discount applied to this endpoint's pricing; the price is multiplied by (1 - discount) (0 = no discount, 1 = free) |
|
||||
| `image` | *Optional[str]* | :heavy_minus_sign: | Price in USD per input image |
|
||||
| `image_output` | *Optional[str]* | :heavy_minus_sign: | Price in USD per output image |
|
||||
| `image_token` | *Optional[str]* | :heavy_minus_sign: | Price in USD per image token |
|
||||
| `input_audio_cache` | *Optional[str]* | :heavy_minus_sign: | Price in USD per cached audio input token |
|
||||
| `input_cache_read` | *Optional[str]* | :heavy_minus_sign: | Price in USD per cached input token (read) |
|
||||
| `input_cache_write` | *Optional[str]* | :heavy_minus_sign: | Price per cache-write token, in USD per token. For providers with multiple cache TTLs (e.g. Anthropic), this is the default (5-minute) cache-write rate. |
|
||||
| `input_cache_write_1h` | *Optional[str]* | :heavy_minus_sign: | Price per 1-hour cache-write token, in USD per token. Only present for providers that price an extended (1-hour) cache TTL separately, such as Anthropic. |
|
||||
| `internal_reasoning` | *Optional[str]* | :heavy_minus_sign: | Price in USD per internal reasoning token |
|
||||
| `prompt` | *str* | :heavy_check_mark: | Price in USD per token for prompt (input) processing |
|
||||
| `request` | *Optional[str]* | :heavy_minus_sign: | Price in USD per request |
|
||||
| `web_search` | *Optional[str]* | :heavy_minus_sign: | Price in USD per web search |
|
||||
@@ -1,13 +0,0 @@
|
||||
# PromptTokensDetails
|
||||
|
||||
Detailed prompt token usage
|
||||
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
|
||||
| `audio_tokens` | *Optional[int]* | :heavy_minus_sign: | Audio input tokens |
|
||||
| `cache_write_tokens` | *Optional[int]* | :heavy_minus_sign: | Tokens written to cache. Only returned for models with explicit caching and cache write pricing. |
|
||||
| `cached_tokens` | *Optional[int]* | :heavy_minus_sign: | Cached prompt tokens |
|
||||
| `video_tokens` | *Optional[int]* | :heavy_minus_sign: | Video input tokens |
|
||||
@@ -10,6 +10,7 @@
|
||||
| `AION_LABS` | AionLabs |
|
||||
| `ALIBABA` | Alibaba |
|
||||
| `AMBIENT` | Ambient |
|
||||
| `BAIDU` | Baidu |
|
||||
| `AMAZON_BEDROCK` | Amazon Bedrock |
|
||||
| `AMAZON_NOVA` | Amazon Nova |
|
||||
| `ANTHROPIC` | Anthropic |
|
||||
@@ -26,10 +27,14 @@
|
||||
| `CLARIFAI` | Clarifai |
|
||||
| `CLOUDFLARE` | Cloudflare |
|
||||
| `COHERE` | Cohere |
|
||||
| `CRUCIBLE` | Crucible |
|
||||
| `CRUSOE` | Crusoe |
|
||||
| `DARKBLOOM` | Darkbloom |
|
||||
| `DECART` | Decart |
|
||||
| `DEEP_INFRA` | DeepInfra |
|
||||
| `DEEP_SEEK` | DeepSeek |
|
||||
| `DEKA_LLM` | DekaLLM |
|
||||
| `DIGITAL_OCEAN` | DigitalOcean |
|
||||
| `FEATHERLESS` | Featherless |
|
||||
| `FIREWORKS` | Fireworks |
|
||||
| `FRIENDLI` | Friendli |
|
||||
@@ -37,13 +42,14 @@
|
||||
| `GOOGLE` | Google |
|
||||
| `GOOGLE_AI_STUDIO` | Google AI Studio |
|
||||
| `GROQ` | Groq |
|
||||
| `HYPERBOLIC` | Hyperbolic |
|
||||
| `HEY_GEN` | HeyGen |
|
||||
| `INCEPTION` | Inception |
|
||||
| `INCEPTRON` | Inceptron |
|
||||
| `INFERENCE_NET` | InferenceNet |
|
||||
| `IONSTREAM` | Ionstream |
|
||||
| `INFERMATIC` | Infermatic |
|
||||
| `IO_NET` | Io Net |
|
||||
| `INFERACT_V_LLM` | Inferact vLLM |
|
||||
| `INFLECTION` | Inflection |
|
||||
| `LIQUID` | Liquid |
|
||||
| `MARA` | Mara |
|
||||
@@ -56,17 +62,21 @@
|
||||
| `MORPH` | Morph |
|
||||
| `N_COMPASS` | NCompass |
|
||||
| `NEBIUS` | Nebius |
|
||||
| `NEX_AGI` | Nex AGI |
|
||||
| `NEXT_BIT` | NextBit |
|
||||
| `NOVITA` | Novita |
|
||||
| `NVIDIA` | Nvidia |
|
||||
| `OPEN_AI` | OpenAI |
|
||||
| `OPEN_INFERENCE` | OpenInference |
|
||||
| `PARASAIL` | Parasail |
|
||||
| `POOLSIDE` | Poolside |
|
||||
| `PERCEPTRON` | Perceptron |
|
||||
| `PERPLEXITY` | Perplexity |
|
||||
| `PHALA` | Phala |
|
||||
| `RECRAFT` | Recraft |
|
||||
| `REKA` | Reka |
|
||||
| `RELACE` | Relace |
|
||||
| `SAKANA_AI` | Sakana AI |
|
||||
| `SAMBA_NOVA` | SambaNova |
|
||||
| `SEED` | Seed |
|
||||
| `SILICON_FLOW` | SiliconFlow |
|
||||
@@ -75,10 +85,13 @@
|
||||
| `STEALTH` | Stealth |
|
||||
| `STREAM_LAKE` | StreamLake |
|
||||
| `SWITCHPOINT` | Switchpoint |
|
||||
| `TENSTORRENT` | Tenstorrent |
|
||||
| `TOGETHER` | Together |
|
||||
| `UPSTAGE` | Upstage |
|
||||
| `VENICE` | Venice |
|
||||
| `WAFER` | Wafer |
|
||||
| `WAND_B` | WandB |
|
||||
| `QUIVER` | Quiver |
|
||||
| `XIAOMI` | Xiaomi |
|
||||
| `X_AI` | xAI |
|
||||
| `Z_AI` | Z.AI |
|
||||
|
||||
@@ -9,8 +9,8 @@ Information about a specific model endpoint
|
||||
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `context_length` | *int* | :heavy_check_mark: | N/A | |
|
||||
| `latency_last_30m` | [Nullable[components.PercentileStats]](../components/percentilestats.md) | :heavy_check_mark: | Latency percentiles in milliseconds over the last 30 minutes. Latency measures time to first token. Only visible when authenticated with an API key or cookie; returns null for unauthenticated requests. | {<br/>"p50": 25.5,<br/>"p75": 35.2,<br/>"p90": 48.7,<br/>"p99": 85.3<br/>} |
|
||||
| `max_completion_tokens` | *int* | :heavy_check_mark: | N/A | |
|
||||
| `max_prompt_tokens` | *int* | :heavy_check_mark: | N/A | |
|
||||
| `max_completion_tokens` | *Nullable[int]* | :heavy_check_mark: | N/A | |
|
||||
| `max_prompt_tokens` | *Nullable[int]* | :heavy_check_mark: | N/A | |
|
||||
| `model_id` | *str* | :heavy_check_mark: | The unique identifier for the model (permaslug) | openai/gpt-4 |
|
||||
| `model_name` | *str* | :heavy_check_mark: | N/A | |
|
||||
| `name` | *str* | :heavy_check_mark: | N/A | |
|
||||
@@ -22,6 +22,6 @@ Information about a specific model endpoint
|
||||
| `supports_implicit_caching` | *bool* | :heavy_check_mark: | N/A | |
|
||||
| `tag` | *str* | :heavy_check_mark: | N/A | |
|
||||
| `throughput_last_30m` | [Nullable[components.PercentileStats]](../components/percentilestats.md) | :heavy_check_mark: | N/A | {<br/>"p50": 25.5,<br/>"p75": 35.2,<br/>"p90": 48.7,<br/>"p99": 85.3<br/>} |
|
||||
| `uptime_last_1d` | *float* | :heavy_check_mark: | Uptime percentage over the last 1 day, calculated as successful requests / (successful + error requests) * 100. Rate-limited requests are excluded. Returns null if insufficient data. | |
|
||||
| `uptime_last_30m` | *float* | :heavy_check_mark: | N/A | |
|
||||
| `uptime_last_5m` | *float* | :heavy_check_mark: | Uptime percentage over the last 5 minutes, calculated as successful requests / (successful + error requests) * 100. Rate-limited requests are excluded. Returns null if insufficient data. | |
|
||||
| `uptime_last_1d` | *Nullable[float]* | :heavy_check_mark: | Uptime percentage over the last 1 day, calculated as successful requests / (successful + error requests) * 100. Rate-limited requests are excluded. Returns null if insufficient data. | |
|
||||
| `uptime_last_30m` | *Nullable[float]* | :heavy_check_mark: | N/A | |
|
||||
| `uptime_last_5m` | *Nullable[float]* | :heavy_check_mark: | Uptime percentage over the last 5 minutes, calculated as successful requests / (successful + error requests) * 100. Rate-limited requests are excluded. Returns null if insufficient data. | |
|
||||
@@ -5,19 +5,20 @@ Pricing information for the model
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| -------------------- | -------------------- | -------------------- | -------------------- | -------------------- |
|
||||
| `audio` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `audio_output` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `completion` | *str* | :heavy_check_mark: | N/A | 1000 |
|
||||
| `discount` | *Optional[float]* | :heavy_minus_sign: | N/A | |
|
||||
| `image` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `image_output` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `image_token` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `input_audio_cache` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `input_cache_read` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `input_cache_write` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `internal_reasoning` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `prompt` | *str* | :heavy_check_mark: | N/A | 1000 |
|
||||
| `request` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| `web_search` | *Optional[str]* | :heavy_minus_sign: | N/A | 1000 |
|
||||
| Field | Type | Required | Description |
|
||||
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `audio` | *Optional[str]* | :heavy_minus_sign: | Price in USD per audio input token |
|
||||
| `audio_output` | *Optional[str]* | :heavy_minus_sign: | Price in USD per audio output token |
|
||||
| `completion` | *str* | :heavy_check_mark: | Price in USD per token for completion (output) generation |
|
||||
| `discount` | *Optional[float]* | :heavy_minus_sign: | Fractional discount applied to this endpoint's pricing; the price is multiplied by (1 - discount) (0 = no discount, 1 = free) |
|
||||
| `image` | *Optional[str]* | :heavy_minus_sign: | Price in USD per input image |
|
||||
| `image_output` | *Optional[str]* | :heavy_minus_sign: | Price in USD per output image |
|
||||
| `image_token` | *Optional[str]* | :heavy_minus_sign: | Price in USD per image token |
|
||||
| `input_audio_cache` | *Optional[str]* | :heavy_minus_sign: | Price in USD per cached audio input token |
|
||||
| `input_cache_read` | *Optional[str]* | :heavy_minus_sign: | Price in USD per cached input token (read) |
|
||||
| `input_cache_write` | *Optional[str]* | :heavy_minus_sign: | Price per cache-write token, in USD per token. For providers with multiple cache TTLs (e.g. Anthropic), this is the default (5-minute) cache-write rate. |
|
||||
| `input_cache_write_1h` | *Optional[str]* | :heavy_minus_sign: | Price per 1-hour cache-write token, in USD per token. Only present for providers that price an extended (1-hour) cache TTL separately, such as Anthropic. |
|
||||
| `internal_reasoning` | *Optional[str]* | :heavy_minus_sign: | Price in USD per internal reasoning token |
|
||||
| `prompt` | *str* | :heavy_check_mark: | Price in USD per token for prompt (input) processing |
|
||||
| `request` | *Optional[str]* | :heavy_minus_sign: | Price in USD per request |
|
||||
| `web_search` | *Optional[str]* | :heavy_minus_sign: | Price in USD per web search |
|
||||
@@ -1,11 +0,0 @@
|
||||
# Reasoning
|
||||
|
||||
Configuration options for reasoning models
|
||||
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
|
||||
| `effort` | [OptionalNullable[components.Effort]](../components/effort.md) | :heavy_minus_sign: | Constrains effort on reasoning for reasoning models | medium |
|
||||
| `summary` | [OptionalNullable[components.ChatReasoningSummaryVerbosityEnum]](../components/chatreasoningsummaryverbosityenum.md) | :heavy_minus_sign: | N/A | concise |
|
||||
@@ -7,6 +7,6 @@ Information about the top provider for this model
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ----------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- |
|
||||
| `context_length` | *Optional[int]* | :heavy_minus_sign: | Context length from the top provider | 8192 |
|
||||
| `context_length` | *OptionalNullable[int]* | :heavy_minus_sign: | Context length from the top provider | 8192 |
|
||||
| `is_moderated` | *bool* | :heavy_check_mark: | Whether the top provider moderates content | true |
|
||||
| `max_completion_tokens` | *Optional[int]* | :heavy_minus_sign: | Maximum completion tokens from the top provider | 4096 |
|
||||
| `max_completion_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | Maximum completion tokens from the top provider | 4096 |
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- |
|
||||
| `content` | *Optional[str]* | :heavy_minus_sign: | N/A |
|
||||
| `end_index` | *int* | :heavy_check_mark: | N/A |
|
||||
| `start_index` | *int* | :heavy_check_mark: | N/A |
|
||||
| `title` | *str* | :heavy_check_mark: | N/A |
|
||||
|
||||
@@ -5,9 +5,10 @@ The search engine to use for web search.
|
||||
|
||||
## Values
|
||||
|
||||
| Name | Value |
|
||||
| ----------- | ----------- |
|
||||
| `NATIVE` | native |
|
||||
| `EXA` | exa |
|
||||
| `FIRECRAWL` | firecrawl |
|
||||
| `PARALLEL` | parallel |
|
||||
| Name | Value |
|
||||
| ------------ | ------------ |
|
||||
| `NATIVE` | native |
|
||||
| `EXA` | exa |
|
||||
| `FIRECRAWL` | firecrawl |
|
||||
| `PARALLEL` | parallel |
|
||||
| `PERPLEXITY` | perplexity |
|
||||
@@ -8,4 +8,5 @@ Bad Gateway - Provider/upstream API failure
|
||||
| Field | Type | Required | Description | Example |
|
||||
| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
|
||||
| `error` | [components.BadGatewayResponseErrorData](../components/badgatewayresponseerrordata.md) | :heavy_check_mark: | Error data for BadGatewayResponse | {<br/>"code": 502,<br/>"message": "Provider returned error"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Bad Request - Invalid request parameters or malformed input
|
||||
| Field | Type | Required | Description | Example |
|
||||
| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
|
||||
| `error` | [components.BadRequestResponseErrorData](../components/badrequestresponseerrordata.md) | :heavy_check_mark: | Error data for BadRequestResponse | {<br/>"code": 400,<br/>"message": "Invalid request parameters"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Infrastructure Timeout - Provider request timed out at edge network
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
|
||||
| `error` | [components.EdgeNetworkTimeoutResponseErrorData](../components/edgenetworktimeoutresponseerrordata.md) | :heavy_check_mark: | Error data for EdgeNetworkTimeoutResponse | {<br/>"code": 524,<br/>"message": "Request timed out. Please try again later."<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Forbidden - Authentication successful but insufficient permissions
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ |
|
||||
| `error` | [components.ForbiddenResponseErrorData](../components/forbiddenresponseerrordata.md) | :heavy_check_mark: | Error data for ForbiddenResponse | {<br/>"code": 403,<br/>"message": "Only management keys can perform this operation"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Internal Server Error - Unexpected server error
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
|
||||
| `error` | [components.InternalServerResponseErrorData](../components/internalserverresponseerrordata.md) | :heavy_check_mark: | Error data for InternalServerResponse | {<br/>"code": 500,<br/>"message": "Internal Server Error"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Not Found - Resource does not exist
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
|
||||
| `error` | [components.NotFoundResponseErrorData](../components/notfoundresponseerrordata.md) | :heavy_check_mark: | Error data for NotFoundResponse | {<br/>"code": 404,<br/>"message": "Resource not found"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Payload Too Large - Request payload exceeds size limits
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
|
||||
| `error` | [components.PayloadTooLargeResponseErrorData](../components/payloadtoolargeresponseerrordata.md) | :heavy_check_mark: | Error data for PayloadTooLargeResponse | {<br/>"code": 413,<br/>"message": "Request payload too large"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Payment Required - Insufficient credits or quota to complete request
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
|
||||
| `error` | [components.PaymentRequiredResponseErrorData](../components/paymentrequiredresponseerrordata.md) | :heavy_check_mark: | Error data for PaymentRequiredResponse | {<br/>"code": 402,<br/>"message": "Insufficient credits. Add more using https://openrouter.ai/credits"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Provider Overloaded - Provider is temporarily overloaded
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
|
||||
| `error` | [components.ProviderOverloadedResponseErrorData](../components/provideroverloadedresponseerrordata.md) | :heavy_check_mark: | Error data for ProviderOverloadedResponse | {<br/>"code": 529,<br/>"message": "Provider returned error"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Request Timeout - Operation exceeded time limit
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
|
||||
| `error` | [components.RequestTimeoutResponseErrorData](../components/requesttimeoutresponseerrordata.md) | :heavy_check_mark: | Error data for RequestTimeoutResponse | {<br/>"code": 408,<br/>"message": "Operation timed out. Please try again later."<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Service Unavailable - Service temporarily unavailable
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
|
||||
| `error` | [components.ServiceUnavailableResponseErrorData](../components/serviceunavailableresponseerrordata.md) | :heavy_check_mark: | Error data for ServiceUnavailableResponse | {<br/>"code": 503,<br/>"message": "Service temporarily unavailable"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Too Many Requests - Rate limit exceeded
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
|
||||
| `error` | [components.TooManyRequestsResponseErrorData](../components/toomanyrequestsresponseerrordata.md) | :heavy_check_mark: | Error data for TooManyRequestsResponse | {<br/>"code": 429,<br/>"message": "Rate limit exceeded"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Unauthorized - Authentication required or invalid credentials
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
|
||||
| `error` | [components.UnauthorizedResponseErrorData](../components/unauthorizedresponseerrordata.md) | :heavy_check_mark: | Error data for UnauthorizedResponse | {<br/>"code": 401,<br/>"message": "Missing Authentication header"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -8,4 +8,5 @@ Unprocessable Entity - Semantic validation failure
|
||||
| Field | Type | Required | Description | Example |
|
||||
| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| `error` | [components.UnprocessableEntityResponseErrorData](../components/unprocessableentityresponseerrordata.md) | :heavy_check_mark: | Error data for UnprocessableEntityResponse | {<br/>"code": 422,<br/>"message": "Invalid argument"<br/>} |
|
||||
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
|
||||
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
@@ -1,13 +0,0 @@
|
||||
# APIType
|
||||
|
||||
Type of API used for the generation
|
||||
|
||||
|
||||
## Values
|
||||
|
||||
| Name | Value |
|
||||
| ------------- | ------------- |
|
||||
| `COMPLETIONS` | completions |
|
||||
| `EMBEDDINGS` | embeddings |
|
||||
| `RERANK` | rerank |
|
||||
| `VIDEO` | video |
|
||||
@@ -1,21 +0,0 @@
|
||||
# Category
|
||||
|
||||
Filter models by use case category
|
||||
|
||||
|
||||
## Values
|
||||
|
||||
| Name | Value |
|
||||
| --------------- | --------------- |
|
||||
| `PROGRAMMING` | programming |
|
||||
| `ROLEPLAY` | roleplay |
|
||||
| `MARKETING` | marketing |
|
||||
| `MARKETING_SEO` | marketing/seo |
|
||||
| `TECHNOLOGY` | technology |
|
||||
| `SCIENCE` | science |
|
||||
| `TRANSLATION` | translation |
|
||||
| `LEGAL` | legal |
|
||||
| `FINANCE` | finance |
|
||||
| `HEALTH` | health |
|
||||
| `TRIVIA` | trivia |
|
||||
| `ACADEMIA` | academia |
|
||||
@@ -15,3 +15,21 @@ value: operations.ContentText = /* values here */
|
||||
value: operations.ContentImageURL = /* values here */
|
||||
```
|
||||
|
||||
### `components.ContentPartInputAudio`
|
||||
|
||||
```python
|
||||
value: components.ContentPartInputAudio = /* values here */
|
||||
```
|
||||
|
||||
### `components.ContentPartInputVideo`
|
||||
|
||||
```python
|
||||
value: components.ContentPartInputVideo = /* values here */
|
||||
```
|
||||
|
||||
### `components.ContentPartInputFile`
|
||||
|
||||
```python
|
||||
value: components.ContentPartInputFile = /* values here */
|
||||
```
|
||||
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
|
||||
| `callback_url` | *str* | :heavy_check_mark: | The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed. | https://myapp.com/auth/callback |
|
||||
| `code_challenge` | *Optional[str]* | :heavy_minus_sign: | PKCE code challenge for enhanced security | E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM |
|
||||
| `code_challenge_method` | [Optional[operations.CreateAuthKeysCodeCodeChallengeMethod]](../operations/createauthkeyscodecodechallengemethod.md) | :heavy_minus_sign: | The method used to generate the code challenge | S256 |
|
||||
| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional expiration time for the API key to be created | 2027-12-31T23:59:59Z |
|
||||
| `key_label` | *Optional[str]* | :heavy_minus_sign: | Optional custom label for the API key. Defaults to the app name if not provided. | My Custom Key |
|
||||
| `limit` | *Optional[float]* | :heavy_minus_sign: | Credit limit for the API key to be created | 100 |
|
||||
| `usage_limit_type` | [Optional[operations.UsageLimitType]](../operations/usagelimittype.md) | :heavy_minus_sign: | Optional credit limit reset interval. When set, the credit limit resets on this interval. | monthly |
|
||||
| Field | Type | Required | Description | Example |
|
||||
| -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `callback_url` | *str* | :heavy_check_mark: | The callback URL to redirect to after authorization. Supports https URLs and localhost/127.0.0.1 URLs on any port for local CLI tools. | https://myapp.com/auth/callback |
|
||||
| `code_challenge` | *Optional[str]* | :heavy_minus_sign: | PKCE code challenge for enhanced security | E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM |
|
||||
| `code_challenge_method` | [Optional[operations.CreateAuthKeysCodeCodeChallengeMethod]](../operations/createauthkeyscodecodechallengemethod.md) | :heavy_minus_sign: | The method used to generate the code challenge | S256 |
|
||||
| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional expiration time for the API key to be created | 2027-12-31T23:59:59Z |
|
||||
| `key_label` | *Optional[str]* | :heavy_minus_sign: | Optional custom label for the API key. Defaults to the app name if not provided. | My Custom Key |
|
||||
| `limit` | *Optional[float]* | :heavy_minus_sign: | Credit limit for the API key to be created | 100 |
|
||||
| `usage_limit_type` | [Optional[operations.UsageLimitType]](../operations/usagelimittype.md) | :heavy_minus_sign: | Optional credit limit reset interval. When set, the credit limit resets on this interval. | monthly |
|
||||
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Optional workspace ID to associate the API key with | |
|
||||
@@ -3,9 +3,9 @@
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `create_guardrail_request` | [components.CreateGuardrailRequest](../components/createguardrailrequest.md) | :heavy_check_mark: | N/A | {<br/>"allowed_models": null,<br/>"allowed_providers": [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>],<br/>"description": "A guardrail for limiting API usage",<br/>"enforce_zdr": false,<br/>"ignored_models": null,<br/>"ignored_providers": null,<br/>"limit_usd": 50,<br/>"name": "My New Guardrail",<br/>"reset_interval": "monthly"<br/>} |
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `create_guardrail_request` | [components.CreateGuardrailRequest](../components/createguardrailrequest.md) | :heavy_check_mark: | N/A | {<br/>"allowed_models": null,<br/>"allowed_providers": [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>],<br/>"content_filter_builtins": [<br/>{<br/>"action": "block",<br/>"slug": "regex-prompt-injection"<br/>}<br/>],<br/>"content_filters": null,<br/>"description": "A guardrail for limiting API usage",<br/>"enforce_zdr_anthropic": true,<br/>"enforce_zdr_google": false,<br/>"enforce_zdr_openai": true,<br/>"enforce_zdr_other": false,<br/>"ignored_models": null,<br/>"ignored_providers": null,<br/>"limit_usd": 50,<br/>"name": "My New Guardrail",<br/>"reset_interval": "monthly"<br/>} |
|
||||
@@ -18,12 +18,13 @@ The created API key information
|
||||
| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943 |
|
||||
| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false |
|
||||
| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | sk-or-v1-0e6...1c96 |
|
||||
| `limit` | *float* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
|
||||
| `limit_remaining` | *float* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
|
||||
| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
|
||||
| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
|
||||
| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly |
|
||||
| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key |
|
||||
| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z |
|
||||
| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 |
|
||||
| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 |
|
||||
| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 |
|
||||
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
|
||||
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
|
||||
| `workspace_id` | *str* | :heavy_check_mark: | The workspace ID this API key belongs to. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
@@ -8,6 +8,7 @@
|
||||
| `creator_user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Optional user ID of the key creator. Only meaningful for organization-owned keys where a specific member is creating the key. | user_2dHFtVWx2n56w6HkM0000000000 |
|
||||
| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected | 2027-12-31T23:59:59Z |
|
||||
| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true |
|
||||
| `limit` | *Optional[float]* | :heavy_minus_sign: | Optional spending limit for the API key in USD | 50 |
|
||||
| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | Optional spending limit for the API key in USD | 50 |
|
||||
| `limit_reset` | [OptionalNullable[operations.CreateKeysLimitReset]](../operations/createkeyslimitreset.md) | :heavy_minus_sign: | Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | monthly |
|
||||
| `name` | *str* | :heavy_check_mark: | Name for the new API key | My New API Key |
|
||||
| `name` | *str* | :heavy_check_mark: | Name for the new API key | My New API Key |
|
||||
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | The workspace to create the API key in. Defaults to the default workspace if not provided. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
@@ -5,7 +5,7 @@ API key created successfully
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `data` | [operations.CreateKeysData](../operations/createkeysdata.md) | :heavy_check_mark: | The created API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5<br/>} |
|
||||
| `key` | *str* | :heavy_check_mark: | The actual API key string (only shown once) | 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 |
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `data` | [operations.CreateKeysData](../operations/createkeysdata.md) | :heavy_check_mark: | The created API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5,<br/>"workspace_id": "0df9e665-d932-5740-b2c7-b52af166bc11"<br/>} |
|
||||
| `key` | *str* | :heavy_check_mark: | The actual API key string (only shown once) | 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 |
|
||||
@@ -8,4 +8,5 @@
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `x_open_router_metadata` | [Optional[components.MetadataLevel]](../components/metadatalevel.md) | :heavy_minus_sign: | Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility. | enabled |
|
||||
| `responses_request` | [components.ResponsesRequest](../components/responsesrequest.md) | :heavy_check_mark: | N/A | {<br/>"input": [<br/>{<br/>"content": "Hello, how are you?",<br/>"role": "user",<br/>"type": "message"<br/>}<br/>],<br/>"model": "anthropic/claude-4.5-sonnet-20250929",<br/>"temperature": 0.7,<br/>"tools": [<br/>{<br/>"description": "Get the current weather in a given location",<br/>"name": "get_current_weather",<br/>"parameters": {<br/>"properties": {<br/>"location": {<br/>"type": "string"<br/>}<br/>},<br/>"type": "object"<br/>},<br/>"type": "function"<br/>}<br/>],<br/>"top_p": 0.9<br/>} |
|
||||
@@ -1,10 +0,0 @@
|
||||
# CreateResponsesResponseBody
|
||||
|
||||
Successful response
|
||||
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `data` | [components.StreamEvents](../components/streamevents.md) | :heavy_check_mark: | Union of all possible event types emitted during response streaming | {<br/>"response": {<br/>"created_at": 1704067200,<br/>"error": null,<br/>"id": "resp-abc123",<br/>"incomplete_details": null,<br/>"instructions": null,<br/>"max_output_tokens": null,<br/>"metadata": null,<br/>"model": "gpt-4",<br/>"object": "response",<br/>"output": [],<br/>"parallel_tool_calls": true,<br/>"status": "in_progress",<br/>"temperature": null,<br/>"tool_choice": "auto",<br/>"tools": [],<br/>"top_p": null<br/>},<br/>"sequence_number": 0,<br/>"type": "response.created"<br/>} |
|
||||
@@ -18,8 +18,8 @@ Current API key information
|
||||
| `is_management_key` | *bool* | :heavy_check_mark: | Whether this is a management key | false |
|
||||
| ~~`is_provisioning_key`~~ | *bool* | :heavy_check_mark: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.<br/><br/>Whether this is a management key | false |
|
||||
| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | sk-or-v1-0e6...1c96 |
|
||||
| `limit` | *float* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
|
||||
| `limit_remaining` | *float* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
|
||||
| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
|
||||
| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
|
||||
| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly |
|
||||
| ~~`rate_limit`~~ | [operations.RateLimit](../operations/ratelimit.md) | :heavy_check_mark: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.<br/><br/>Legacy rate limit information about a key. Will always return -1. | {<br/>"interval": "1h",<br/>"note": "This field is deprecated and safe to ignore.",<br/>"requests": 1000<br/>} |
|
||||
| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 |
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
# GetGenerationData
|
||||
|
||||
Generation data
|
||||
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
|
||||
| `api_type` | [Nullable[operations.APIType]](../operations/apitype.md) | :heavy_check_mark: | Type of API used for the generation | |
|
||||
| `app_id` | *int* | :heavy_check_mark: | ID of the app that made the request | 12345 |
|
||||
| `cache_discount` | *float* | :heavy_check_mark: | Discount applied due to caching | 0.0002 |
|
||||
| `cancelled` | *Nullable[bool]* | :heavy_check_mark: | Whether the generation was cancelled | false |
|
||||
| `created_at` | *str* | :heavy_check_mark: | ISO 8601 timestamp of when the generation was created | 2024-07-15T23:33:19.433273+00:00 |
|
||||
| `external_user` | *Nullable[str]* | :heavy_check_mark: | External user identifier | user-123 |
|
||||
| `finish_reason` | *Nullable[str]* | :heavy_check_mark: | Reason the generation finished | stop |
|
||||
| `generation_time` | *float* | :heavy_check_mark: | Time taken for generation in milliseconds | 1200 |
|
||||
| `http_referer` | *Nullable[str]* | :heavy_check_mark: | Referer header from the request | |
|
||||
| `id` | *str* | :heavy_check_mark: | Unique identifier for the generation | gen-3bhGkxlo4XFrqiabUM7NDtwDzWwG |
|
||||
| `is_byok` | *bool* | :heavy_check_mark: | Whether this used bring-your-own-key | false |
|
||||
| `latency` | *float* | :heavy_check_mark: | Total latency in milliseconds | 1250 |
|
||||
| `model` | *str* | :heavy_check_mark: | Model used for the generation | sao10k/l3-stheno-8b |
|
||||
| `moderation_latency` | *float* | :heavy_check_mark: | Moderation latency in milliseconds | 50 |
|
||||
| `native_finish_reason` | *Nullable[str]* | :heavy_check_mark: | Native finish reason as reported by provider | stop |
|
||||
| `native_tokens_cached` | *int* | :heavy_check_mark: | Native cached tokens as reported by provider | 3 |
|
||||
| `native_tokens_completion` | *int* | :heavy_check_mark: | Native completion tokens as reported by provider | 25 |
|
||||
| `native_tokens_completion_images` | *int* | :heavy_check_mark: | Native completion image tokens as reported by provider | 0 |
|
||||
| `native_tokens_prompt` | *int* | :heavy_check_mark: | Native prompt tokens as reported by provider | 10 |
|
||||
| `native_tokens_reasoning` | *int* | :heavy_check_mark: | Native reasoning tokens as reported by provider | 5 |
|
||||
| `num_input_audio_prompt` | *int* | :heavy_check_mark: | Number of audio inputs in the prompt | 0 |
|
||||
| `num_media_completion` | *int* | :heavy_check_mark: | Number of media items in the completion | 0 |
|
||||
| `num_media_prompt` | *int* | :heavy_check_mark: | Number of media items in the prompt | 1 |
|
||||
| `num_search_results` | *int* | :heavy_check_mark: | Number of search results included | 5 |
|
||||
| `origin` | *str* | :heavy_check_mark: | Origin URL of the request | https://openrouter.ai/ |
|
||||
| `provider_name` | *Nullable[str]* | :heavy_check_mark: | Name of the provider that served the request | Infermatic |
|
||||
| `provider_responses` | List[[components.ProviderResponse](../components/providerresponse.md)] | :heavy_check_mark: | List of provider responses for this generation, including fallback attempts | |
|
||||
| `request_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier grouping all generations from a single API request | req-1727282430-aBcDeFgHiJkLmNoPqRsT |
|
||||
| `router` | *Nullable[str]* | :heavy_check_mark: | Router used for the request (e.g., openrouter/auto) | openrouter/auto |
|
||||
| `session_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Session identifier grouping multiple generations in the same session | |
|
||||
| `streamed` | *Nullable[bool]* | :heavy_check_mark: | Whether the response was streamed | true |
|
||||
| `tokens_completion` | *int* | :heavy_check_mark: | Number of tokens in the completion | 25 |
|
||||
| `tokens_prompt` | *int* | :heavy_check_mark: | Number of tokens in the prompt | 10 |
|
||||
| `total_cost` | *float* | :heavy_check_mark: | Total cost of the generation in USD | 0.0015 |
|
||||
| `upstream_id` | *Nullable[str]* | :heavy_check_mark: | Upstream provider's identifier for this generation | chatcmpl-791bcf62-080e-4568-87d0-94c72e3b4946 |
|
||||
| `upstream_inference_cost` | *float* | :heavy_check_mark: | Cost charged by the upstream provider | 0.0012 |
|
||||
| `usage` | *float* | :heavy_check_mark: | Usage amount in USD | 0.0015 |
|
||||
| `user_agent` | *Nullable[str]* | :heavy_check_mark: | User-Agent header from the request | |
|
||||
@@ -1,10 +0,0 @@
|
||||
# GetGenerationResponse
|
||||
|
||||
Generation response
|
||||
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ |
|
||||
| `data` | [operations.GetGenerationData](../operations/getgenerationdata.md) | :heavy_check_mark: | Generation data |
|
||||
@@ -18,12 +18,13 @@ The API key information
|
||||
| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943 |
|
||||
| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false |
|
||||
| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | sk-or-v1-0e6...1c96 |
|
||||
| `limit` | *float* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
|
||||
| `limit_remaining` | *float* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
|
||||
| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
|
||||
| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
|
||||
| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly |
|
||||
| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key |
|
||||
| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z |
|
||||
| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 |
|
||||
| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 |
|
||||
| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 |
|
||||
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
|
||||
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
|
||||
| `workspace_id` | *str* | :heavy_check_mark: | The workspace ID this API key belongs to. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
@@ -5,6 +5,6 @@ API key details
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `data` | [operations.GetKeyData](../operations/getkeydata.md) | :heavy_check_mark: | The API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5<br/>} |
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `data` | [operations.GetKeyData](../operations/getkeydata.md) | :heavy_check_mark: | The API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5,<br/>"workspace_id": "0df9e665-d932-5740-b2c7-b52af166bc11"<br/>} |
|
||||
@@ -3,11 +3,23 @@
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `category` | [Optional[operations.Category]](../operations/category.md) | :heavy_minus_sign: | Filter models by use case category | programming |
|
||||
| `supported_parameters` | *Optional[str]* | :heavy_minus_sign: | Filter models by supported parameter (comma-separated) | temperature |
|
||||
| `output_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by output modality. Accepts a comma-separated list of modalities (text, image, audio, embeddings) or "all" to include all models. Defaults to "text". | text |
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `category` | [Optional[operations.GetModelsCategory]](../operations/getmodelscategory.md) | :heavy_minus_sign: | Filter models by use case category | programming |
|
||||
| `supported_parameters` | *Optional[str]* | :heavy_minus_sign: | Filter models by supported parameter (comma-separated) | temperature |
|
||||
| `output_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by output modality. Accepts a comma-separated list of modalities (text, image, audio, embeddings) or "all" to include all models. Defaults to "text". | text |
|
||||
| `sort` | [Optional[operations.GetModelsSort]](../operations/getmodelssort.md) | :heavy_minus_sign: | Sort the returned models server-side. Prefer this over fetching the full list and sorting client-side. Options: pricing-low-to-high, pricing-high-to-low (average prompt/completion price), context-high-to-low (context length), throughput-high-to-low, latency-low-to-high (recent median performance), most-popular, top-weekly (tokens processed in the last week), newest (creation date), intelligence-high-to-low (Artificial Analysis intelligence index), design-arena-elo-high-to-low (best Design Arena ELO across arenas). Models without a score for the chosen benchmark are placed last. When omitted, the existing default ordering is preserved. | newest |
|
||||
| `q` | *Optional[str]* | :heavy_minus_sign: | Free-text search by model name or slug. | gpt-4 |
|
||||
| `input_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by input modality. Comma-separated list of: text, image, audio, file. | text,image |
|
||||
| `context` | *Optional[int]* | :heavy_minus_sign: | Minimum context length (tokens). Models with smaller context are excluded. | 128000 |
|
||||
| `min_price` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum prompt price in $/M tokens. | 0 |
|
||||
| `max_price` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum prompt price in $/M tokens. | 10 |
|
||||
| `arch` | *Optional[str]* | :heavy_minus_sign: | Filter models by architecture/model family (e.g. GPT, Claude, Gemini, Llama). | GPT |
|
||||
| `model_authors` | *Optional[str]* | :heavy_minus_sign: | Filter models by the organization that created the model. Comma-separated list of author slugs. | openai,anthropic |
|
||||
| `providers` | *Optional[str]* | :heavy_minus_sign: | Filter models by hosting provider. Comma-separated list of provider names. | OpenAI,Anthropic |
|
||||
| `distillable` | [Optional[operations.Distillable]](../operations/distillable.md) | :heavy_minus_sign: | Filter by distillation capability. "true" returns only distillable models, "false" excludes them. | true |
|
||||
| `zdr` | [Optional[operations.Zdr]](../operations/zdr.md) | :heavy_minus_sign: | When set to "true", return only models with zero data retention endpoints. | true |
|
||||
| `region` | [Optional[operations.Region]](../operations/region.md) | :heavy_minus_sign: | Filter to models with endpoints in the given data region. Currently only "eu" is supported. | eu |
|
||||
@@ -16,12 +16,13 @@
|
||||
| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943 |
|
||||
| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false |
|
||||
| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | sk-or-v1-0e6...1c96 |
|
||||
| `limit` | *float* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
|
||||
| `limit_remaining` | *float* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
|
||||
| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
|
||||
| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
|
||||
| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly |
|
||||
| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key |
|
||||
| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z |
|
||||
| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 |
|
||||
| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 |
|
||||
| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 |
|
||||
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
|
||||
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
|
||||
| `workspace_id` | *str* | :heavy_check_mark: | The workspace ID this API key belongs to. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
@@ -9,4 +9,5 @@
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `offset` | *Optional[int]* | :heavy_minus_sign: | Number of records to skip for pagination | 0 |
|
||||
| `limit` | *Optional[int]* | :heavy_minus_sign: | Maximum number of records to return (max 100) | 50 |
|
||||
| `limit` | *Optional[int]* | :heavy_minus_sign: | Maximum number of records to return (max 100) | 50 |
|
||||
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Filter guardrails by workspace ID. By default, guardrails in the default workspace are returned. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
@@ -3,6 +3,6 @@
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `result` | [components.ListGuardrailsResponse](../components/listguardrailsresponse.md) | :heavy_check_mark: | N/A | {<br/>"data": [<br/>{<br/>"allowed_models": null,<br/>"allowed_providers": [<br/>"openai",<br/>"anthropic",<br/>"google"<br/>],<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"description": "Guardrail for production environment",<br/>"enforce_zdr": false,<br/>"id": "550e8400-e29b-41d4-a716-446655440000",<br/>"ignored_models": null,<br/>"ignored_providers": null,<br/>"limit_usd": 100,<br/>"name": "Production Guardrail",<br/>"reset_interval": "monthly",<br/>"updated_at": "2025-08-24T15:45:00Z"<br/>}<br/>],<br/>"total_count": 1<br/>} |
|
||||
| Field | Type | Required | Description | Example |
|
||||
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `result` | [components.ListGuardrailsResponse](../components/listguardrailsresponse.md) | :heavy_check_mark: | N/A | {<br/>"data": [<br/>{<br/>"allowed_models": null,<br/>"allowed_providers": [<br/>"openai",<br/>"anthropic",<br/>"google"<br/>],<br/>"content_filter_builtins": [<br/>{<br/>"action": "redact",<br/>"label": "[EMAIL]",<br/>"slug": "email"<br/>}<br/>],<br/>"content_filters": null,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"description": "Guardrail for production environment",<br/>"enforce_zdr": null,<br/>"enforce_zdr_anthropic": true,<br/>"enforce_zdr_google": false,<br/>"enforce_zdr_openai": true,<br/>"enforce_zdr_other": false,<br/>"id": "550e8400-e29b-41d4-a716-446655440000",<br/>"ignored_models": null,<br/>"ignored_providers": null,<br/>"limit_usd": 100,<br/>"name": "Production Guardrail",<br/>"reset_interval": "monthly",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"workspace_id": "0df9e665-d932-5740-b2c7-b52af166bc11"<br/>}<br/>],<br/>"total_count": 1<br/>} |
|
||||
@@ -9,4 +9,5 @@
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `include_disabled` | *Optional[bool]* | :heavy_minus_sign: | Whether to include disabled API keys in the response | false |
|
||||
| `offset` | *Optional[int]* | :heavy_minus_sign: | Number of API keys to skip for pagination | 0 |
|
||||
| `offset` | *Optional[int]* | :heavy_minus_sign: | Number of API keys to skip for pagination | 0 |
|
||||
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Filter API keys by workspace ID. By default, keys in the default workspace are returned. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
@@ -8,4 +8,5 @@
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `x_open_router_metadata` | [Optional[components.MetadataLevel]](../components/metadatalevel.md) | :heavy_minus_sign: | Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility. | enabled |
|
||||
| `chat_request` | [components.ChatRequest](../components/chatrequest.md) | :heavy_check_mark: | N/A | {<br/>"max_tokens": 150,<br/>"messages": [<br/>{<br/>"content": "You are a helpful assistant.",<br/>"role": "system"<br/>},<br/>{<br/>"content": "What is the capital of France?",<br/>"role": "user"<br/>}<br/>],<br/>"model": "openai/gpt-4",<br/>"temperature": 0.7<br/>} |
|
||||
@@ -1,10 +0,0 @@
|
||||
# SendChatCompletionRequestResponseBody
|
||||
|
||||
Successful chat completion response
|
||||
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `data` | [components.ChatStreamChunk](../components/chatstreamchunk.md) | :heavy_check_mark: | Streaming chat completion chunk | {<br/>"choices": [<br/>{<br/>"delta": {<br/>"content": "Hello",<br/>"role": "assistant"<br/>},<br/>"finish_reason": null,<br/>"index": 0<br/>}<br/>],<br/>"created": 1677652288,<br/>"id": "chatcmpl-123",<br/>"model": "openai/gpt-4",<br/>"object": "chat.completion.chunk"<br/>} |
|
||||
@@ -18,12 +18,13 @@ The updated API key information
|
||||
| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943 |
|
||||
| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false |
|
||||
| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | sk-or-v1-0e6...1c96 |
|
||||
| `limit` | *float* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
|
||||
| `limit_remaining` | *float* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
|
||||
| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
|
||||
| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
|
||||
| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly |
|
||||
| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key |
|
||||
| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z |
|
||||
| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 |
|
||||
| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 |
|
||||
| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 |
|
||||
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
|
||||
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
|
||||
| `workspace_id` | *str* | :heavy_check_mark: | The workspace ID this API key belongs to. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
@@ -7,6 +7,6 @@
|
||||
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `disabled` | *Optional[bool]* | :heavy_minus_sign: | Whether to disable the API key | false |
|
||||
| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true |
|
||||
| `limit` | *Optional[float]* | :heavy_minus_sign: | New spending limit for the API key in USD | 75 |
|
||||
| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | New spending limit for the API key in USD | 75 |
|
||||
| `limit_reset` | [OptionalNullable[operations.UpdateKeysLimitReset]](../operations/updatekeyslimitreset.md) | :heavy_minus_sign: | New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | daily |
|
||||
| `name` | *Optional[str]* | :heavy_minus_sign: | New name for the API key | Updated API Key Name |
|
||||
@@ -5,6 +5,6 @@ API key updated successfully
|
||||
|
||||
## Fields
|
||||
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `data` | [operations.UpdateKeysData](../operations/updatekeysdata.md) | :heavy_check_mark: | The updated API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5<br/>} |
|
||||
| Field | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `data` | [operations.UpdateKeysData](../operations/updatekeysdata.md) | :heavy_check_mark: | The updated API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5,<br/>"workspace_id": "0df9e665-d932-5740-b2c7-b52af166bc11"<br/>} |
|
||||
@@ -95,6 +95,7 @@ with OpenRouter(
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `include_disabled` | *Optional[bool]* | :heavy_minus_sign: | Whether to include disabled API keys in the response | false |
|
||||
| `offset` | *Optional[int]* | :heavy_minus_sign: | Number of API keys to skip for pagination | 0 |
|
||||
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Filter API keys by workspace ID. By default, keys in the default workspace are returned. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
@@ -112,7 +113,7 @@ with OpenRouter(
|
||||
|
||||
## create
|
||||
|
||||
Create a new API key for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
Create a new API key for the authenticated user. The plaintext `key` is returned only in this response. Treat it as a write-only, sensitive value; it cannot be retrieved later. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
|
||||
### Example Usage
|
||||
|
||||
@@ -148,8 +149,9 @@ with OpenRouter(
|
||||
| `creator_user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Optional user ID of the key creator. Only meaningful for organization-owned keys where a specific member is creating the key. | user_2dHFtVWx2n56w6HkM0000000000 |
|
||||
| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected | 2027-12-31T23:59:59Z |
|
||||
| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true |
|
||||
| `limit` | *Optional[float]* | :heavy_minus_sign: | Optional spending limit for the API key in USD | 50 |
|
||||
| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | Optional spending limit for the API key in USD | 50 |
|
||||
| `limit_reset` | [OptionalNullable[operations.CreateKeysLimitReset]](../../operations/createkeyslimitreset.md) | :heavy_minus_sign: | Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | monthly |
|
||||
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | The workspace to create the API key in. Defaults to the default workspace if not provided. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
@@ -162,6 +164,7 @@ with OpenRouter(
|
||||
| ----------------------------------- | ----------------------------------- | ----------------------------------- |
|
||||
| errors.BadRequestResponseError | 400 | application/json |
|
||||
| errors.UnauthorizedResponseError | 401 | application/json |
|
||||
| errors.ForbiddenResponseError | 403 | application/json |
|
||||
| errors.TooManyRequestsResponseError | 429 | application/json |
|
||||
| errors.InternalServerResponseError | 500 | application/json |
|
||||
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
|
||||
@@ -302,7 +305,7 @@ with OpenRouter(
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `disabled` | *Optional[bool]* | :heavy_minus_sign: | Whether to disable the API key | false |
|
||||
| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true |
|
||||
| `limit` | *Optional[float]* | :heavy_minus_sign: | New spending limit for the API key in USD | 75 |
|
||||
| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | New spending limit for the API key in USD | 75 |
|
||||
| `limit_reset` | [OptionalNullable[operations.UpdateKeysLimitReset]](../../operations/updatekeyslimitreset.md) | :heavy_minus_sign: | New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | daily |
|
||||
| `name` | *Optional[str]* | :heavy_minus_sign: | New name for the API key | Updated API Key Name |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
+47
-39
@@ -34,7 +34,7 @@ with OpenRouter(
|
||||
"content": "What is the capital of France?",
|
||||
"role": "user",
|
||||
},
|
||||
], max_tokens=150, model="openai/gpt-4", stream=False, temperature=0.7)
|
||||
], x_open_router_metadata="enabled", max_tokens=150, model="openai/gpt-4", stream=False, temperature=0.7)
|
||||
|
||||
with res as event_stream:
|
||||
for event in event_stream:
|
||||
@@ -45,44 +45,51 @@ with OpenRouter(
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `messages` | List[[components.ChatMessages](../../components/chatmessages.md)] | :heavy_check_mark: | List of messages for the conversation | [<br/>{<br/>"content": "Hello!",<br/>"role": "user"<br/>}<br/>] |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `cache_control` | [Optional[components.AnthropicCacheControlDirective]](../../components/anthropiccachecontroldirective.md) | :heavy_minus_sign: | N/A | {<br/>"type": "ephemeral"<br/>} |
|
||||
| `debug` | [Optional[components.ChatDebugOptions]](../../components/chatdebugoptions.md) | :heavy_minus_sign: | Debug options for inspecting request transformations (streaming only) | {<br/>"echo_upstream_body": true<br/>} |
|
||||
| `frequency_penalty` | *Optional[float]* | :heavy_minus_sign: | Frequency penalty (-2.0 to 2.0) | 0 |
|
||||
| `image_config` | Dict[str, [components.ChatRequestImageConfig](../../components/chatrequestimageconfig.md)] | :heavy_minus_sign: | Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details. | {<br/>"aspect_ratio": "16:9"<br/>} |
|
||||
| `logit_bias` | Dict[str, *float*] | :heavy_minus_sign: | Token logit bias adjustments | {<br/>"50256": -100<br/>} |
|
||||
| `logprobs` | *OptionalNullable[bool]* | :heavy_minus_sign: | Return log probabilities | false |
|
||||
| `max_completion_tokens` | *Optional[int]* | :heavy_minus_sign: | Maximum tokens in completion | 100 |
|
||||
| `max_tokens` | *Optional[int]* | :heavy_minus_sign: | Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16. | 100 |
|
||||
| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values) | {<br/>"session_id": "session-456",<br/>"user_id": "user-123"<br/>} |
|
||||
| `modalities` | List[[components.Modality](../../components/modality.md)] | :heavy_minus_sign: | Output modalities for the response. Supported values are "text", "image", and "audio". | [<br/>"text",<br/>"image"<br/>] |
|
||||
| `model` | *Optional[str]* | :heavy_minus_sign: | Model to use for completion | openai/gpt-4 |
|
||||
| `models` | List[*str*] | :heavy_minus_sign: | Models to use for completion | [<br/>"openai/gpt-4",<br/>"openai/gpt-4o"<br/>] |
|
||||
| `parallel_tool_calls` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enable parallel function calling during tool use. When true, the model may generate multiple tool calls in a single response. | true |
|
||||
| `plugins` | List[[components.ChatRequestPlugin](../../components/chatrequestplugin.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
|
||||
| `presence_penalty` | *Optional[float]* | :heavy_minus_sign: | Presence penalty (-2.0 to 2.0) | 0 |
|
||||
| `provider` | [OptionalNullable[components.ProviderPreferences]](../../components/providerpreferences.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | {<br/>"allow_fallbacks": true<br/>} |
|
||||
| `reasoning` | [Optional[components.Reasoning]](../../components/reasoning.md) | :heavy_minus_sign: | Configuration options for reasoning models | {<br/>"effort": "medium",<br/>"summary": "concise"<br/>} |
|
||||
| `response_format` | [Optional[components.ResponseFormat]](../../components/responseformat.md) | :heavy_minus_sign: | Response format configuration | {<br/>"type": "json_object"<br/>} |
|
||||
| `seed` | *Optional[int]* | :heavy_minus_sign: | Random seed for deterministic outputs | 42 |
|
||||
| `service_tier` | [OptionalNullable[components.ChatRequestServiceTier]](../../components/chatrequestservicetier.md) | :heavy_minus_sign: | The service tier to use for processing this request. | auto |
|
||||
| `session_id` | *Optional[str]* | :heavy_minus_sign: | A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters. | |
|
||||
| `stop` | [OptionalNullable[components.Stop]](../../components/stop.md) | :heavy_minus_sign: | Stop sequences (up to 4) | [<br/>""<br/>] |
|
||||
| `stream` | *Optional[bool]* | :heavy_minus_sign: | Enable streaming response | false |
|
||||
| `stream_options` | [OptionalNullable[components.ChatStreamOptions]](../../components/chatstreamoptions.md) | :heavy_minus_sign: | Streaming configuration options | {<br/>"include_usage": true<br/>} |
|
||||
| `temperature` | *Optional[float]* | :heavy_minus_sign: | Sampling temperature (0-2) | 0.7 |
|
||||
| `tool_choice` | [Optional[components.ChatToolChoice]](../../components/chattoolchoice.md) | :heavy_minus_sign: | Tool choice configuration | auto |
|
||||
| `tools` | List[[components.ChatFunctionTool](../../components/chatfunctiontool.md)] | :heavy_minus_sign: | Available tools for function calling | [<br/>{<br/>"function": {<br/>"description": "Get weather",<br/>"name": "get_weather"<br/>},<br/>"type": "function"<br/>}<br/>] |
|
||||
| `top_logprobs` | *Optional[int]* | :heavy_minus_sign: | Number of top log probabilities to return (0-20) | 5 |
|
||||
| `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | 1 |
|
||||
| `trace` | [Optional[components.TraceConfig]](../../components/traceconfig.md) | :heavy_minus_sign: | Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations. | {<br/>"trace_id": "trace-abc123",<br/>"trace_name": "my-app-trace"<br/>} |
|
||||
| `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | user-123 |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `messages` | List[[components.ChatMessages](../../components/chatmessages.md)] | :heavy_check_mark: | List of messages for the conversation | [<br/>{<br/>"content": "Hello!",<br/>"role": "user"<br/>}<br/>] |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `x_open_router_metadata` | [Optional[components.MetadataLevel]](../../components/metadatalevel.md) | :heavy_minus_sign: | Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility. | enabled |
|
||||
| `cache_control` | [Optional[components.AnthropicCacheControlDirective]](../../components/anthropiccachecontroldirective.md) | :heavy_minus_sign: | Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models. | {<br/>"type": "ephemeral"<br/>} |
|
||||
| `debug` | [Optional[components.ChatDebugOptions]](../../components/chatdebugoptions.md) | :heavy_minus_sign: | Debug options for inspecting request transformations (streaming only) | {<br/>"echo_upstream_body": true<br/>} |
|
||||
| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | Frequency penalty (-2.0 to 2.0) | 0 |
|
||||
| `image_config` | Dict[str, [components.ImageConfig](../../components/imageconfig.md)] | :heavy_minus_sign: | Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details. | {<br/>"aspect_ratio": "16:9",<br/>"quality": "high"<br/>} |
|
||||
| `logit_bias` | Dict[str, *float*] | :heavy_minus_sign: | Token logit bias adjustments | {<br/>"50256": -100<br/>} |
|
||||
| `logprobs` | *OptionalNullable[bool]* | :heavy_minus_sign: | Return log probabilities | false |
|
||||
| `max_completion_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | Maximum tokens in completion | 100 |
|
||||
| `max_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16. | 100 |
|
||||
| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values) | {<br/>"session_id": "session-456",<br/>"user_id": "user-123"<br/>} |
|
||||
| `min_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter. | 0.1 |
|
||||
| `modalities` | List[[components.Modality](../../components/modality.md)] | :heavy_minus_sign: | Output modalities for the response. Supported values are "text", "image", and "audio". | [<br/>"text",<br/>"image"<br/>] |
|
||||
| `model` | *Optional[str]* | :heavy_minus_sign: | Model to use for completion | openai/gpt-4 |
|
||||
| `models` | List[*str*] | :heavy_minus_sign: | Models to use for completion | [<br/>"openai/gpt-4",<br/>"openai/gpt-4o"<br/>] |
|
||||
| `parallel_tool_calls` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enable parallel function calling during tool use. When true, the model may generate multiple tool calls in a single response. | true |
|
||||
| `plugins` | List[[components.ChatRequestPlugin](../../components/chatrequestplugin.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
|
||||
| `presence_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | Presence penalty (-2.0 to 2.0) | 0 |
|
||||
| `provider` | [OptionalNullable[components.ProviderPreferences]](../../components/providerpreferences.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | {<br/>"allow_fallbacks": true<br/>} |
|
||||
| `reasoning` | [Optional[components.ChatRequestReasoning]](../../components/chatrequestreasoning.md) | :heavy_minus_sign: | Configuration options for reasoning models | {<br/>"effort": "medium",<br/>"summary": "concise"<br/>} |
|
||||
| `reasoning_effort` | [OptionalNullable[components.ChatRequestReasoningEffort]](../../components/chatrequestreasoningeffort.md) | :heavy_minus_sign: | Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ. | medium |
|
||||
| `repetition_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter. | 1 |
|
||||
| `response_format` | [Optional[components.ResponseFormat]](../../components/responseformat.md) | :heavy_minus_sign: | Response format configuration | {<br/>"type": "json_object"<br/>} |
|
||||
| `seed` | *OptionalNullable[int]* | :heavy_minus_sign: | Random seed for deterministic outputs | 42 |
|
||||
| `service_tier` | [OptionalNullable[components.ChatRequestServiceTier]](../../components/chatrequestservicetier.md) | :heavy_minus_sign: | The service tier to use for processing this request. | auto |
|
||||
| `session_id` | *Optional[str]* | :heavy_minus_sign: | A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters. | |
|
||||
| `stop` | [OptionalNullable[components.Stop]](../../components/stop.md) | :heavy_minus_sign: | Stop sequences (up to 4) | [<br/>""<br/>] |
|
||||
| `stop_server_tools_when` | List[[components.StopServerToolsWhenCondition](../../components/stopservertoolswhencondition.md)] | :heavy_minus_sign: | Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`. | [<br/>{<br/>"step_count": 5,<br/>"type": "step_count_is"<br/>},<br/>{<br/>"max_cost_in_dollars": 0.5,<br/>"type": "max_cost"<br/>}<br/>] |
|
||||
| `stream` | *Optional[bool]* | :heavy_minus_sign: | Enable streaming response | false |
|
||||
| `stream_options` | [OptionalNullable[components.ChatStreamOptions]](../../components/chatstreamoptions.md) | :heavy_minus_sign: | Streaming configuration options | {<br/>"include_usage": true<br/>} |
|
||||
| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | Sampling temperature (0-2) | 0.7 |
|
||||
| `tool_choice` | [Optional[components.ChatToolChoice]](../../components/chattoolchoice.md) | :heavy_minus_sign: | Tool choice configuration | auto |
|
||||
| `tools` | List[[components.ChatFunctionTool](../../components/chatfunctiontool.md)] | :heavy_minus_sign: | Available tools for function calling | [<br/>{<br/>"function": {<br/>"description": "Get weather",<br/>"name": "get_weather"<br/>},<br/>"type": "function"<br/>}<br/>] |
|
||||
| `top_a` | *OptionalNullable[float]* | :heavy_minus_sign: | Consider only tokens with "sufficiently high" probabilities based on the probability of the most likely token. Not all providers support this parameter. | 0 |
|
||||
| `top_k` | *OptionalNullable[int]* | :heavy_minus_sign: | Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter. | 40 |
|
||||
| `top_logprobs` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of top log probabilities to return (0-20) | 5 |
|
||||
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | 1 |
|
||||
| `trace` | [Optional[components.TraceConfig]](../../components/traceconfig.md) | :heavy_minus_sign: | Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations. | {<br/>"trace_id": "trace-abc123",<br/>"trace_name": "my-app-trace"<br/>} |
|
||||
| `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | user-123 |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
|
||||
@@ -95,6 +102,7 @@ with OpenRouter(
|
||||
| errors.BadRequestResponseError | 400 | application/json |
|
||||
| errors.UnauthorizedResponseError | 401 | application/json |
|
||||
| errors.PaymentRequiredResponseError | 402 | application/json |
|
||||
| errors.ForbiddenResponseError | 403 | application/json |
|
||||
| errors.NotFoundResponseError | 404 | application/json |
|
||||
| errors.RequestTimeoutResponseError | 408 | application/json |
|
||||
| errors.PayloadTooLargeResponseError | 413 | application/json |
|
||||
|
||||
@@ -7,6 +7,7 @@ Generation history endpoints
|
||||
### Available Operations
|
||||
|
||||
* [get_generation](#get_generation) - Get request & usage metadata for a generation
|
||||
* [list_generation_content](#list_generation_content) - Get stored prompt and completion content for a generation
|
||||
|
||||
## get_generation
|
||||
|
||||
@@ -46,7 +47,7 @@ with OpenRouter(
|
||||
|
||||
### Response
|
||||
|
||||
**[operations.GetGenerationResponse](../../operations/getgenerationresponse.md)**
|
||||
**[components.GenerationResponse](../../components/generationresponse.md)**
|
||||
|
||||
### Errors
|
||||
|
||||
@@ -60,4 +61,58 @@ with OpenRouter(
|
||||
| errors.BadGatewayResponseError | 502 | application/json |
|
||||
| errors.EdgeNetworkTimeoutResponseError | 524 | application/json |
|
||||
| errors.ProviderOverloadedResponseError | 529 | application/json |
|
||||
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
|
||||
|
||||
## list_generation_content
|
||||
|
||||
Get stored prompt and completion content for a generation
|
||||
|
||||
### Example Usage
|
||||
|
||||
<!-- UsageSnippet language="python" operationID="listGenerationContent" method="get" path="/generation/content" -->
|
||||
```python
|
||||
from openrouter import OpenRouter
|
||||
import os
|
||||
|
||||
|
||||
with OpenRouter(
|
||||
http_referer="<value>",
|
||||
x_open_router_title="<value>",
|
||||
x_open_router_categories="<value>",
|
||||
api_key=os.getenv("OPENROUTER_API_KEY", ""),
|
||||
) as open_router:
|
||||
|
||||
res = open_router.generations.list_generation_content(id="gen-1234567890")
|
||||
|
||||
# Handle response
|
||||
print(res)
|
||||
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `id` | *str* | :heavy_check_mark: | The generation ID | gen-1234567890 |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
|
||||
**[components.GenerationContentResponse](../../components/generationcontentresponse.md)**
|
||||
|
||||
### Errors
|
||||
|
||||
| Error Type | Status Code | Content Type |
|
||||
| -------------------------------------- | -------------------------------------- | -------------------------------------- |
|
||||
| errors.UnauthorizedResponseError | 401 | application/json |
|
||||
| errors.ForbiddenResponseError | 403 | application/json |
|
||||
| errors.NotFoundResponseError | 404 | application/json |
|
||||
| errors.TooManyRequestsResponseError | 429 | application/json |
|
||||
| errors.InternalServerResponseError | 500 | application/json |
|
||||
| errors.BadGatewayResponseError | 502 | application/json |
|
||||
| errors.EdgeNetworkTimeoutResponseError | 524 | application/json |
|
||||
| errors.ProviderOverloadedResponseError | 529 | application/json |
|
||||
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
|
||||
@@ -57,6 +57,7 @@ with OpenRouter(
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `offset` | *Optional[int]* | :heavy_minus_sign: | Number of records to skip for pagination | 0 |
|
||||
| `limit` | *Optional[int]* | :heavy_minus_sign: | Maximum number of records to return (max 100) | 50 |
|
||||
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Filter guardrails by workspace ID. By default, guardrails in the default workspace are returned. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
@@ -94,7 +95,7 @@ with OpenRouter(
|
||||
"openai",
|
||||
"anthropic",
|
||||
"deepseek",
|
||||
], description="A guardrail for limiting API usage", enforce_zdr=False, ignored_models=None, ignored_providers=None, limit_usd=50, reset_interval="monthly")
|
||||
], description="A guardrail for limiting API usage", enforce_zdr_anthropic=True, enforce_zdr_google=False, enforce_zdr_openai=True, enforce_zdr_other=False, ignored_models=None, ignored_providers=None, limit_usd=50, reset_interval="monthly")
|
||||
|
||||
# Handle response
|
||||
print(res)
|
||||
@@ -103,21 +104,28 @@ with OpenRouter(
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `name` | *str* | :heavy_check_mark: | Name for the new guardrail | My New Guardrail |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `allowed_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers (slug or canonical_slug accepted) | [<br/>"openai/gpt-5.2",<br/>"anthropic/claude-4.5-opus-20251124",<br/>"deepseek/deepseek-r1-0528:free"<br/>] |
|
||||
| `allowed_providers` | List[*str*] | :heavy_minus_sign: | List of allowed provider IDs | [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>] |
|
||||
| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | Description of the guardrail | A guardrail for limiting API usage |
|
||||
| `enforce_zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention | false |
|
||||
| `ignored_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers to exclude from routing (slug or canonical_slug accepted) | [<br/>"openai/gpt-4o-mini"<br/>] |
|
||||
| `ignored_providers` | List[*str*] | :heavy_minus_sign: | List of provider IDs to exclude from routing | [<br/>"azure"<br/>] |
|
||||
| `limit_usd` | *Optional[float]* | :heavy_minus_sign: | Spending limit in USD | 50 |
|
||||
| `reset_interval` | [OptionalNullable[components.GuardrailInterval]](../../components/guardrailinterval.md) | :heavy_minus_sign: | Interval at which the limit resets (daily, weekly, monthly) | monthly |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `name` | *str* | :heavy_check_mark: | Name for the new guardrail | My New Guardrail |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `allowed_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers (slug or canonical_slug accepted) | [<br/>"openai/gpt-5.2",<br/>"anthropic/claude-4.5-opus-20251124",<br/>"deepseek/deepseek-r1-0528:free"<br/>] |
|
||||
| `allowed_providers` | List[*str*] | :heavy_minus_sign: | List of allowed provider IDs | [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>] |
|
||||
| `content_filter_builtins` | List[[components.ContentFilterBuiltinEntryInput](../../components/contentfilterbuiltinentryinput.md)] | :heavy_minus_sign: | Builtin content filters to apply. The "flag" action is only supported for "regex-prompt-injection"; PII slugs (email, phone, ssn, credit-card, ip-address, person-name, address) accept "block" or "redact" only. | [<br/>{<br/>"action": "block",<br/>"slug": "regex-prompt-injection"<br/>}<br/>] |
|
||||
| `content_filters` | List[[components.ContentFilterEntry](../../components/contentfilterentry.md)] | :heavy_minus_sign: | Custom regex content filters to apply to request messages | [<br/>{<br/>"action": "redact",<br/>"label": "[API_KEY]",<br/>"pattern": "\\b(sk-[a-zA-Z0-9]{48})\\b"<br/>}<br/>] |
|
||||
| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | Description of the guardrail | A guardrail for limiting API usage |
|
||||
| `enforce_zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.<br/><br/>Deprecated. Use enforce_zdr_anthropic, enforce_zdr_openai, enforce_zdr_google, and enforce_zdr_other instead. When provided, its value is copied into any of those per-provider fields that are not explicitly specified on the request. | false |
|
||||
| `enforce_zdr_anthropic` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for Anthropic models. Falls back to enforce_zdr when not provided. | false |
|
||||
| `enforce_zdr_google` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for Google models. Falls back to enforce_zdr when not provided. | false |
|
||||
| `enforce_zdr_openai` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for OpenAI models. Falls back to enforce_zdr when not provided. | false |
|
||||
| `enforce_zdr_other` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for models that are not from Anthropic, OpenAI, or Google. Falls back to enforce_zdr when not provided. | false |
|
||||
| `ignored_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers to exclude from routing (slug or canonical_slug accepted) | [<br/>"openai/gpt-4o-mini"<br/>] |
|
||||
| `ignored_providers` | List[*str*] | :heavy_minus_sign: | List of provider IDs to exclude from routing | [<br/>"azure"<br/>] |
|
||||
| `limit_usd` | *OptionalNullable[float]* | :heavy_minus_sign: | Spending limit in USD | 50 |
|
||||
| `reset_interval` | [OptionalNullable[components.GuardrailInterval]](../../components/guardrailinterval.md) | :heavy_minus_sign: | Interval at which the limit resets (daily, weekly, monthly) | monthly |
|
||||
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | The workspace to create the guardrail in. Defaults to the default workspace if not provided. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
|
||||
@@ -129,6 +137,7 @@ with OpenRouter(
|
||||
| ---------------------------------- | ---------------------------------- | ---------------------------------- |
|
||||
| errors.BadRequestResponseError | 400 | application/json |
|
||||
| errors.UnauthorizedResponseError | 401 | application/json |
|
||||
| errors.ForbiddenResponseError | 403 | application/json |
|
||||
| errors.InternalServerResponseError | 500 | application/json |
|
||||
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
|
||||
|
||||
@@ -232,7 +241,7 @@ with OpenRouter(
|
||||
|
||||
## update
|
||||
|
||||
Update an existing guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
Update an existing guardrail. Collection fields use replace semantics: send the full desired set on every update. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
|
||||
### Example Usage
|
||||
|
||||
@@ -258,22 +267,28 @@ with OpenRouter(
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `id` | *str* | :heavy_check_mark: | The unique identifier of the guardrail to update | 550e8400-e29b-41d4-a716-446655440000 |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `allowed_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers (slug or canonical_slug accepted) | [<br/>"openai/gpt-5.2"<br/>] |
|
||||
| `allowed_providers` | List[*str*] | :heavy_minus_sign: | New list of allowed provider IDs | [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>] |
|
||||
| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | New description for the guardrail | Updated description |
|
||||
| `enforce_zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention | true |
|
||||
| `ignored_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers to exclude from routing (slug or canonical_slug accepted) | [<br/>"openai/gpt-4o-mini"<br/>] |
|
||||
| `ignored_providers` | List[*str*] | :heavy_minus_sign: | List of provider IDs to exclude from routing | [<br/>"azure"<br/>] |
|
||||
| `limit_usd` | *Optional[float]* | :heavy_minus_sign: | New spending limit in USD | 75 |
|
||||
| `name` | *Optional[str]* | :heavy_minus_sign: | New name for the guardrail | Updated Guardrail Name |
|
||||
| `reset_interval` | [OptionalNullable[components.GuardrailInterval]](../../components/guardrailinterval.md) | :heavy_minus_sign: | Interval at which the limit resets (daily, weekly, monthly) | monthly |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `id` | *str* | :heavy_check_mark: | The unique identifier of the guardrail to update | 550e8400-e29b-41d4-a716-446655440000 |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `allowed_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers (slug or canonical_slug accepted) | [<br/>"openai/gpt-5.2"<br/>] |
|
||||
| `allowed_providers` | List[*str*] | :heavy_minus_sign: | New list of allowed provider IDs | [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>] |
|
||||
| `content_filter_builtins` | List[[components.ContentFilterBuiltinEntryInput](../../components/contentfilterbuiltinentryinput.md)] | :heavy_minus_sign: | Builtin content filters to apply. Set to null to remove. The "flag" action is only supported for "regex-prompt-injection"; PII slugs (email, phone, ssn, credit-card, ip-address, person-name, address) accept "block" or "redact" only. | [<br/>{<br/>"action": "block",<br/>"slug": "regex-prompt-injection"<br/>}<br/>] |
|
||||
| `content_filters` | List[[components.ContentFilterEntry](../../components/contentfilterentry.md)] | :heavy_minus_sign: | Custom regex content filters to apply. Set to null to remove. | <nil> |
|
||||
| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | New description for the guardrail | Updated description |
|
||||
| `enforce_zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.<br/><br/>Deprecated. Use enforce_zdr_anthropic, enforce_zdr_openai, enforce_zdr_google, and enforce_zdr_other instead. When provided, its value is copied into any of those per-provider fields that are not explicitly specified on the request. | true |
|
||||
| `enforce_zdr_anthropic` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for Anthropic models. Falls back to enforce_zdr when not provided. | true |
|
||||
| `enforce_zdr_google` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for Google models. Falls back to enforce_zdr when not provided. | true |
|
||||
| `enforce_zdr_openai` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for OpenAI models. Falls back to enforce_zdr when not provided. | true |
|
||||
| `enforce_zdr_other` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for models that are not from Anthropic, OpenAI, or Google. Falls back to enforce_zdr when not provided. | true |
|
||||
| `ignored_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers to exclude from routing (slug or canonical_slug accepted) | [<br/>"openai/gpt-4o-mini"<br/>] |
|
||||
| `ignored_providers` | List[*str*] | :heavy_minus_sign: | List of provider IDs to exclude from routing | [<br/>"azure"<br/>] |
|
||||
| `limit_usd` | *OptionalNullable[float]* | :heavy_minus_sign: | New spending limit in USD | 75 |
|
||||
| `name` | *Optional[str]* | :heavy_minus_sign: | New name for the guardrail | Updated Guardrail Name |
|
||||
| `reset_interval` | [OptionalNullable[components.GuardrailInterval]](../../components/guardrailinterval.md) | :heavy_minus_sign: | Interval at which the limit resets (daily, weekly, monthly) | monthly |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
|
||||
@@ -344,7 +359,7 @@ with OpenRouter(
|
||||
|
||||
## bulk_assign_keys
|
||||
|
||||
Assign multiple API keys to a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
Assign multiple API keys to a specific guardrail. A key may hold at most one guardrail; assigning replaces any existing assignment. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
|
||||
### Example Usage
|
||||
|
||||
|
||||
@@ -6,10 +6,60 @@ Model information endpoints
|
||||
|
||||
### Available Operations
|
||||
|
||||
* [get](#get) - Get a model by its slug
|
||||
* [list](#list) - List all models and their properties
|
||||
* [count](#count) - Get total count of available models
|
||||
* [list_for_user](#list_for_user) - List models filtered by user provider preferences, privacy settings, and guardrails
|
||||
|
||||
## get
|
||||
|
||||
Returns full details for a single model identified by its author and slug (e.g. openai/gpt-4). Supports variant suffixes (e.g. openai/gpt-4:free) and resolves known slug aliases.
|
||||
|
||||
### Example Usage
|
||||
|
||||
<!-- UsageSnippet language="python" operationID="getModel" method="get" path="/model/{author}/{slug}" -->
|
||||
```python
|
||||
from openrouter import OpenRouter
|
||||
import os
|
||||
|
||||
|
||||
with OpenRouter(
|
||||
http_referer="<value>",
|
||||
x_open_router_title="<value>",
|
||||
x_open_router_categories="<value>",
|
||||
api_key=os.getenv("OPENROUTER_API_KEY", ""),
|
||||
) as open_router:
|
||||
|
||||
res = open_router.models.get(author="openai", slug="gpt-4")
|
||||
|
||||
# Handle response
|
||||
print(res)
|
||||
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `author` | *str* | :heavy_check_mark: | The author/organization of the model | openai |
|
||||
| `slug` | *str* | :heavy_check_mark: | The model slug, optionally including a variant suffix (e.g. gpt-4 or gpt-4:free) | gpt-4 |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
|
||||
**[components.ModelResponse](../../components/modelresponse.md)**
|
||||
|
||||
### Errors
|
||||
|
||||
| Error Type | Status Code | Content Type |
|
||||
| ---------------------------------- | ---------------------------------- | ---------------------------------- |
|
||||
| errors.NotFoundResponseError | 404 | application/json |
|
||||
| errors.InternalServerResponseError | 500 | application/json |
|
||||
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
|
||||
|
||||
## list
|
||||
|
||||
List all models and their properties
|
||||
@@ -38,15 +88,27 @@ with OpenRouter(
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `category` | [Optional[operations.Category]](../../operations/category.md) | :heavy_minus_sign: | Filter models by use case category | programming |
|
||||
| `supported_parameters` | *Optional[str]* | :heavy_minus_sign: | Filter models by supported parameter (comma-separated) | temperature |
|
||||
| `output_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by output modality. Accepts a comma-separated list of modalities (text, image, audio, embeddings) or "all" to include all models. Defaults to "text". | text |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `category` | [Optional[operations.GetModelsCategory]](../../operations/getmodelscategory.md) | :heavy_minus_sign: | Filter models by use case category | programming |
|
||||
| `supported_parameters` | *Optional[str]* | :heavy_minus_sign: | Filter models by supported parameter (comma-separated) | temperature |
|
||||
| `output_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by output modality. Accepts a comma-separated list of modalities (text, image, audio, embeddings) or "all" to include all models. Defaults to "text". | text |
|
||||
| `sort` | [Optional[operations.GetModelsSort]](../../operations/getmodelssort.md) | :heavy_minus_sign: | Sort the returned models server-side. Prefer this over fetching the full list and sorting client-side. Options: pricing-low-to-high, pricing-high-to-low (average prompt/completion price), context-high-to-low (context length), throughput-high-to-low, latency-low-to-high (recent median performance), most-popular, top-weekly (tokens processed in the last week), newest (creation date), intelligence-high-to-low (Artificial Analysis intelligence index), design-arena-elo-high-to-low (best Design Arena ELO across arenas). Models without a score for the chosen benchmark are placed last. When omitted, the existing default ordering is preserved. | newest |
|
||||
| `q` | *Optional[str]* | :heavy_minus_sign: | Free-text search by model name or slug. | gpt-4 |
|
||||
| `input_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by input modality. Comma-separated list of: text, image, audio, file. | text,image |
|
||||
| `context` | *Optional[int]* | :heavy_minus_sign: | Minimum context length (tokens). Models with smaller context are excluded. | 128000 |
|
||||
| `min_price` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum prompt price in $/M tokens. | 0 |
|
||||
| `max_price` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum prompt price in $/M tokens. | 10 |
|
||||
| `arch` | *Optional[str]* | :heavy_minus_sign: | Filter models by architecture/model family (e.g. GPT, Claude, Gemini, Llama). | GPT |
|
||||
| `model_authors` | *Optional[str]* | :heavy_minus_sign: | Filter models by the organization that created the model. Comma-separated list of author slugs. | openai,anthropic |
|
||||
| `providers` | *Optional[str]* | :heavy_minus_sign: | Filter models by hosting provider. Comma-separated list of provider names. | OpenAI,Anthropic |
|
||||
| `distillable` | [Optional[operations.Distillable]](../../operations/distillable.md) | :heavy_minus_sign: | Filter by distillation capability. "true" returns only distillable models, "false" excludes them. | true |
|
||||
| `zdr` | [Optional[operations.Zdr]](../../operations/zdr.md) | :heavy_minus_sign: | When set to "true", return only models with zero data retention endpoints. | true |
|
||||
| `region` | [Optional[operations.Region]](../../operations/region.md) | :heavy_minus_sign: | Filter to models with endpoints in the given data region. Currently only "eu" is supported. | eu |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ with OpenRouter(
|
||||
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `callback_url` | *str* | :heavy_check_mark: | The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed. | https://myapp.com/auth/callback |
|
||||
| `callback_url` | *str* | :heavy_check_mark: | The callback URL to redirect to after authorization. Supports https URLs and localhost/127.0.0.1 URLs on any port for local CLI tools. | https://myapp.com/auth/callback |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
@@ -100,6 +100,7 @@ with OpenRouter(
|
||||
| `key_label` | *Optional[str]* | :heavy_minus_sign: | Optional custom label for the API key. Defaults to the app name if not provided. | My Custom Key |
|
||||
| `limit` | *Optional[float]* | :heavy_minus_sign: | Credit limit for the API key to be created | 100 |
|
||||
| `usage_limit_type` | [Optional[operations.UsageLimitType]](../../operations/usagelimittype.md) | :heavy_minus_sign: | Optional credit limit reset interval. When set, the credit limit resets on this interval. | monthly |
|
||||
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Optional workspace ID to associate the API key with | |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
@@ -112,6 +113,7 @@ with OpenRouter(
|
||||
| ---------------------------------- | ---------------------------------- | ---------------------------------- |
|
||||
| errors.BadRequestResponseError | 400 | application/json |
|
||||
| errors.UnauthorizedResponseError | 401 | application/json |
|
||||
| errors.ForbiddenResponseError | 403 | application/json |
|
||||
| errors.ConflictResponseError | 409 | application/json |
|
||||
| errors.InternalServerResponseError | 500 | application/json |
|
||||
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
|
||||
@@ -27,7 +27,7 @@ with OpenRouter(
|
||||
api_key=os.getenv("OPENROUTER_API_KEY", ""),
|
||||
) as open_router:
|
||||
|
||||
res = open_router.beta.responses.send(input="Tell me a joke", model="openai/gpt-4o", service_tier="auto", stream=False)
|
||||
res = open_router.beta.responses.send(x_open_router_metadata="enabled", input="Tell me a joke", model="openai/gpt-4o", service_tier="auto", stream=False)
|
||||
|
||||
with res as event_stream:
|
||||
for event in event_stream:
|
||||
@@ -38,46 +38,50 @@ with OpenRouter(
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `background` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
|
||||
| `frequency_penalty` | *Optional[float]* | :heavy_minus_sign: | N/A | |
|
||||
| `image_config` | Dict[str, [components.ResponsesRequestImageConfig](../../components/responsesrequestimageconfig.md)] | :heavy_minus_sign: | Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/features/multimodal/image-generation for more details. | {<br/>"aspect_ratio": "16:9"<br/>} |
|
||||
| `include` | List[[components.ResponseIncludesEnum](../../components/responseincludesenum.md)] | :heavy_minus_sign: | N/A | |
|
||||
| `input` | [Optional[components.InputsUnion]](../../components/inputsunion.md) | :heavy_minus_sign: | Input for a response request - can be a string or array of items | [<br/>{<br/>"content": "What is the weather today?",<br/>"role": "user"<br/>}<br/>] |
|
||||
| `instructions` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
| `max_output_tokens` | *Optional[int]* | :heavy_minus_sign: | N/A | |
|
||||
| `max_tool_calls` | *Optional[int]* | :heavy_minus_sign: | N/A | |
|
||||
| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. | {<br/>"session_id": "abc-def-ghi",<br/>"user_id": "123"<br/>} |
|
||||
| `modalities` | List[[components.OutputModalityEnum](../../components/outputmodalityenum.md)] | :heavy_minus_sign: | Output modalities for the response. Supported values are "text" and "image". | [<br/>"text",<br/>"image"<br/>] |
|
||||
| `model` | *Optional[str]* | :heavy_minus_sign: | N/A | |
|
||||
| `models` | List[*str*] | :heavy_minus_sign: | N/A | |
|
||||
| `parallel_tool_calls` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
|
||||
| `plugins` | List[[components.ResponsesRequestPlugin](../../components/responsesrequestplugin.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
|
||||
| `presence_penalty` | *Optional[float]* | :heavy_minus_sign: | N/A | |
|
||||
| `previous_response_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
| `prompt` | [OptionalNullable[components.StoredPromptTemplate]](../../components/storedprompttemplate.md) | :heavy_minus_sign: | N/A | {<br/>"id": "prompt-abc123",<br/>"variables": {<br/>"name": "John"<br/>}<br/>} |
|
||||
| `prompt_cache_key` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
| `provider` | [OptionalNullable[components.ProviderPreferences]](../../components/providerpreferences.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | {<br/>"allow_fallbacks": true<br/>} |
|
||||
| `reasoning` | [OptionalNullable[components.ReasoningConfig]](../../components/reasoningconfig.md) | :heavy_minus_sign: | Configuration for reasoning mode in the response | {<br/>"effort": "medium",<br/>"summary": "auto"<br/>} |
|
||||
| `safety_identifier` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
| `service_tier` | [OptionalNullable[components.ResponsesRequestServiceTier]](../../components/responsesrequestservicetier.md) | :heavy_minus_sign: | N/A | |
|
||||
| `session_id` | *Optional[str]* | :heavy_minus_sign: | A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters. | |
|
||||
| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | |
|
||||
| `temperature` | *Optional[float]* | :heavy_minus_sign: | N/A | |
|
||||
| `text` | [Optional[components.TextExtendedConfig]](../../components/textextendedconfig.md) | :heavy_minus_sign: | Text output configuration including format and verbosity | {<br/>"format": {<br/>"type": "text"<br/>},<br/>"verbosity": "medium"<br/>} |
|
||||
| `tool_choice` | [Optional[components.OpenAIResponsesToolChoiceUnion]](../../components/openairesponsestoolchoiceunion.md) | :heavy_minus_sign: | N/A | auto |
|
||||
| `tools` | List[[components.ResponsesRequestToolUnion](../../components/responsesrequesttoolunion.md)] | :heavy_minus_sign: | N/A | |
|
||||
| `top_k` | *Optional[int]* | :heavy_minus_sign: | N/A | |
|
||||
| `top_logprobs` | *Optional[int]* | :heavy_minus_sign: | N/A | |
|
||||
| `top_p` | *Optional[float]* | :heavy_minus_sign: | N/A | |
|
||||
| `trace` | [Optional[components.TraceConfig]](../../components/traceconfig.md) | :heavy_minus_sign: | Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations. | {<br/>"trace_id": "trace-abc123",<br/>"trace_name": "my-app-trace"<br/>} |
|
||||
| `truncation` | [OptionalNullable[components.OpenAIResponsesTruncation]](../../components/openairesponsestruncation.md) | :heavy_minus_sign: | N/A | auto |
|
||||
| `user` | *Optional[str]* | :heavy_minus_sign: | A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 256 characters. | |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
| Parameter | Type | Required | Description | Example |
|
||||
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> | |
|
||||
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
|
||||
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
|
||||
| `x_open_router_metadata` | [Optional[components.MetadataLevel]](../../components/metadatalevel.md) | :heavy_minus_sign: | Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility. | enabled |
|
||||
| `background` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
|
||||
| `cache_control` | [Optional[components.AnthropicCacheControlDirective]](../../components/anthropiccachecontroldirective.md) | :heavy_minus_sign: | Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models. | {<br/>"type": "ephemeral"<br/>} |
|
||||
| `debug` | [Optional[components.ChatDebugOptions]](../../components/chatdebugoptions.md) | :heavy_minus_sign: | Debug options for inspecting request transformations (streaming only) | {<br/>"echo_upstream_body": true<br/>} |
|
||||
| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | |
|
||||
| `image_config` | Dict[str, [components.ImageConfig](../../components/imageconfig.md)] | :heavy_minus_sign: | Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details. | {<br/>"aspect_ratio": "16:9",<br/>"quality": "high"<br/>} |
|
||||
| `include` | List[[components.ResponseIncludesEnum](../../components/responseincludesenum.md)] | :heavy_minus_sign: | N/A | |
|
||||
| `input` | [Optional[components.InputsUnion]](../../components/inputsunion.md) | :heavy_minus_sign: | Input for a response request - can be a string or array of items | [<br/>{<br/>"content": "What is the weather today?",<br/>"role": "user"<br/>}<br/>] |
|
||||
| `instructions` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
| `max_output_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | |
|
||||
| `max_tool_calls` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | |
|
||||
| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. | {<br/>"session_id": "abc-def-ghi",<br/>"user_id": "123"<br/>} |
|
||||
| `modalities` | List[[components.OutputModalityEnum](../../components/outputmodalityenum.md)] | :heavy_minus_sign: | Output modalities for the response. Supported values are "text" and "image". | [<br/>"text",<br/>"image"<br/>] |
|
||||
| `model` | *Optional[str]* | :heavy_minus_sign: | N/A | |
|
||||
| `models` | List[*str*] | :heavy_minus_sign: | N/A | |
|
||||
| `parallel_tool_calls` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
|
||||
| `plugins` | List[[components.ResponsesRequestPlugin](../../components/responsesrequestplugin.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
|
||||
| `presence_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | |
|
||||
| `previous_response_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
| `prompt` | [OptionalNullable[components.StoredPromptTemplate]](../../components/storedprompttemplate.md) | :heavy_minus_sign: | N/A | {<br/>"id": "prompt-abc123",<br/>"variables": {<br/>"name": "John"<br/>}<br/>} |
|
||||
| `prompt_cache_key` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
| `provider` | [OptionalNullable[components.ProviderPreferences]](../../components/providerpreferences.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | {<br/>"allow_fallbacks": true<br/>} |
|
||||
| `reasoning` | [OptionalNullable[components.ReasoningConfig]](../../components/reasoningconfig.md) | :heavy_minus_sign: | Configuration for reasoning mode in the response | {<br/>"effort": "medium",<br/>"summary": "auto"<br/>} |
|
||||
| `safety_identifier` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
|
||||
| `service_tier` | [OptionalNullable[components.ResponsesRequestServiceTier]](../../components/responsesrequestservicetier.md) | :heavy_minus_sign: | N/A | |
|
||||
| `session_id` | *Optional[str]* | :heavy_minus_sign: | A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters. | |
|
||||
| `stop_server_tools_when` | List[[components.StopServerToolsWhenCondition](../../components/stopservertoolswhencondition.md)] | :heavy_minus_sign: | Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`. | [<br/>{<br/>"step_count": 5,<br/>"type": "step_count_is"<br/>},<br/>{<br/>"max_cost_in_dollars": 0.5,<br/>"type": "max_cost"<br/>}<br/>] |
|
||||
| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | |
|
||||
| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | |
|
||||
| `text` | [Optional[components.TextExtendedConfig]](../../components/textextendedconfig.md) | :heavy_minus_sign: | Text output configuration including format and verbosity | {<br/>"format": {<br/>"type": "text"<br/>},<br/>"verbosity": "medium"<br/>} |
|
||||
| `tool_choice` | [Optional[components.OpenAIResponsesToolChoiceUnion]](../../components/openairesponsestoolchoiceunion.md) | :heavy_minus_sign: | N/A | auto |
|
||||
| `tools` | List[[components.ResponsesRequestToolUnion](../../components/responsesrequesttoolunion.md)] | :heavy_minus_sign: | N/A | |
|
||||
| `top_k` | *Optional[int]* | :heavy_minus_sign: | N/A | |
|
||||
| `top_logprobs` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | |
|
||||
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | |
|
||||
| `trace` | [Optional[components.TraceConfig]](../../components/traceconfig.md) | :heavy_minus_sign: | Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations. | {<br/>"trace_id": "trace-abc123",<br/>"trace_name": "my-app-trace"<br/>} |
|
||||
| `truncation` | [OptionalNullable[components.OpenAIResponsesTruncation]](../../components/openairesponsestruncation.md) | :heavy_minus_sign: | N/A | auto |
|
||||
| `user` | *Optional[str]* | :heavy_minus_sign: | A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 256 characters. | |
|
||||
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
|
||||
|
||||
### Response
|
||||
|
||||
@@ -90,6 +94,7 @@ with OpenRouter(
|
||||
| errors.BadRequestResponseError | 400 | application/json |
|
||||
| errors.UnauthorizedResponseError | 401 | application/json |
|
||||
| errors.PaymentRequiredResponseError | 402 | application/json |
|
||||
| errors.ForbiddenResponseError | 403 | application/json |
|
||||
| errors.NotFoundResponseError | 404 | application/json |
|
||||
| errors.RequestTimeoutResponseError | 408 | application/json |
|
||||
| errors.PayloadTooLargeResponseError | 413 | application/json |
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "openrouter"
|
||||
version = "0.9.0"
|
||||
version = "0.10.8"
|
||||
description = "Official Python Client SDK for OpenRouter."
|
||||
authors = [{ name = "OpenRouter" },]
|
||||
readme = "README-PYPI.md"
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
import importlib.metadata
|
||||
|
||||
__title__: str = "openrouter"
|
||||
__version__: str = "0.9.0"
|
||||
__version__: str = "0.10.8"
|
||||
__openapi_doc_version__: str = "1.0.0"
|
||||
__gen_version__: str = "2.788.4"
|
||||
__user_agent__: str = "speakeasy-sdk/python 0.9.0 2.788.4 1.0.0 openrouter"
|
||||
__user_agent__: str = "speakeasy-sdk/python 0.10.8 2.788.4 1.0.0 openrouter"
|
||||
|
||||
try:
|
||||
if __package__ is not None:
|
||||
|
||||
@@ -257,6 +257,7 @@ class APIKeys(BaseSDK):
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
include_disabled: Optional[bool] = None,
|
||||
offset: Optional[int] = None,
|
||||
workspace_id: Optional[str] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
@@ -275,6 +276,7 @@ class APIKeys(BaseSDK):
|
||||
|
||||
:param include_disabled: Whether to include disabled API keys in the response
|
||||
:param offset: Number of API keys to skip for pagination
|
||||
:param workspace_id: Filter API keys by workspace ID. By default, keys in the default workspace are returned.
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
@@ -296,6 +298,7 @@ class APIKeys(BaseSDK):
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
include_disabled=include_disabled,
|
||||
offset=offset,
|
||||
workspace_id=workspace_id,
|
||||
)
|
||||
|
||||
req = self._build_request(
|
||||
@@ -386,6 +389,7 @@ class APIKeys(BaseSDK):
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
include_disabled: Optional[bool] = None,
|
||||
offset: Optional[int] = None,
|
||||
workspace_id: Optional[str] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
@@ -404,6 +408,7 @@ class APIKeys(BaseSDK):
|
||||
|
||||
:param include_disabled: Whether to include disabled API keys in the response
|
||||
:param offset: Number of API keys to skip for pagination
|
||||
:param workspace_id: Filter API keys by workspace ID. By default, keys in the default workspace are returned.
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
@@ -425,6 +430,7 @@ class APIKeys(BaseSDK):
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
include_disabled=include_disabled,
|
||||
offset=offset,
|
||||
workspace_id=workspace_id,
|
||||
)
|
||||
|
||||
req = self._build_request_async(
|
||||
@@ -517,8 +523,9 @@ class APIKeys(BaseSDK):
|
||||
creator_user_id: OptionalNullable[str] = UNSET,
|
||||
expires_at: OptionalNullable[datetime] = UNSET,
|
||||
include_byok_in_limit: Optional[bool] = None,
|
||||
limit: Optional[float] = None,
|
||||
limit: OptionalNullable[float] = UNSET,
|
||||
limit_reset: OptionalNullable[operations.CreateKeysLimitReset] = UNSET,
|
||||
workspace_id: Optional[str] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
@@ -526,7 +533,7 @@ class APIKeys(BaseSDK):
|
||||
) -> operations.CreateKeysResponse:
|
||||
r"""Create a new API key
|
||||
|
||||
Create a new API key for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
Create a new API key for the authenticated user. The plaintext `key` is returned only in this response. Treat it as a write-only, sensitive value; it cannot be retrieved later. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
|
||||
:param name: Name for the new API key
|
||||
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
|
||||
@@ -541,6 +548,7 @@ class APIKeys(BaseSDK):
|
||||
:param include_byok_in_limit: Whether to include BYOK usage in the limit
|
||||
:param limit: Optional spending limit for the API key in USD
|
||||
:param limit_reset: Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.
|
||||
:param workspace_id: The workspace to create the API key in. Defaults to the default workspace if not provided.
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
@@ -567,6 +575,7 @@ class APIKeys(BaseSDK):
|
||||
limit=limit,
|
||||
limit_reset=limit_reset,
|
||||
name=name,
|
||||
workspace_id=workspace_id,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -622,7 +631,7 @@ class APIKeys(BaseSDK):
|
||||
),
|
||||
),
|
||||
request=req,
|
||||
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
|
||||
error_status_codes=["400", "401", "403", "429", "4XX", "500", "5XX"],
|
||||
retry_config=retry_config,
|
||||
)
|
||||
|
||||
@@ -639,6 +648,11 @@ class APIKeys(BaseSDK):
|
||||
errors.UnauthorizedResponseErrorData, http_res
|
||||
)
|
||||
raise errors.UnauthorizedResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "403", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.ForbiddenResponseErrorData, http_res
|
||||
)
|
||||
raise errors.ForbiddenResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "429", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.TooManyRequestsResponseErrorData, http_res
|
||||
@@ -672,8 +686,9 @@ class APIKeys(BaseSDK):
|
||||
creator_user_id: OptionalNullable[str] = UNSET,
|
||||
expires_at: OptionalNullable[datetime] = UNSET,
|
||||
include_byok_in_limit: Optional[bool] = None,
|
||||
limit: Optional[float] = None,
|
||||
limit: OptionalNullable[float] = UNSET,
|
||||
limit_reset: OptionalNullable[operations.CreateKeysLimitReset] = UNSET,
|
||||
workspace_id: Optional[str] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
@@ -681,7 +696,7 @@ class APIKeys(BaseSDK):
|
||||
) -> operations.CreateKeysResponse:
|
||||
r"""Create a new API key
|
||||
|
||||
Create a new API key for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
Create a new API key for the authenticated user. The plaintext `key` is returned only in this response. Treat it as a write-only, sensitive value; it cannot be retrieved later. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
|
||||
:param name: Name for the new API key
|
||||
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
|
||||
@@ -696,6 +711,7 @@ class APIKeys(BaseSDK):
|
||||
:param include_byok_in_limit: Whether to include BYOK usage in the limit
|
||||
:param limit: Optional spending limit for the API key in USD
|
||||
:param limit_reset: Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.
|
||||
:param workspace_id: The workspace to create the API key in. Defaults to the default workspace if not provided.
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
@@ -722,6 +738,7 @@ class APIKeys(BaseSDK):
|
||||
limit=limit,
|
||||
limit_reset=limit_reset,
|
||||
name=name,
|
||||
workspace_id=workspace_id,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -777,7 +794,7 @@ class APIKeys(BaseSDK):
|
||||
),
|
||||
),
|
||||
request=req,
|
||||
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
|
||||
error_status_codes=["400", "401", "403", "429", "4XX", "500", "5XX"],
|
||||
retry_config=retry_config,
|
||||
)
|
||||
|
||||
@@ -794,6 +811,11 @@ class APIKeys(BaseSDK):
|
||||
errors.UnauthorizedResponseErrorData, http_res
|
||||
)
|
||||
raise errors.UnauthorizedResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "403", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.ForbiddenResponseErrorData, http_res
|
||||
)
|
||||
raise errors.ForbiddenResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "429", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.TooManyRequestsResponseErrorData, http_res
|
||||
@@ -1350,7 +1372,7 @@ class APIKeys(BaseSDK):
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
disabled: Optional[bool] = None,
|
||||
include_byok_in_limit: Optional[bool] = None,
|
||||
limit: Optional[float] = None,
|
||||
limit: OptionalNullable[float] = UNSET,
|
||||
limit_reset: OptionalNullable[operations.UpdateKeysLimitReset] = UNSET,
|
||||
name: Optional[str] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
@@ -1510,7 +1532,7 @@ class APIKeys(BaseSDK):
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
disabled: Optional[bool] = None,
|
||||
include_byok_in_limit: Optional[bool] = None,
|
||||
limit: Optional[float] = None,
|
||||
limit: OptionalNullable[float] = UNSET,
|
||||
limit_reset: OptionalNullable[operations.UpdateKeysLimitReset] = UNSET,
|
||||
name: Optional[str] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
|
||||
|
||||
from .basesdk import BaseSDK
|
||||
from openrouter import components, errors, operations, utils
|
||||
from openrouter._hooks import HookContext
|
||||
from openrouter.types import OptionalNullable, UNSET
|
||||
from openrouter.utils import get_security_from_env
|
||||
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
|
||||
from typing import Any, Mapping, Optional
|
||||
|
||||
|
||||
class Benchmarks(BaseSDK):
|
||||
r"""Benchmarks endpoints"""
|
||||
|
||||
def get_benchmarks(
|
||||
self,
|
||||
*,
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
source: Optional[operations.Source] = None,
|
||||
task_type: Optional[operations.TaskType] = None,
|
||||
arena: Optional[operations.Arena] = None,
|
||||
category: Optional[str] = None,
|
||||
max_results: Optional[int] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
http_headers: Optional[Mapping[str, str]] = None,
|
||||
) -> components.UnifiedBenchmarksResponse:
|
||||
r"""List Benchmarks
|
||||
|
||||
Unified benchmark endpoint that aggregates scores from multiple benchmark sources (Artificial Analysis, Design Arena). Filter by source to reproduce the exact shapes from the legacy per-source endpoints, or use task_type to find models suited for specific workloads. Authenticate with any valid OpenRouter API key. Rate-limited to 30 requests/minute per key and 500 requests/day per account.
|
||||
|
||||
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
|
||||
This is used to track API usage per application.
|
||||
|
||||
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param source: Benchmark source to query. Determines the shape of the returned items. When omitted, returns results from all sources.
|
||||
:param task_type: Filter results by task type. For Artificial Analysis, maps to the corresponding index. For Design Arena, maps to the matching category.
|
||||
:param arena: Design Arena only: arena to query. Defaults to `models` when source is `design-arena`.
|
||||
:param category: Design Arena only: category within the arena (e.g. `codecategories`, `uicomponent`, `gamedev`, `3d`, `dataviz`, `image`, `video`, `svg`). When omitted, returns all categories.
|
||||
:param max_results: Maximum number of items to return. When omitted, all matching results are returned.
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
:param http_headers: Additional headers to set or replace on requests.
|
||||
"""
|
||||
base_url = None
|
||||
url_variables = None
|
||||
if timeout_ms is None:
|
||||
timeout_ms = self.sdk_configuration.timeout_ms
|
||||
|
||||
if server_url is not None:
|
||||
base_url = server_url
|
||||
else:
|
||||
base_url = self._get_url(base_url, url_variables)
|
||||
|
||||
request = operations.GetBenchmarksRequest(
|
||||
http_referer=http_referer,
|
||||
x_open_router_title=x_open_router_title,
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
source=source,
|
||||
task_type=task_type,
|
||||
arena=arena,
|
||||
category=category,
|
||||
max_results=max_results,
|
||||
)
|
||||
|
||||
req = self._build_request(
|
||||
method="GET",
|
||||
path="/benchmarks",
|
||||
base_url=base_url,
|
||||
url_variables=url_variables,
|
||||
request=request,
|
||||
request_body_required=False,
|
||||
request_has_path_params=False,
|
||||
request_has_query_params=True,
|
||||
user_agent_header="user-agent",
|
||||
accept_header_value="application/json",
|
||||
http_headers=http_headers,
|
||||
_globals=operations.GetBenchmarksGlobals(
|
||||
http_referer=self.sdk_configuration.globals.http_referer,
|
||||
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
|
||||
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
|
||||
),
|
||||
security=self.sdk_configuration.security,
|
||||
allow_empty_value=None,
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
|
||||
if retries == UNSET:
|
||||
if self.sdk_configuration.retry_config is not UNSET:
|
||||
retries = self.sdk_configuration.retry_config
|
||||
else:
|
||||
retries = utils.RetryConfig(
|
||||
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
|
||||
)
|
||||
|
||||
retry_config = None
|
||||
if isinstance(retries, utils.RetryConfig):
|
||||
retry_config = (retries, ["5XX"])
|
||||
|
||||
http_res = self.do_request(
|
||||
hook_ctx=HookContext(
|
||||
config=self.sdk_configuration,
|
||||
base_url=base_url or "",
|
||||
operation_id="getBenchmarks",
|
||||
oauth2_scopes=None,
|
||||
security_source=get_security_from_env(
|
||||
self.sdk_configuration.security, components.Security
|
||||
),
|
||||
),
|
||||
request=req,
|
||||
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
|
||||
retry_config=retry_config,
|
||||
)
|
||||
|
||||
response_data: Any = None
|
||||
if utils.match_response(http_res, "200", "application/json"):
|
||||
return unmarshal_json_response(
|
||||
components.UnifiedBenchmarksResponse, http_res
|
||||
)
|
||||
if utils.match_response(http_res, "400", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.BadRequestResponseErrorData, http_res
|
||||
)
|
||||
raise errors.BadRequestResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "401", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.UnauthorizedResponseErrorData, http_res
|
||||
)
|
||||
raise errors.UnauthorizedResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "429", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.TooManyRequestsResponseErrorData, http_res
|
||||
)
|
||||
raise errors.TooManyRequestsResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "500", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.InternalServerResponseErrorData, http_res
|
||||
)
|
||||
raise errors.InternalServerResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "4XX", "*"):
|
||||
http_res_text = utils.stream_to_text(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
if utils.match_response(http_res, "5XX", "*"):
|
||||
http_res_text = utils.stream_to_text(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
|
||||
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
|
||||
|
||||
async def get_benchmarks_async(
|
||||
self,
|
||||
*,
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
source: Optional[operations.Source] = None,
|
||||
task_type: Optional[operations.TaskType] = None,
|
||||
arena: Optional[operations.Arena] = None,
|
||||
category: Optional[str] = None,
|
||||
max_results: Optional[int] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
http_headers: Optional[Mapping[str, str]] = None,
|
||||
) -> components.UnifiedBenchmarksResponse:
|
||||
r"""List Benchmarks
|
||||
|
||||
Unified benchmark endpoint that aggregates scores from multiple benchmark sources (Artificial Analysis, Design Arena). Filter by source to reproduce the exact shapes from the legacy per-source endpoints, or use task_type to find models suited for specific workloads. Authenticate with any valid OpenRouter API key. Rate-limited to 30 requests/minute per key and 500 requests/day per account.
|
||||
|
||||
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
|
||||
This is used to track API usage per application.
|
||||
|
||||
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param source: Benchmark source to query. Determines the shape of the returned items. When omitted, returns results from all sources.
|
||||
:param task_type: Filter results by task type. For Artificial Analysis, maps to the corresponding index. For Design Arena, maps to the matching category.
|
||||
:param arena: Design Arena only: arena to query. Defaults to `models` when source is `design-arena`.
|
||||
:param category: Design Arena only: category within the arena (e.g. `codecategories`, `uicomponent`, `gamedev`, `3d`, `dataviz`, `image`, `video`, `svg`). When omitted, returns all categories.
|
||||
:param max_results: Maximum number of items to return. When omitted, all matching results are returned.
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
:param http_headers: Additional headers to set or replace on requests.
|
||||
"""
|
||||
base_url = None
|
||||
url_variables = None
|
||||
if timeout_ms is None:
|
||||
timeout_ms = self.sdk_configuration.timeout_ms
|
||||
|
||||
if server_url is not None:
|
||||
base_url = server_url
|
||||
else:
|
||||
base_url = self._get_url(base_url, url_variables)
|
||||
|
||||
request = operations.GetBenchmarksRequest(
|
||||
http_referer=http_referer,
|
||||
x_open_router_title=x_open_router_title,
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
source=source,
|
||||
task_type=task_type,
|
||||
arena=arena,
|
||||
category=category,
|
||||
max_results=max_results,
|
||||
)
|
||||
|
||||
req = self._build_request_async(
|
||||
method="GET",
|
||||
path="/benchmarks",
|
||||
base_url=base_url,
|
||||
url_variables=url_variables,
|
||||
request=request,
|
||||
request_body_required=False,
|
||||
request_has_path_params=False,
|
||||
request_has_query_params=True,
|
||||
user_agent_header="user-agent",
|
||||
accept_header_value="application/json",
|
||||
http_headers=http_headers,
|
||||
_globals=operations.GetBenchmarksGlobals(
|
||||
http_referer=self.sdk_configuration.globals.http_referer,
|
||||
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
|
||||
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
|
||||
),
|
||||
security=self.sdk_configuration.security,
|
||||
allow_empty_value=None,
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
|
||||
if retries == UNSET:
|
||||
if self.sdk_configuration.retry_config is not UNSET:
|
||||
retries = self.sdk_configuration.retry_config
|
||||
else:
|
||||
retries = utils.RetryConfig(
|
||||
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
|
||||
)
|
||||
|
||||
retry_config = None
|
||||
if isinstance(retries, utils.RetryConfig):
|
||||
retry_config = (retries, ["5XX"])
|
||||
|
||||
http_res = await self.do_request_async(
|
||||
hook_ctx=HookContext(
|
||||
config=self.sdk_configuration,
|
||||
base_url=base_url or "",
|
||||
operation_id="getBenchmarks",
|
||||
oauth2_scopes=None,
|
||||
security_source=get_security_from_env(
|
||||
self.sdk_configuration.security, components.Security
|
||||
),
|
||||
),
|
||||
request=req,
|
||||
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
|
||||
retry_config=retry_config,
|
||||
)
|
||||
|
||||
response_data: Any = None
|
||||
if utils.match_response(http_res, "200", "application/json"):
|
||||
return unmarshal_json_response(
|
||||
components.UnifiedBenchmarksResponse, http_res
|
||||
)
|
||||
if utils.match_response(http_res, "400", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.BadRequestResponseErrorData, http_res
|
||||
)
|
||||
raise errors.BadRequestResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "401", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.UnauthorizedResponseErrorData, http_res
|
||||
)
|
||||
raise errors.UnauthorizedResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "429", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.TooManyRequestsResponseErrorData, http_res
|
||||
)
|
||||
raise errors.TooManyRequestsResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "500", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.InternalServerResponseErrorData, http_res
|
||||
)
|
||||
raise errors.InternalServerResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "4XX", "*"):
|
||||
http_res_text = await utils.stream_to_text_async(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
if utils.match_response(http_res, "5XX", "*"):
|
||||
http_res_text = await utils.stream_to_text_async(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
|
||||
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
|
||||
@@ -2,11 +2,14 @@
|
||||
|
||||
from .basesdk import BaseSDK
|
||||
from .sdkconfiguration import SDKConfiguration
|
||||
from openrouter.beta_analytics import BetaAnalytics
|
||||
from openrouter.responses import Responses
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class Beta(BaseSDK):
|
||||
analytics: BetaAnalytics
|
||||
r"""beta.Analytics endpoints"""
|
||||
responses: Responses
|
||||
r"""beta.responses endpoints"""
|
||||
|
||||
@@ -18,4 +21,7 @@ class Beta(BaseSDK):
|
||||
self._init_sdks()
|
||||
|
||||
def _init_sdks(self):
|
||||
self.analytics = BetaAnalytics(
|
||||
self.sdk_configuration, parent_ref=self.parent_ref
|
||||
)
|
||||
self.responses = Responses(self.sdk_configuration, parent_ref=self.parent_ref)
|
||||
|
||||
@@ -0,0 +1,619 @@
|
||||
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
|
||||
|
||||
from .basesdk import BaseSDK
|
||||
from openrouter import components, errors, operations, utils
|
||||
from openrouter._hooks import HookContext
|
||||
from openrouter.types import OptionalNullable, UNSET
|
||||
from openrouter.utils import get_security_from_env
|
||||
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
|
||||
from typing import Any, List, Mapping, Optional, Union
|
||||
|
||||
|
||||
class BetaAnalytics(BaseSDK):
|
||||
r"""beta.Analytics endpoints"""
|
||||
|
||||
def get_analytics_meta(
|
||||
self,
|
||||
*,
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
http_headers: Optional[Mapping[str, str]] = None,
|
||||
) -> operations.GetAnalyticsMetaResponse:
|
||||
r"""Get available analytics metrics and dimensions
|
||||
|
||||
Returns the available metrics, dimensions, filter operators, and granularities for the analytics query endpoint. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
|
||||
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
|
||||
This is used to track API usage per application.
|
||||
|
||||
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
:param http_headers: Additional headers to set or replace on requests.
|
||||
"""
|
||||
base_url = None
|
||||
url_variables = None
|
||||
if timeout_ms is None:
|
||||
timeout_ms = self.sdk_configuration.timeout_ms
|
||||
|
||||
if server_url is not None:
|
||||
base_url = server_url
|
||||
else:
|
||||
base_url = self._get_url(base_url, url_variables)
|
||||
|
||||
request = operations.GetAnalyticsMetaRequest(
|
||||
http_referer=http_referer,
|
||||
x_open_router_title=x_open_router_title,
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
)
|
||||
|
||||
req = self._build_request(
|
||||
method="GET",
|
||||
path="/analytics/meta",
|
||||
base_url=base_url,
|
||||
url_variables=url_variables,
|
||||
request=request,
|
||||
request_body_required=False,
|
||||
request_has_path_params=False,
|
||||
request_has_query_params=True,
|
||||
user_agent_header="user-agent",
|
||||
accept_header_value="application/json",
|
||||
http_headers=http_headers,
|
||||
_globals=operations.GetAnalyticsMetaGlobals(
|
||||
http_referer=self.sdk_configuration.globals.http_referer,
|
||||
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
|
||||
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
|
||||
),
|
||||
security=self.sdk_configuration.security,
|
||||
allow_empty_value=None,
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
|
||||
if retries == UNSET:
|
||||
if self.sdk_configuration.retry_config is not UNSET:
|
||||
retries = self.sdk_configuration.retry_config
|
||||
else:
|
||||
retries = utils.RetryConfig(
|
||||
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
|
||||
)
|
||||
|
||||
retry_config = None
|
||||
if isinstance(retries, utils.RetryConfig):
|
||||
retry_config = (retries, ["5XX"])
|
||||
|
||||
http_res = self.do_request(
|
||||
hook_ctx=HookContext(
|
||||
config=self.sdk_configuration,
|
||||
base_url=base_url or "",
|
||||
operation_id="getAnalyticsMeta",
|
||||
oauth2_scopes=None,
|
||||
security_source=get_security_from_env(
|
||||
self.sdk_configuration.security, components.Security
|
||||
),
|
||||
),
|
||||
request=req,
|
||||
error_status_codes=["401", "403", "4XX", "500", "5XX"],
|
||||
retry_config=retry_config,
|
||||
)
|
||||
|
||||
response_data: Any = None
|
||||
if utils.match_response(http_res, "200", "application/json"):
|
||||
return unmarshal_json_response(
|
||||
operations.GetAnalyticsMetaResponse, http_res
|
||||
)
|
||||
if utils.match_response(http_res, "401", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.UnauthorizedResponseErrorData, http_res
|
||||
)
|
||||
raise errors.UnauthorizedResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "403", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.ForbiddenResponseErrorData, http_res
|
||||
)
|
||||
raise errors.ForbiddenResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "500", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.InternalServerResponseErrorData, http_res
|
||||
)
|
||||
raise errors.InternalServerResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "4XX", "*"):
|
||||
http_res_text = utils.stream_to_text(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
if utils.match_response(http_res, "5XX", "*"):
|
||||
http_res_text = utils.stream_to_text(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
|
||||
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
|
||||
|
||||
async def get_analytics_meta_async(
|
||||
self,
|
||||
*,
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
http_headers: Optional[Mapping[str, str]] = None,
|
||||
) -> operations.GetAnalyticsMetaResponse:
|
||||
r"""Get available analytics metrics and dimensions
|
||||
|
||||
Returns the available metrics, dimensions, filter operators, and granularities for the analytics query endpoint. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
|
||||
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
|
||||
This is used to track API usage per application.
|
||||
|
||||
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
:param http_headers: Additional headers to set or replace on requests.
|
||||
"""
|
||||
base_url = None
|
||||
url_variables = None
|
||||
if timeout_ms is None:
|
||||
timeout_ms = self.sdk_configuration.timeout_ms
|
||||
|
||||
if server_url is not None:
|
||||
base_url = server_url
|
||||
else:
|
||||
base_url = self._get_url(base_url, url_variables)
|
||||
|
||||
request = operations.GetAnalyticsMetaRequest(
|
||||
http_referer=http_referer,
|
||||
x_open_router_title=x_open_router_title,
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
)
|
||||
|
||||
req = self._build_request_async(
|
||||
method="GET",
|
||||
path="/analytics/meta",
|
||||
base_url=base_url,
|
||||
url_variables=url_variables,
|
||||
request=request,
|
||||
request_body_required=False,
|
||||
request_has_path_params=False,
|
||||
request_has_query_params=True,
|
||||
user_agent_header="user-agent",
|
||||
accept_header_value="application/json",
|
||||
http_headers=http_headers,
|
||||
_globals=operations.GetAnalyticsMetaGlobals(
|
||||
http_referer=self.sdk_configuration.globals.http_referer,
|
||||
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
|
||||
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
|
||||
),
|
||||
security=self.sdk_configuration.security,
|
||||
allow_empty_value=None,
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
|
||||
if retries == UNSET:
|
||||
if self.sdk_configuration.retry_config is not UNSET:
|
||||
retries = self.sdk_configuration.retry_config
|
||||
else:
|
||||
retries = utils.RetryConfig(
|
||||
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
|
||||
)
|
||||
|
||||
retry_config = None
|
||||
if isinstance(retries, utils.RetryConfig):
|
||||
retry_config = (retries, ["5XX"])
|
||||
|
||||
http_res = await self.do_request_async(
|
||||
hook_ctx=HookContext(
|
||||
config=self.sdk_configuration,
|
||||
base_url=base_url or "",
|
||||
operation_id="getAnalyticsMeta",
|
||||
oauth2_scopes=None,
|
||||
security_source=get_security_from_env(
|
||||
self.sdk_configuration.security, components.Security
|
||||
),
|
||||
),
|
||||
request=req,
|
||||
error_status_codes=["401", "403", "4XX", "500", "5XX"],
|
||||
retry_config=retry_config,
|
||||
)
|
||||
|
||||
response_data: Any = None
|
||||
if utils.match_response(http_res, "200", "application/json"):
|
||||
return unmarshal_json_response(
|
||||
operations.GetAnalyticsMetaResponse, http_res
|
||||
)
|
||||
if utils.match_response(http_res, "401", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.UnauthorizedResponseErrorData, http_res
|
||||
)
|
||||
raise errors.UnauthorizedResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "403", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.ForbiddenResponseErrorData, http_res
|
||||
)
|
||||
raise errors.ForbiddenResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "500", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.InternalServerResponseErrorData, http_res
|
||||
)
|
||||
raise errors.InternalServerResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "4XX", "*"):
|
||||
http_res_text = await utils.stream_to_text_async(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
if utils.match_response(http_res, "5XX", "*"):
|
||||
http_res_text = await utils.stream_to_text_async(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
|
||||
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
|
||||
|
||||
def query_analytics(
|
||||
self,
|
||||
*,
|
||||
metrics: List[str],
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
dimensions: Optional[List[str]] = None,
|
||||
filters: Optional[
|
||||
Union[List[operations.Filter], List[operations.FilterTypedDict]]
|
||||
] = None,
|
||||
granularity: Optional[str] = None,
|
||||
group_limit: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
order_by: Optional[
|
||||
Union[operations.OrderBy, operations.OrderByTypedDict]
|
||||
] = None,
|
||||
time_range: Optional[
|
||||
Union[operations.TimeRange, operations.TimeRangeTypedDict]
|
||||
] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
http_headers: Optional[Mapping[str, str]] = None,
|
||||
) -> operations.QueryAnalyticsResponse:
|
||||
r"""Query analytics data
|
||||
|
||||
Execute an analytics query with specified metrics, dimensions, filters, and time range. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
|
||||
:param metrics:
|
||||
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
|
||||
This is used to track API usage per application.
|
||||
|
||||
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param dimensions:
|
||||
:param filters:
|
||||
:param granularity: Time granularity
|
||||
:param group_limit: Maximum rows per distinct combination of dimensions. When omitted on time-series queries (granularity + dimensions), auto-computed to avoid truncating time windows. Explicit values override the default and may truncate time buckets if set lower than the number of buckets in the range. Ignored when no dimensions are specified.
|
||||
:param limit: Maximum total rows returned. Defaults to 1000. On time-series queries with dimensions and no explicit group_limit, the server may raise this to accommodate the expected number of unique time-bucket/dimension combinations.
|
||||
:param order_by:
|
||||
:param time_range:
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
:param http_headers: Additional headers to set or replace on requests.
|
||||
"""
|
||||
base_url = None
|
||||
url_variables = None
|
||||
if timeout_ms is None:
|
||||
timeout_ms = self.sdk_configuration.timeout_ms
|
||||
|
||||
if server_url is not None:
|
||||
base_url = server_url
|
||||
else:
|
||||
base_url = self._get_url(base_url, url_variables)
|
||||
|
||||
request = operations.QueryAnalyticsRequest(
|
||||
http_referer=http_referer,
|
||||
x_open_router_title=x_open_router_title,
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
request_body=operations.QueryAnalyticsRequestBody(
|
||||
dimensions=dimensions,
|
||||
filters=utils.get_pydantic_model(
|
||||
filters, Optional[List[operations.Filter]]
|
||||
),
|
||||
granularity=granularity,
|
||||
group_limit=group_limit,
|
||||
limit=limit,
|
||||
metrics=metrics,
|
||||
order_by=utils.get_pydantic_model(
|
||||
order_by, Optional[operations.OrderBy]
|
||||
),
|
||||
time_range=utils.get_pydantic_model(
|
||||
time_range, Optional[operations.TimeRange]
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
req = self._build_request(
|
||||
method="POST",
|
||||
path="/analytics/query",
|
||||
base_url=base_url,
|
||||
url_variables=url_variables,
|
||||
request=request,
|
||||
request_body_required=True,
|
||||
request_has_path_params=False,
|
||||
request_has_query_params=True,
|
||||
user_agent_header="user-agent",
|
||||
accept_header_value="application/json",
|
||||
http_headers=http_headers,
|
||||
_globals=operations.QueryAnalyticsGlobals(
|
||||
http_referer=self.sdk_configuration.globals.http_referer,
|
||||
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
|
||||
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
|
||||
),
|
||||
security=self.sdk_configuration.security,
|
||||
get_serialized_body=lambda: utils.serialize_request_body(
|
||||
request.request_body,
|
||||
False,
|
||||
False,
|
||||
"json",
|
||||
operations.QueryAnalyticsRequestBody,
|
||||
),
|
||||
allow_empty_value=None,
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
|
||||
if retries == UNSET:
|
||||
if self.sdk_configuration.retry_config is not UNSET:
|
||||
retries = self.sdk_configuration.retry_config
|
||||
else:
|
||||
retries = utils.RetryConfig(
|
||||
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
|
||||
)
|
||||
|
||||
retry_config = None
|
||||
if isinstance(retries, utils.RetryConfig):
|
||||
retry_config = (retries, ["5XX"])
|
||||
|
||||
http_res = self.do_request(
|
||||
hook_ctx=HookContext(
|
||||
config=self.sdk_configuration,
|
||||
base_url=base_url or "",
|
||||
operation_id="queryAnalytics",
|
||||
oauth2_scopes=None,
|
||||
security_source=get_security_from_env(
|
||||
self.sdk_configuration.security, components.Security
|
||||
),
|
||||
),
|
||||
request=req,
|
||||
error_status_codes=["400", "401", "403", "408", "4XX", "500", "5XX"],
|
||||
retry_config=retry_config,
|
||||
)
|
||||
|
||||
response_data: Any = None
|
||||
if utils.match_response(http_res, "200", "application/json"):
|
||||
return unmarshal_json_response(operations.QueryAnalyticsResponse, http_res)
|
||||
if utils.match_response(http_res, "400", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.BadRequestResponseErrorData, http_res
|
||||
)
|
||||
raise errors.BadRequestResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "401", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.UnauthorizedResponseErrorData, http_res
|
||||
)
|
||||
raise errors.UnauthorizedResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "403", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.ForbiddenResponseErrorData, http_res
|
||||
)
|
||||
raise errors.ForbiddenResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "408", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.RequestTimeoutResponseErrorData, http_res
|
||||
)
|
||||
raise errors.RequestTimeoutResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "500", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.InternalServerResponseErrorData, http_res
|
||||
)
|
||||
raise errors.InternalServerResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "4XX", "*"):
|
||||
http_res_text = utils.stream_to_text(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
if utils.match_response(http_res, "5XX", "*"):
|
||||
http_res_text = utils.stream_to_text(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
|
||||
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
|
||||
|
||||
async def query_analytics_async(
|
||||
self,
|
||||
*,
|
||||
metrics: List[str],
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
dimensions: Optional[List[str]] = None,
|
||||
filters: Optional[
|
||||
Union[List[operations.Filter], List[operations.FilterTypedDict]]
|
||||
] = None,
|
||||
granularity: Optional[str] = None,
|
||||
group_limit: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
order_by: Optional[
|
||||
Union[operations.OrderBy, operations.OrderByTypedDict]
|
||||
] = None,
|
||||
time_range: Optional[
|
||||
Union[operations.TimeRange, operations.TimeRangeTypedDict]
|
||||
] = None,
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
http_headers: Optional[Mapping[str, str]] = None,
|
||||
) -> operations.QueryAnalyticsResponse:
|
||||
r"""Query analytics data
|
||||
|
||||
Execute an analytics query with specified metrics, dimensions, filters, and time range. [Management key](/docs/guides/overview/auth/management-api-keys) required.
|
||||
|
||||
:param metrics:
|
||||
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
|
||||
This is used to track API usage per application.
|
||||
|
||||
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param dimensions:
|
||||
:param filters:
|
||||
:param granularity: Time granularity
|
||||
:param group_limit: Maximum rows per distinct combination of dimensions. When omitted on time-series queries (granularity + dimensions), auto-computed to avoid truncating time windows. Explicit values override the default and may truncate time buckets if set lower than the number of buckets in the range. Ignored when no dimensions are specified.
|
||||
:param limit: Maximum total rows returned. Defaults to 1000. On time-series queries with dimensions and no explicit group_limit, the server may raise this to accommodate the expected number of unique time-bucket/dimension combinations.
|
||||
:param order_by:
|
||||
:param time_range:
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
:param http_headers: Additional headers to set or replace on requests.
|
||||
"""
|
||||
base_url = None
|
||||
url_variables = None
|
||||
if timeout_ms is None:
|
||||
timeout_ms = self.sdk_configuration.timeout_ms
|
||||
|
||||
if server_url is not None:
|
||||
base_url = server_url
|
||||
else:
|
||||
base_url = self._get_url(base_url, url_variables)
|
||||
|
||||
request = operations.QueryAnalyticsRequest(
|
||||
http_referer=http_referer,
|
||||
x_open_router_title=x_open_router_title,
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
request_body=operations.QueryAnalyticsRequestBody(
|
||||
dimensions=dimensions,
|
||||
filters=utils.get_pydantic_model(
|
||||
filters, Optional[List[operations.Filter]]
|
||||
),
|
||||
granularity=granularity,
|
||||
group_limit=group_limit,
|
||||
limit=limit,
|
||||
metrics=metrics,
|
||||
order_by=utils.get_pydantic_model(
|
||||
order_by, Optional[operations.OrderBy]
|
||||
),
|
||||
time_range=utils.get_pydantic_model(
|
||||
time_range, Optional[operations.TimeRange]
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
req = self._build_request_async(
|
||||
method="POST",
|
||||
path="/analytics/query",
|
||||
base_url=base_url,
|
||||
url_variables=url_variables,
|
||||
request=request,
|
||||
request_body_required=True,
|
||||
request_has_path_params=False,
|
||||
request_has_query_params=True,
|
||||
user_agent_header="user-agent",
|
||||
accept_header_value="application/json",
|
||||
http_headers=http_headers,
|
||||
_globals=operations.QueryAnalyticsGlobals(
|
||||
http_referer=self.sdk_configuration.globals.http_referer,
|
||||
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
|
||||
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
|
||||
),
|
||||
security=self.sdk_configuration.security,
|
||||
get_serialized_body=lambda: utils.serialize_request_body(
|
||||
request.request_body,
|
||||
False,
|
||||
False,
|
||||
"json",
|
||||
operations.QueryAnalyticsRequestBody,
|
||||
),
|
||||
allow_empty_value=None,
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
|
||||
if retries == UNSET:
|
||||
if self.sdk_configuration.retry_config is not UNSET:
|
||||
retries = self.sdk_configuration.retry_config
|
||||
else:
|
||||
retries = utils.RetryConfig(
|
||||
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
|
||||
)
|
||||
|
||||
retry_config = None
|
||||
if isinstance(retries, utils.RetryConfig):
|
||||
retry_config = (retries, ["5XX"])
|
||||
|
||||
http_res = await self.do_request_async(
|
||||
hook_ctx=HookContext(
|
||||
config=self.sdk_configuration,
|
||||
base_url=base_url or "",
|
||||
operation_id="queryAnalytics",
|
||||
oauth2_scopes=None,
|
||||
security_source=get_security_from_env(
|
||||
self.sdk_configuration.security, components.Security
|
||||
),
|
||||
),
|
||||
request=req,
|
||||
error_status_codes=["400", "401", "403", "408", "4XX", "500", "5XX"],
|
||||
retry_config=retry_config,
|
||||
)
|
||||
|
||||
response_data: Any = None
|
||||
if utils.match_response(http_res, "200", "application/json"):
|
||||
return unmarshal_json_response(operations.QueryAnalyticsResponse, http_res)
|
||||
if utils.match_response(http_res, "400", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.BadRequestResponseErrorData, http_res
|
||||
)
|
||||
raise errors.BadRequestResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "401", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.UnauthorizedResponseErrorData, http_res
|
||||
)
|
||||
raise errors.UnauthorizedResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "403", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.ForbiddenResponseErrorData, http_res
|
||||
)
|
||||
raise errors.ForbiddenResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "408", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.RequestTimeoutResponseErrorData, http_res
|
||||
)
|
||||
raise errors.RequestTimeoutResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "500", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.InternalServerResponseErrorData, http_res
|
||||
)
|
||||
raise errors.InternalServerResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "4XX", "*"):
|
||||
http_res_text = await utils.stream_to_text_async(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
if utils.match_response(http_res, "5XX", "*"):
|
||||
http_res_text = await utils.stream_to_text_async(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
|
||||
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
|
||||
File diff suppressed because it is too large
Load Diff
+260
-82
@@ -26,6 +26,7 @@ class Chat(BaseSDK):
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
x_open_router_metadata: Optional[components.MetadataLevel] = None,
|
||||
cache_control: Optional[
|
||||
Union[
|
||||
components.AnthropicCacheControlDirective,
|
||||
@@ -35,18 +36,19 @@ class Chat(BaseSDK):
|
||||
debug: Optional[
|
||||
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
|
||||
] = None,
|
||||
frequency_penalty: Optional[float] = None,
|
||||
frequency_penalty: OptionalNullable[float] = UNSET,
|
||||
image_config: Optional[
|
||||
Union[
|
||||
Dict[str, components.ChatRequestImageConfig],
|
||||
Dict[str, components.ChatRequestImageConfigTypedDict],
|
||||
Dict[str, components.ImageConfig],
|
||||
Dict[str, components.ImageConfigTypedDict],
|
||||
]
|
||||
] = None,
|
||||
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
|
||||
logprobs: OptionalNullable[bool] = UNSET,
|
||||
max_completion_tokens: Optional[int] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
max_completion_tokens: OptionalNullable[int] = UNSET,
|
||||
max_tokens: OptionalNullable[int] = UNSET,
|
||||
metadata: Optional[Dict[str, str]] = None,
|
||||
min_p: OptionalNullable[float] = UNSET,
|
||||
modalities: Optional[List[components.Modality]] = None,
|
||||
model: Optional[str] = None,
|
||||
models: Optional[List[str]] = None,
|
||||
@@ -57,29 +59,42 @@ class Chat(BaseSDK):
|
||||
List[components.ChatRequestPluginTypedDict],
|
||||
]
|
||||
] = None,
|
||||
presence_penalty: Optional[float] = None,
|
||||
presence_penalty: OptionalNullable[float] = UNSET,
|
||||
provider: OptionalNullable[
|
||||
Union[
|
||||
components.ProviderPreferences, components.ProviderPreferencesTypedDict
|
||||
]
|
||||
] = UNSET,
|
||||
reasoning: Optional[
|
||||
Union[components.Reasoning, components.ReasoningTypedDict]
|
||||
Union[
|
||||
components.ChatRequestReasoning,
|
||||
components.ChatRequestReasoningTypedDict,
|
||||
]
|
||||
] = None,
|
||||
reasoning_effort: OptionalNullable[
|
||||
components.ChatRequestReasoningEffort
|
||||
] = UNSET,
|
||||
repetition_penalty: OptionalNullable[float] = UNSET,
|
||||
response_format: Optional[
|
||||
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
|
||||
] = None,
|
||||
seed: Optional[int] = None,
|
||||
seed: OptionalNullable[int] = UNSET,
|
||||
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
|
||||
session_id: Optional[str] = None,
|
||||
stop: OptionalNullable[
|
||||
Union[components.Stop, components.StopTypedDict]
|
||||
] = UNSET,
|
||||
stop_server_tools_when: Optional[
|
||||
Union[
|
||||
List[components.StopServerToolsWhenCondition],
|
||||
List[components.StopServerToolsWhenConditionTypedDict],
|
||||
]
|
||||
] = None,
|
||||
stream: Union[Literal[False], None] = None,
|
||||
stream_options: OptionalNullable[
|
||||
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
|
||||
] = UNSET,
|
||||
temperature: Optional[float] = None,
|
||||
temperature: OptionalNullable[float] = UNSET,
|
||||
tool_choice: Optional[
|
||||
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
|
||||
] = None,
|
||||
@@ -89,8 +104,10 @@ class Chat(BaseSDK):
|
||||
List[components.ChatFunctionToolTypedDict],
|
||||
]
|
||||
] = None,
|
||||
top_logprobs: Optional[int] = None,
|
||||
top_p: Optional[float] = None,
|
||||
top_a: OptionalNullable[float] = UNSET,
|
||||
top_k: OptionalNullable[int] = UNSET,
|
||||
top_logprobs: OptionalNullable[int] = UNSET,
|
||||
top_p: OptionalNullable[float] = UNSET,
|
||||
trace: Optional[
|
||||
Union[components.TraceConfig, components.TraceConfigTypedDict]
|
||||
] = None,
|
||||
@@ -112,7 +129,8 @@ class Chat(BaseSDK):
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param cache_control:
|
||||
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
|
||||
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
|
||||
:param debug: Debug options for inspecting request transformations (streaming only)
|
||||
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
|
||||
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
|
||||
@@ -121,6 +139,7 @@ class Chat(BaseSDK):
|
||||
:param max_completion_tokens: Maximum tokens in completion
|
||||
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
|
||||
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
|
||||
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
|
||||
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
|
||||
:param model: Model to use for completion
|
||||
:param models: Models to use for completion
|
||||
@@ -129,16 +148,21 @@ class Chat(BaseSDK):
|
||||
:param presence_penalty: Presence penalty (-2.0 to 2.0)
|
||||
:param provider: When multiple model providers are available, optionally indicate your routing preference.
|
||||
:param reasoning: Configuration options for reasoning models
|
||||
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
|
||||
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
|
||||
:param response_format: Response format configuration
|
||||
:param seed: Random seed for deterministic outputs
|
||||
:param service_tier: The service tier to use for processing this request.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param stop: Stop sequences (up to 4)
|
||||
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
|
||||
:param stream: Enable streaming response
|
||||
:param stream_options: Streaming configuration options
|
||||
:param temperature: Sampling temperature (0-2)
|
||||
:param tool_choice: Tool choice configuration
|
||||
:param tools: Available tools for function calling
|
||||
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
|
||||
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
|
||||
:param top_logprobs: Number of top log probabilities to return (0-20)
|
||||
:param top_p: Nucleus sampling parameter (0-1)
|
||||
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
|
||||
@@ -160,6 +184,7 @@ class Chat(BaseSDK):
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
x_open_router_metadata: Optional[components.MetadataLevel] = None,
|
||||
cache_control: Optional[
|
||||
Union[
|
||||
components.AnthropicCacheControlDirective,
|
||||
@@ -169,18 +194,19 @@ class Chat(BaseSDK):
|
||||
debug: Optional[
|
||||
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
|
||||
] = None,
|
||||
frequency_penalty: Optional[float] = None,
|
||||
frequency_penalty: OptionalNullable[float] = UNSET,
|
||||
image_config: Optional[
|
||||
Union[
|
||||
Dict[str, components.ChatRequestImageConfig],
|
||||
Dict[str, components.ChatRequestImageConfigTypedDict],
|
||||
Dict[str, components.ImageConfig],
|
||||
Dict[str, components.ImageConfigTypedDict],
|
||||
]
|
||||
] = None,
|
||||
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
|
||||
logprobs: OptionalNullable[bool] = UNSET,
|
||||
max_completion_tokens: Optional[int] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
max_completion_tokens: OptionalNullable[int] = UNSET,
|
||||
max_tokens: OptionalNullable[int] = UNSET,
|
||||
metadata: Optional[Dict[str, str]] = None,
|
||||
min_p: OptionalNullable[float] = UNSET,
|
||||
modalities: Optional[List[components.Modality]] = None,
|
||||
model: Optional[str] = None,
|
||||
models: Optional[List[str]] = None,
|
||||
@@ -191,29 +217,42 @@ class Chat(BaseSDK):
|
||||
List[components.ChatRequestPluginTypedDict],
|
||||
]
|
||||
] = None,
|
||||
presence_penalty: Optional[float] = None,
|
||||
presence_penalty: OptionalNullable[float] = UNSET,
|
||||
provider: OptionalNullable[
|
||||
Union[
|
||||
components.ProviderPreferences, components.ProviderPreferencesTypedDict
|
||||
]
|
||||
] = UNSET,
|
||||
reasoning: Optional[
|
||||
Union[components.Reasoning, components.ReasoningTypedDict]
|
||||
Union[
|
||||
components.ChatRequestReasoning,
|
||||
components.ChatRequestReasoningTypedDict,
|
||||
]
|
||||
] = None,
|
||||
reasoning_effort: OptionalNullable[
|
||||
components.ChatRequestReasoningEffort
|
||||
] = UNSET,
|
||||
repetition_penalty: OptionalNullable[float] = UNSET,
|
||||
response_format: Optional[
|
||||
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
|
||||
] = None,
|
||||
seed: Optional[int] = None,
|
||||
seed: OptionalNullable[int] = UNSET,
|
||||
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
|
||||
session_id: Optional[str] = None,
|
||||
stop: OptionalNullable[
|
||||
Union[components.Stop, components.StopTypedDict]
|
||||
] = UNSET,
|
||||
stop_server_tools_when: Optional[
|
||||
Union[
|
||||
List[components.StopServerToolsWhenCondition],
|
||||
List[components.StopServerToolsWhenConditionTypedDict],
|
||||
]
|
||||
] = None,
|
||||
stream: Literal[True],
|
||||
stream_options: OptionalNullable[
|
||||
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
|
||||
] = UNSET,
|
||||
temperature: Optional[float] = None,
|
||||
temperature: OptionalNullable[float] = UNSET,
|
||||
tool_choice: Optional[
|
||||
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
|
||||
] = None,
|
||||
@@ -223,8 +262,10 @@ class Chat(BaseSDK):
|
||||
List[components.ChatFunctionToolTypedDict],
|
||||
]
|
||||
] = None,
|
||||
top_logprobs: Optional[int] = None,
|
||||
top_p: Optional[float] = None,
|
||||
top_a: OptionalNullable[float] = UNSET,
|
||||
top_k: OptionalNullable[int] = UNSET,
|
||||
top_logprobs: OptionalNullable[int] = UNSET,
|
||||
top_p: OptionalNullable[float] = UNSET,
|
||||
trace: Optional[
|
||||
Union[components.TraceConfig, components.TraceConfigTypedDict]
|
||||
] = None,
|
||||
@@ -246,7 +287,8 @@ class Chat(BaseSDK):
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param cache_control:
|
||||
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
|
||||
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
|
||||
:param debug: Debug options for inspecting request transformations (streaming only)
|
||||
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
|
||||
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
|
||||
@@ -255,6 +297,7 @@ class Chat(BaseSDK):
|
||||
:param max_completion_tokens: Maximum tokens in completion
|
||||
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
|
||||
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
|
||||
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
|
||||
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
|
||||
:param model: Model to use for completion
|
||||
:param models: Models to use for completion
|
||||
@@ -263,16 +306,21 @@ class Chat(BaseSDK):
|
||||
:param presence_penalty: Presence penalty (-2.0 to 2.0)
|
||||
:param provider: When multiple model providers are available, optionally indicate your routing preference.
|
||||
:param reasoning: Configuration options for reasoning models
|
||||
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
|
||||
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
|
||||
:param response_format: Response format configuration
|
||||
:param seed: Random seed for deterministic outputs
|
||||
:param service_tier: The service tier to use for processing this request.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param stop: Stop sequences (up to 4)
|
||||
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
|
||||
:param stream: Enable streaming response
|
||||
:param stream_options: Streaming configuration options
|
||||
:param temperature: Sampling temperature (0-2)
|
||||
:param tool_choice: Tool choice configuration
|
||||
:param tools: Available tools for function calling
|
||||
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
|
||||
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
|
||||
:param top_logprobs: Number of top log probabilities to return (0-20)
|
||||
:param top_p: Nucleus sampling parameter (0-1)
|
||||
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
|
||||
@@ -293,6 +341,7 @@ class Chat(BaseSDK):
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
x_open_router_metadata: Optional[components.MetadataLevel] = None,
|
||||
cache_control: Optional[
|
||||
Union[
|
||||
components.AnthropicCacheControlDirective,
|
||||
@@ -302,18 +351,19 @@ class Chat(BaseSDK):
|
||||
debug: Optional[
|
||||
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
|
||||
] = None,
|
||||
frequency_penalty: Optional[float] = None,
|
||||
frequency_penalty: OptionalNullable[float] = UNSET,
|
||||
image_config: Optional[
|
||||
Union[
|
||||
Dict[str, components.ChatRequestImageConfig],
|
||||
Dict[str, components.ChatRequestImageConfigTypedDict],
|
||||
Dict[str, components.ImageConfig],
|
||||
Dict[str, components.ImageConfigTypedDict],
|
||||
]
|
||||
] = None,
|
||||
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
|
||||
logprobs: OptionalNullable[bool] = UNSET,
|
||||
max_completion_tokens: Optional[int] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
max_completion_tokens: OptionalNullable[int] = UNSET,
|
||||
max_tokens: OptionalNullable[int] = UNSET,
|
||||
metadata: Optional[Dict[str, str]] = None,
|
||||
min_p: OptionalNullable[float] = UNSET,
|
||||
modalities: Optional[List[components.Modality]] = None,
|
||||
model: Optional[str] = None,
|
||||
models: Optional[List[str]] = None,
|
||||
@@ -324,29 +374,42 @@ class Chat(BaseSDK):
|
||||
List[components.ChatRequestPluginTypedDict],
|
||||
]
|
||||
] = None,
|
||||
presence_penalty: Optional[float] = None,
|
||||
presence_penalty: OptionalNullable[float] = UNSET,
|
||||
provider: OptionalNullable[
|
||||
Union[
|
||||
components.ProviderPreferences, components.ProviderPreferencesTypedDict
|
||||
]
|
||||
] = UNSET,
|
||||
reasoning: Optional[
|
||||
Union[components.Reasoning, components.ReasoningTypedDict]
|
||||
Union[
|
||||
components.ChatRequestReasoning,
|
||||
components.ChatRequestReasoningTypedDict,
|
||||
]
|
||||
] = None,
|
||||
reasoning_effort: OptionalNullable[
|
||||
components.ChatRequestReasoningEffort
|
||||
] = UNSET,
|
||||
repetition_penalty: OptionalNullable[float] = UNSET,
|
||||
response_format: Optional[
|
||||
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
|
||||
] = None,
|
||||
seed: Optional[int] = None,
|
||||
seed: OptionalNullable[int] = UNSET,
|
||||
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
|
||||
session_id: Optional[str] = None,
|
||||
stop: OptionalNullable[
|
||||
Union[components.Stop, components.StopTypedDict]
|
||||
] = UNSET,
|
||||
stop_server_tools_when: Optional[
|
||||
Union[
|
||||
List[components.StopServerToolsWhenCondition],
|
||||
List[components.StopServerToolsWhenConditionTypedDict],
|
||||
]
|
||||
] = None,
|
||||
stream: Optional[bool] = False,
|
||||
stream_options: OptionalNullable[
|
||||
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
|
||||
] = UNSET,
|
||||
temperature: Optional[float] = None,
|
||||
temperature: OptionalNullable[float] = UNSET,
|
||||
tool_choice: Optional[
|
||||
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
|
||||
] = None,
|
||||
@@ -356,8 +419,10 @@ class Chat(BaseSDK):
|
||||
List[components.ChatFunctionToolTypedDict],
|
||||
]
|
||||
] = None,
|
||||
top_logprobs: Optional[int] = None,
|
||||
top_p: Optional[float] = None,
|
||||
top_a: OptionalNullable[float] = UNSET,
|
||||
top_k: OptionalNullable[int] = UNSET,
|
||||
top_logprobs: OptionalNullable[int] = UNSET,
|
||||
top_p: OptionalNullable[float] = UNSET,
|
||||
trace: Optional[
|
||||
Union[components.TraceConfig, components.TraceConfigTypedDict]
|
||||
] = None,
|
||||
@@ -379,7 +444,8 @@ class Chat(BaseSDK):
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param cache_control:
|
||||
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
|
||||
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
|
||||
:param debug: Debug options for inspecting request transformations (streaming only)
|
||||
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
|
||||
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
|
||||
@@ -388,6 +454,7 @@ class Chat(BaseSDK):
|
||||
:param max_completion_tokens: Maximum tokens in completion
|
||||
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
|
||||
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
|
||||
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
|
||||
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
|
||||
:param model: Model to use for completion
|
||||
:param models: Models to use for completion
|
||||
@@ -396,16 +463,21 @@ class Chat(BaseSDK):
|
||||
:param presence_penalty: Presence penalty (-2.0 to 2.0)
|
||||
:param provider: When multiple model providers are available, optionally indicate your routing preference.
|
||||
:param reasoning: Configuration options for reasoning models
|
||||
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
|
||||
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
|
||||
:param response_format: Response format configuration
|
||||
:param seed: Random seed for deterministic outputs
|
||||
:param service_tier: The service tier to use for processing this request.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param stop: Stop sequences (up to 4)
|
||||
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
|
||||
:param stream: Enable streaming response
|
||||
:param stream_options: Streaming configuration options
|
||||
:param temperature: Sampling temperature (0-2)
|
||||
:param tool_choice: Tool choice configuration
|
||||
:param tools: Available tools for function calling
|
||||
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
|
||||
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
|
||||
:param top_logprobs: Number of top log probabilities to return (0-20)
|
||||
:param top_p: Nucleus sampling parameter (0-1)
|
||||
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
|
||||
@@ -430,6 +502,7 @@ class Chat(BaseSDK):
|
||||
http_referer=http_referer,
|
||||
x_open_router_title=x_open_router_title,
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
x_open_router_metadata=x_open_router_metadata,
|
||||
chat_request=components.ChatRequest(
|
||||
cache_control=utils.get_pydantic_model(
|
||||
cache_control, Optional[components.AnthropicCacheControlDirective]
|
||||
@@ -447,6 +520,7 @@ class Chat(BaseSDK):
|
||||
messages, List[components.ChatMessages]
|
||||
),
|
||||
metadata=metadata,
|
||||
min_p=min_p,
|
||||
modalities=modalities,
|
||||
model=model,
|
||||
models=models,
|
||||
@@ -459,8 +533,10 @@ class Chat(BaseSDK):
|
||||
provider, OptionalNullable[components.ProviderPreferences]
|
||||
),
|
||||
reasoning=utils.get_pydantic_model(
|
||||
reasoning, Optional[components.Reasoning]
|
||||
reasoning, Optional[components.ChatRequestReasoning]
|
||||
),
|
||||
reasoning_effort=reasoning_effort,
|
||||
repetition_penalty=repetition_penalty,
|
||||
response_format=utils.get_pydantic_model(
|
||||
response_format, Optional[components.ResponseFormat]
|
||||
),
|
||||
@@ -468,6 +544,10 @@ class Chat(BaseSDK):
|
||||
service_tier=service_tier,
|
||||
session_id=session_id,
|
||||
stop=stop,
|
||||
stop_server_tools_when=utils.get_pydantic_model(
|
||||
stop_server_tools_when,
|
||||
Optional[List[components.StopServerToolsWhenCondition]],
|
||||
),
|
||||
stream=stream,
|
||||
stream_options=utils.get_pydantic_model(
|
||||
stream_options, OptionalNullable[components.ChatStreamOptions]
|
||||
@@ -479,6 +559,8 @@ class Chat(BaseSDK):
|
||||
tools=utils.get_pydantic_model(
|
||||
tools, Optional[List[components.ChatFunctionTool]]
|
||||
),
|
||||
top_a=top_a,
|
||||
top_k=top_k,
|
||||
top_logprobs=top_logprobs,
|
||||
top_p=top_p,
|
||||
trace=utils.get_pydantic_model(trace, Optional[components.TraceConfig]),
|
||||
@@ -538,6 +620,7 @@ class Chat(BaseSDK):
|
||||
"400",
|
||||
"401",
|
||||
"402",
|
||||
"403",
|
||||
"404",
|
||||
"408",
|
||||
"413",
|
||||
@@ -565,7 +648,7 @@ class Chat(BaseSDK):
|
||||
return eventstreaming.EventStream(
|
||||
http_res,
|
||||
lambda raw: utils.unmarshal_json(
|
||||
raw, operations.SendChatCompletionRequestResponseBody
|
||||
raw, components.ChatStreamingResponse
|
||||
).data,
|
||||
sentinel="[DONE]",
|
||||
client_ref=self,
|
||||
@@ -592,6 +675,12 @@ class Chat(BaseSDK):
|
||||
raise errors.PaymentRequiredResponseError(
|
||||
response_data, http_res, http_res_text
|
||||
)
|
||||
if utils.match_response(http_res, "403", "application/json"):
|
||||
http_res_text = utils.stream_to_text(http_res)
|
||||
response_data = unmarshal_json_response(
|
||||
errors.ForbiddenResponseErrorData, http_res, http_res_text
|
||||
)
|
||||
raise errors.ForbiddenResponseError(response_data, http_res, http_res_text)
|
||||
if utils.match_response(http_res, "404", "application/json"):
|
||||
http_res_text = utils.stream_to_text(http_res)
|
||||
response_data = unmarshal_json_response(
|
||||
@@ -694,6 +783,7 @@ class Chat(BaseSDK):
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
x_open_router_metadata: Optional[components.MetadataLevel] = None,
|
||||
cache_control: Optional[
|
||||
Union[
|
||||
components.AnthropicCacheControlDirective,
|
||||
@@ -703,18 +793,19 @@ class Chat(BaseSDK):
|
||||
debug: Optional[
|
||||
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
|
||||
] = None,
|
||||
frequency_penalty: Optional[float] = None,
|
||||
frequency_penalty: OptionalNullable[float] = UNSET,
|
||||
image_config: Optional[
|
||||
Union[
|
||||
Dict[str, components.ChatRequestImageConfig],
|
||||
Dict[str, components.ChatRequestImageConfigTypedDict],
|
||||
Dict[str, components.ImageConfig],
|
||||
Dict[str, components.ImageConfigTypedDict],
|
||||
]
|
||||
] = None,
|
||||
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
|
||||
logprobs: OptionalNullable[bool] = UNSET,
|
||||
max_completion_tokens: Optional[int] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
max_completion_tokens: OptionalNullable[int] = UNSET,
|
||||
max_tokens: OptionalNullable[int] = UNSET,
|
||||
metadata: Optional[Dict[str, str]] = None,
|
||||
min_p: OptionalNullable[float] = UNSET,
|
||||
modalities: Optional[List[components.Modality]] = None,
|
||||
model: Optional[str] = None,
|
||||
models: Optional[List[str]] = None,
|
||||
@@ -725,29 +816,42 @@ class Chat(BaseSDK):
|
||||
List[components.ChatRequestPluginTypedDict],
|
||||
]
|
||||
] = None,
|
||||
presence_penalty: Optional[float] = None,
|
||||
presence_penalty: OptionalNullable[float] = UNSET,
|
||||
provider: OptionalNullable[
|
||||
Union[
|
||||
components.ProviderPreferences, components.ProviderPreferencesTypedDict
|
||||
]
|
||||
] = UNSET,
|
||||
reasoning: Optional[
|
||||
Union[components.Reasoning, components.ReasoningTypedDict]
|
||||
Union[
|
||||
components.ChatRequestReasoning,
|
||||
components.ChatRequestReasoningTypedDict,
|
||||
]
|
||||
] = None,
|
||||
reasoning_effort: OptionalNullable[
|
||||
components.ChatRequestReasoningEffort
|
||||
] = UNSET,
|
||||
repetition_penalty: OptionalNullable[float] = UNSET,
|
||||
response_format: Optional[
|
||||
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
|
||||
] = None,
|
||||
seed: Optional[int] = None,
|
||||
seed: OptionalNullable[int] = UNSET,
|
||||
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
|
||||
session_id: Optional[str] = None,
|
||||
stop: OptionalNullable[
|
||||
Union[components.Stop, components.StopTypedDict]
|
||||
] = UNSET,
|
||||
stop_server_tools_when: Optional[
|
||||
Union[
|
||||
List[components.StopServerToolsWhenCondition],
|
||||
List[components.StopServerToolsWhenConditionTypedDict],
|
||||
]
|
||||
] = None,
|
||||
stream: Union[Literal[False], None] = None,
|
||||
stream_options: OptionalNullable[
|
||||
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
|
||||
] = UNSET,
|
||||
temperature: Optional[float] = None,
|
||||
temperature: OptionalNullable[float] = UNSET,
|
||||
tool_choice: Optional[
|
||||
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
|
||||
] = None,
|
||||
@@ -757,8 +861,10 @@ class Chat(BaseSDK):
|
||||
List[components.ChatFunctionToolTypedDict],
|
||||
]
|
||||
] = None,
|
||||
top_logprobs: Optional[int] = None,
|
||||
top_p: Optional[float] = None,
|
||||
top_a: OptionalNullable[float] = UNSET,
|
||||
top_k: OptionalNullable[int] = UNSET,
|
||||
top_logprobs: OptionalNullable[int] = UNSET,
|
||||
top_p: OptionalNullable[float] = UNSET,
|
||||
trace: Optional[
|
||||
Union[components.TraceConfig, components.TraceConfigTypedDict]
|
||||
] = None,
|
||||
@@ -780,7 +886,8 @@ class Chat(BaseSDK):
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param cache_control:
|
||||
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
|
||||
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
|
||||
:param debug: Debug options for inspecting request transformations (streaming only)
|
||||
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
|
||||
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
|
||||
@@ -789,6 +896,7 @@ class Chat(BaseSDK):
|
||||
:param max_completion_tokens: Maximum tokens in completion
|
||||
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
|
||||
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
|
||||
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
|
||||
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
|
||||
:param model: Model to use for completion
|
||||
:param models: Models to use for completion
|
||||
@@ -797,16 +905,21 @@ class Chat(BaseSDK):
|
||||
:param presence_penalty: Presence penalty (-2.0 to 2.0)
|
||||
:param provider: When multiple model providers are available, optionally indicate your routing preference.
|
||||
:param reasoning: Configuration options for reasoning models
|
||||
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
|
||||
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
|
||||
:param response_format: Response format configuration
|
||||
:param seed: Random seed for deterministic outputs
|
||||
:param service_tier: The service tier to use for processing this request.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param stop: Stop sequences (up to 4)
|
||||
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
|
||||
:param stream: Enable streaming response
|
||||
:param stream_options: Streaming configuration options
|
||||
:param temperature: Sampling temperature (0-2)
|
||||
:param tool_choice: Tool choice configuration
|
||||
:param tools: Available tools for function calling
|
||||
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
|
||||
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
|
||||
:param top_logprobs: Number of top log probabilities to return (0-20)
|
||||
:param top_p: Nucleus sampling parameter (0-1)
|
||||
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
|
||||
@@ -828,6 +941,7 @@ class Chat(BaseSDK):
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
x_open_router_metadata: Optional[components.MetadataLevel] = None,
|
||||
cache_control: Optional[
|
||||
Union[
|
||||
components.AnthropicCacheControlDirective,
|
||||
@@ -837,18 +951,19 @@ class Chat(BaseSDK):
|
||||
debug: Optional[
|
||||
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
|
||||
] = None,
|
||||
frequency_penalty: Optional[float] = None,
|
||||
frequency_penalty: OptionalNullable[float] = UNSET,
|
||||
image_config: Optional[
|
||||
Union[
|
||||
Dict[str, components.ChatRequestImageConfig],
|
||||
Dict[str, components.ChatRequestImageConfigTypedDict],
|
||||
Dict[str, components.ImageConfig],
|
||||
Dict[str, components.ImageConfigTypedDict],
|
||||
]
|
||||
] = None,
|
||||
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
|
||||
logprobs: OptionalNullable[bool] = UNSET,
|
||||
max_completion_tokens: Optional[int] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
max_completion_tokens: OptionalNullable[int] = UNSET,
|
||||
max_tokens: OptionalNullable[int] = UNSET,
|
||||
metadata: Optional[Dict[str, str]] = None,
|
||||
min_p: OptionalNullable[float] = UNSET,
|
||||
modalities: Optional[List[components.Modality]] = None,
|
||||
model: Optional[str] = None,
|
||||
models: Optional[List[str]] = None,
|
||||
@@ -859,29 +974,42 @@ class Chat(BaseSDK):
|
||||
List[components.ChatRequestPluginTypedDict],
|
||||
]
|
||||
] = None,
|
||||
presence_penalty: Optional[float] = None,
|
||||
presence_penalty: OptionalNullable[float] = UNSET,
|
||||
provider: OptionalNullable[
|
||||
Union[
|
||||
components.ProviderPreferences, components.ProviderPreferencesTypedDict
|
||||
]
|
||||
] = UNSET,
|
||||
reasoning: Optional[
|
||||
Union[components.Reasoning, components.ReasoningTypedDict]
|
||||
Union[
|
||||
components.ChatRequestReasoning,
|
||||
components.ChatRequestReasoningTypedDict,
|
||||
]
|
||||
] = None,
|
||||
reasoning_effort: OptionalNullable[
|
||||
components.ChatRequestReasoningEffort
|
||||
] = UNSET,
|
||||
repetition_penalty: OptionalNullable[float] = UNSET,
|
||||
response_format: Optional[
|
||||
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
|
||||
] = None,
|
||||
seed: Optional[int] = None,
|
||||
seed: OptionalNullable[int] = UNSET,
|
||||
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
|
||||
session_id: Optional[str] = None,
|
||||
stop: OptionalNullable[
|
||||
Union[components.Stop, components.StopTypedDict]
|
||||
] = UNSET,
|
||||
stop_server_tools_when: Optional[
|
||||
Union[
|
||||
List[components.StopServerToolsWhenCondition],
|
||||
List[components.StopServerToolsWhenConditionTypedDict],
|
||||
]
|
||||
] = None,
|
||||
stream: Literal[True],
|
||||
stream_options: OptionalNullable[
|
||||
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
|
||||
] = UNSET,
|
||||
temperature: Optional[float] = None,
|
||||
temperature: OptionalNullable[float] = UNSET,
|
||||
tool_choice: Optional[
|
||||
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
|
||||
] = None,
|
||||
@@ -891,8 +1019,10 @@ class Chat(BaseSDK):
|
||||
List[components.ChatFunctionToolTypedDict],
|
||||
]
|
||||
] = None,
|
||||
top_logprobs: Optional[int] = None,
|
||||
top_p: Optional[float] = None,
|
||||
top_a: OptionalNullable[float] = UNSET,
|
||||
top_k: OptionalNullable[int] = UNSET,
|
||||
top_logprobs: OptionalNullable[int] = UNSET,
|
||||
top_p: OptionalNullable[float] = UNSET,
|
||||
trace: Optional[
|
||||
Union[components.TraceConfig, components.TraceConfigTypedDict]
|
||||
] = None,
|
||||
@@ -914,7 +1044,8 @@ class Chat(BaseSDK):
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param cache_control:
|
||||
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
|
||||
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
|
||||
:param debug: Debug options for inspecting request transformations (streaming only)
|
||||
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
|
||||
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
|
||||
@@ -923,6 +1054,7 @@ class Chat(BaseSDK):
|
||||
:param max_completion_tokens: Maximum tokens in completion
|
||||
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
|
||||
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
|
||||
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
|
||||
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
|
||||
:param model: Model to use for completion
|
||||
:param models: Models to use for completion
|
||||
@@ -931,16 +1063,21 @@ class Chat(BaseSDK):
|
||||
:param presence_penalty: Presence penalty (-2.0 to 2.0)
|
||||
:param provider: When multiple model providers are available, optionally indicate your routing preference.
|
||||
:param reasoning: Configuration options for reasoning models
|
||||
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
|
||||
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
|
||||
:param response_format: Response format configuration
|
||||
:param seed: Random seed for deterministic outputs
|
||||
:param service_tier: The service tier to use for processing this request.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param stop: Stop sequences (up to 4)
|
||||
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
|
||||
:param stream: Enable streaming response
|
||||
:param stream_options: Streaming configuration options
|
||||
:param temperature: Sampling temperature (0-2)
|
||||
:param tool_choice: Tool choice configuration
|
||||
:param tools: Available tools for function calling
|
||||
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
|
||||
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
|
||||
:param top_logprobs: Number of top log probabilities to return (0-20)
|
||||
:param top_p: Nucleus sampling parameter (0-1)
|
||||
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
|
||||
@@ -961,6 +1098,7 @@ class Chat(BaseSDK):
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
x_open_router_metadata: Optional[components.MetadataLevel] = None,
|
||||
cache_control: Optional[
|
||||
Union[
|
||||
components.AnthropicCacheControlDirective,
|
||||
@@ -970,18 +1108,19 @@ class Chat(BaseSDK):
|
||||
debug: Optional[
|
||||
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
|
||||
] = None,
|
||||
frequency_penalty: Optional[float] = None,
|
||||
frequency_penalty: OptionalNullable[float] = UNSET,
|
||||
image_config: Optional[
|
||||
Union[
|
||||
Dict[str, components.ChatRequestImageConfig],
|
||||
Dict[str, components.ChatRequestImageConfigTypedDict],
|
||||
Dict[str, components.ImageConfig],
|
||||
Dict[str, components.ImageConfigTypedDict],
|
||||
]
|
||||
] = None,
|
||||
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
|
||||
logprobs: OptionalNullable[bool] = UNSET,
|
||||
max_completion_tokens: Optional[int] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
max_completion_tokens: OptionalNullable[int] = UNSET,
|
||||
max_tokens: OptionalNullable[int] = UNSET,
|
||||
metadata: Optional[Dict[str, str]] = None,
|
||||
min_p: OptionalNullable[float] = UNSET,
|
||||
modalities: Optional[List[components.Modality]] = None,
|
||||
model: Optional[str] = None,
|
||||
models: Optional[List[str]] = None,
|
||||
@@ -992,29 +1131,42 @@ class Chat(BaseSDK):
|
||||
List[components.ChatRequestPluginTypedDict],
|
||||
]
|
||||
] = None,
|
||||
presence_penalty: Optional[float] = None,
|
||||
presence_penalty: OptionalNullable[float] = UNSET,
|
||||
provider: OptionalNullable[
|
||||
Union[
|
||||
components.ProviderPreferences, components.ProviderPreferencesTypedDict
|
||||
]
|
||||
] = UNSET,
|
||||
reasoning: Optional[
|
||||
Union[components.Reasoning, components.ReasoningTypedDict]
|
||||
Union[
|
||||
components.ChatRequestReasoning,
|
||||
components.ChatRequestReasoningTypedDict,
|
||||
]
|
||||
] = None,
|
||||
reasoning_effort: OptionalNullable[
|
||||
components.ChatRequestReasoningEffort
|
||||
] = UNSET,
|
||||
repetition_penalty: OptionalNullable[float] = UNSET,
|
||||
response_format: Optional[
|
||||
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
|
||||
] = None,
|
||||
seed: Optional[int] = None,
|
||||
seed: OptionalNullable[int] = UNSET,
|
||||
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
|
||||
session_id: Optional[str] = None,
|
||||
stop: OptionalNullable[
|
||||
Union[components.Stop, components.StopTypedDict]
|
||||
] = UNSET,
|
||||
stop_server_tools_when: Optional[
|
||||
Union[
|
||||
List[components.StopServerToolsWhenCondition],
|
||||
List[components.StopServerToolsWhenConditionTypedDict],
|
||||
]
|
||||
] = None,
|
||||
stream: Optional[bool] = False,
|
||||
stream_options: OptionalNullable[
|
||||
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
|
||||
] = UNSET,
|
||||
temperature: Optional[float] = None,
|
||||
temperature: OptionalNullable[float] = UNSET,
|
||||
tool_choice: Optional[
|
||||
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
|
||||
] = None,
|
||||
@@ -1024,8 +1176,10 @@ class Chat(BaseSDK):
|
||||
List[components.ChatFunctionToolTypedDict],
|
||||
]
|
||||
] = None,
|
||||
top_logprobs: Optional[int] = None,
|
||||
top_p: Optional[float] = None,
|
||||
top_a: OptionalNullable[float] = UNSET,
|
||||
top_k: OptionalNullable[int] = UNSET,
|
||||
top_logprobs: OptionalNullable[int] = UNSET,
|
||||
top_p: OptionalNullable[float] = UNSET,
|
||||
trace: Optional[
|
||||
Union[components.TraceConfig, components.TraceConfigTypedDict]
|
||||
] = None,
|
||||
@@ -1047,7 +1201,8 @@ class Chat(BaseSDK):
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param cache_control:
|
||||
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
|
||||
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
|
||||
:param debug: Debug options for inspecting request transformations (streaming only)
|
||||
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
|
||||
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
|
||||
@@ -1056,6 +1211,7 @@ class Chat(BaseSDK):
|
||||
:param max_completion_tokens: Maximum tokens in completion
|
||||
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
|
||||
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
|
||||
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
|
||||
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
|
||||
:param model: Model to use for completion
|
||||
:param models: Models to use for completion
|
||||
@@ -1064,16 +1220,21 @@ class Chat(BaseSDK):
|
||||
:param presence_penalty: Presence penalty (-2.0 to 2.0)
|
||||
:param provider: When multiple model providers are available, optionally indicate your routing preference.
|
||||
:param reasoning: Configuration options for reasoning models
|
||||
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
|
||||
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
|
||||
:param response_format: Response format configuration
|
||||
:param seed: Random seed for deterministic outputs
|
||||
:param service_tier: The service tier to use for processing this request.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
|
||||
:param stop: Stop sequences (up to 4)
|
||||
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
|
||||
:param stream: Enable streaming response
|
||||
:param stream_options: Streaming configuration options
|
||||
:param temperature: Sampling temperature (0-2)
|
||||
:param tool_choice: Tool choice configuration
|
||||
:param tools: Available tools for function calling
|
||||
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
|
||||
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
|
||||
:param top_logprobs: Number of top log probabilities to return (0-20)
|
||||
:param top_p: Nucleus sampling parameter (0-1)
|
||||
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
|
||||
@@ -1098,6 +1259,7 @@ class Chat(BaseSDK):
|
||||
http_referer=http_referer,
|
||||
x_open_router_title=x_open_router_title,
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
x_open_router_metadata=x_open_router_metadata,
|
||||
chat_request=components.ChatRequest(
|
||||
cache_control=utils.get_pydantic_model(
|
||||
cache_control, Optional[components.AnthropicCacheControlDirective]
|
||||
@@ -1115,6 +1277,7 @@ class Chat(BaseSDK):
|
||||
messages, List[components.ChatMessages]
|
||||
),
|
||||
metadata=metadata,
|
||||
min_p=min_p,
|
||||
modalities=modalities,
|
||||
model=model,
|
||||
models=models,
|
||||
@@ -1127,8 +1290,10 @@ class Chat(BaseSDK):
|
||||
provider, OptionalNullable[components.ProviderPreferences]
|
||||
),
|
||||
reasoning=utils.get_pydantic_model(
|
||||
reasoning, Optional[components.Reasoning]
|
||||
reasoning, Optional[components.ChatRequestReasoning]
|
||||
),
|
||||
reasoning_effort=reasoning_effort,
|
||||
repetition_penalty=repetition_penalty,
|
||||
response_format=utils.get_pydantic_model(
|
||||
response_format, Optional[components.ResponseFormat]
|
||||
),
|
||||
@@ -1136,6 +1301,10 @@ class Chat(BaseSDK):
|
||||
service_tier=service_tier,
|
||||
session_id=session_id,
|
||||
stop=stop,
|
||||
stop_server_tools_when=utils.get_pydantic_model(
|
||||
stop_server_tools_when,
|
||||
Optional[List[components.StopServerToolsWhenCondition]],
|
||||
),
|
||||
stream=stream,
|
||||
stream_options=utils.get_pydantic_model(
|
||||
stream_options, OptionalNullable[components.ChatStreamOptions]
|
||||
@@ -1147,6 +1316,8 @@ class Chat(BaseSDK):
|
||||
tools=utils.get_pydantic_model(
|
||||
tools, Optional[List[components.ChatFunctionTool]]
|
||||
),
|
||||
top_a=top_a,
|
||||
top_k=top_k,
|
||||
top_logprobs=top_logprobs,
|
||||
top_p=top_p,
|
||||
trace=utils.get_pydantic_model(trace, Optional[components.TraceConfig]),
|
||||
@@ -1206,6 +1377,7 @@ class Chat(BaseSDK):
|
||||
"400",
|
||||
"401",
|
||||
"402",
|
||||
"403",
|
||||
"404",
|
||||
"408",
|
||||
"413",
|
||||
@@ -1233,7 +1405,7 @@ class Chat(BaseSDK):
|
||||
return eventstreaming.EventStreamAsync(
|
||||
http_res,
|
||||
lambda raw: utils.unmarshal_json(
|
||||
raw, operations.SendChatCompletionRequestResponseBody
|
||||
raw, components.ChatStreamingResponse
|
||||
).data,
|
||||
sentinel="[DONE]",
|
||||
client_ref=self,
|
||||
@@ -1260,6 +1432,12 @@ class Chat(BaseSDK):
|
||||
raise errors.PaymentRequiredResponseError(
|
||||
response_data, http_res, http_res_text
|
||||
)
|
||||
if utils.match_response(http_res, "403", "application/json"):
|
||||
http_res_text = await utils.stream_to_text_async(http_res)
|
||||
response_data = unmarshal_json_response(
|
||||
errors.ForbiddenResponseErrorData, http_res, http_res_text
|
||||
)
|
||||
raise errors.ForbiddenResponseError(response_data, http_res, http_res_text)
|
||||
if utils.match_response(http_res, "404", "application/json"):
|
||||
http_res_text = await utils.stream_to_text_async(http_res)
|
||||
response_data = unmarshal_json_response(
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
|
||||
|
||||
from .basesdk import BaseSDK
|
||||
from openrouter import components, errors, operations, utils
|
||||
from openrouter._hooks import HookContext
|
||||
from openrouter.types import OptionalNullable, UNSET
|
||||
from openrouter.utils import get_security_from_env
|
||||
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
|
||||
from typing import Any, Mapping, Optional
|
||||
|
||||
|
||||
class Classifications(BaseSDK):
|
||||
r"""Task classification market-share endpoints"""
|
||||
|
||||
def get_task_classifications(
|
||||
self,
|
||||
*,
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
window: Optional[operations.Window] = "7d",
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
http_headers: Optional[Mapping[str, str]] = None,
|
||||
) -> components.TaskClassificationResponse:
|
||||
r"""Task classification market share
|
||||
|
||||
Returns the market-share breakdown of OpenRouter traffic by task classification
|
||||
(e.g. code generation, web search, summarization) over a trailing time window.
|
||||
|
||||
Each classification reports its share of classified sampled requests (`usage_share`)
|
||||
and classified sampled token volume (`token_share`) as fractions between 0 and 1.
|
||||
The unclassified `other` bucket is excluded. Absolute volumes are not exposed
|
||||
because the underlying data is sampled.
|
||||
|
||||
Each classification also includes a `models` array listing the top models by
|
||||
request volume within that classification, with their within-tag usage and token shares.
|
||||
|
||||
Classifications are grouped into macro-categories (Code, Data, Agent, General)
|
||||
with aggregate shares provided for each.
|
||||
|
||||
Authenticate with any valid OpenRouter API key (same key used for inference).
|
||||
Rate-limited to 30 requests/minute per key and 500 requests/day per account.
|
||||
|
||||
When republishing or quoting this data, cite as:
|
||||
\"Source: OpenRouter (openrouter.ai/rankings), as of {as_of}.\"
|
||||
|
||||
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
|
||||
This is used to track API usage per application.
|
||||
|
||||
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param window: Trailing time window for the classification data. Currently only `7d` (trailing 7 days) is supported.
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
:param http_headers: Additional headers to set or replace on requests.
|
||||
"""
|
||||
base_url = None
|
||||
url_variables = None
|
||||
if timeout_ms is None:
|
||||
timeout_ms = self.sdk_configuration.timeout_ms
|
||||
|
||||
if server_url is not None:
|
||||
base_url = server_url
|
||||
else:
|
||||
base_url = self._get_url(base_url, url_variables)
|
||||
|
||||
request = operations.GetTaskClassificationsRequest(
|
||||
http_referer=http_referer,
|
||||
x_open_router_title=x_open_router_title,
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
window=window,
|
||||
)
|
||||
|
||||
req = self._build_request(
|
||||
method="GET",
|
||||
path="/classifications/task",
|
||||
base_url=base_url,
|
||||
url_variables=url_variables,
|
||||
request=request,
|
||||
request_body_required=False,
|
||||
request_has_path_params=False,
|
||||
request_has_query_params=True,
|
||||
user_agent_header="user-agent",
|
||||
accept_header_value="application/json",
|
||||
http_headers=http_headers,
|
||||
_globals=operations.GetTaskClassificationsGlobals(
|
||||
http_referer=self.sdk_configuration.globals.http_referer,
|
||||
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
|
||||
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
|
||||
),
|
||||
security=self.sdk_configuration.security,
|
||||
allow_empty_value=None,
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
|
||||
if retries == UNSET:
|
||||
if self.sdk_configuration.retry_config is not UNSET:
|
||||
retries = self.sdk_configuration.retry_config
|
||||
else:
|
||||
retries = utils.RetryConfig(
|
||||
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
|
||||
)
|
||||
|
||||
retry_config = None
|
||||
if isinstance(retries, utils.RetryConfig):
|
||||
retry_config = (retries, ["5XX"])
|
||||
|
||||
http_res = self.do_request(
|
||||
hook_ctx=HookContext(
|
||||
config=self.sdk_configuration,
|
||||
base_url=base_url or "",
|
||||
operation_id="getTaskClassifications",
|
||||
oauth2_scopes=None,
|
||||
security_source=get_security_from_env(
|
||||
self.sdk_configuration.security, components.Security
|
||||
),
|
||||
),
|
||||
request=req,
|
||||
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
|
||||
retry_config=retry_config,
|
||||
)
|
||||
|
||||
response_data: Any = None
|
||||
if utils.match_response(http_res, "200", "application/json"):
|
||||
return unmarshal_json_response(
|
||||
components.TaskClassificationResponse, http_res
|
||||
)
|
||||
if utils.match_response(http_res, "400", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.BadRequestResponseErrorData, http_res
|
||||
)
|
||||
raise errors.BadRequestResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "401", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.UnauthorizedResponseErrorData, http_res
|
||||
)
|
||||
raise errors.UnauthorizedResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "429", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.TooManyRequestsResponseErrorData, http_res
|
||||
)
|
||||
raise errors.TooManyRequestsResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "500", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.InternalServerResponseErrorData, http_res
|
||||
)
|
||||
raise errors.InternalServerResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "4XX", "*"):
|
||||
http_res_text = utils.stream_to_text(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
if utils.match_response(http_res, "5XX", "*"):
|
||||
http_res_text = utils.stream_to_text(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
|
||||
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
|
||||
|
||||
async def get_task_classifications_async(
|
||||
self,
|
||||
*,
|
||||
http_referer: Optional[str] = None,
|
||||
x_open_router_title: Optional[str] = None,
|
||||
x_open_router_categories: Optional[str] = None,
|
||||
window: Optional[operations.Window] = "7d",
|
||||
retries: OptionalNullable[utils.RetryConfig] = UNSET,
|
||||
server_url: Optional[str] = None,
|
||||
timeout_ms: Optional[int] = None,
|
||||
http_headers: Optional[Mapping[str, str]] = None,
|
||||
) -> components.TaskClassificationResponse:
|
||||
r"""Task classification market share
|
||||
|
||||
Returns the market-share breakdown of OpenRouter traffic by task classification
|
||||
(e.g. code generation, web search, summarization) over a trailing time window.
|
||||
|
||||
Each classification reports its share of classified sampled requests (`usage_share`)
|
||||
and classified sampled token volume (`token_share`) as fractions between 0 and 1.
|
||||
The unclassified `other` bucket is excluded. Absolute volumes are not exposed
|
||||
because the underlying data is sampled.
|
||||
|
||||
Each classification also includes a `models` array listing the top models by
|
||||
request volume within that classification, with their within-tag usage and token shares.
|
||||
|
||||
Classifications are grouped into macro-categories (Code, Data, Agent, General)
|
||||
with aggregate shares provided for each.
|
||||
|
||||
Authenticate with any valid OpenRouter API key (same key used for inference).
|
||||
Rate-limited to 30 requests/minute per key and 500 requests/day per account.
|
||||
|
||||
When republishing or quoting this data, cite as:
|
||||
\"Source: OpenRouter (openrouter.ai/rankings), as of {as_of}.\"
|
||||
|
||||
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
|
||||
This is used to track API usage per application.
|
||||
|
||||
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
|
||||
|
||||
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
|
||||
|
||||
:param window: Trailing time window for the classification data. Currently only `7d` (trailing 7 days) is supported.
|
||||
:param retries: Override the default retry configuration for this method
|
||||
:param server_url: Override the default server URL for this method
|
||||
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
|
||||
:param http_headers: Additional headers to set or replace on requests.
|
||||
"""
|
||||
base_url = None
|
||||
url_variables = None
|
||||
if timeout_ms is None:
|
||||
timeout_ms = self.sdk_configuration.timeout_ms
|
||||
|
||||
if server_url is not None:
|
||||
base_url = server_url
|
||||
else:
|
||||
base_url = self._get_url(base_url, url_variables)
|
||||
|
||||
request = operations.GetTaskClassificationsRequest(
|
||||
http_referer=http_referer,
|
||||
x_open_router_title=x_open_router_title,
|
||||
x_open_router_categories=x_open_router_categories,
|
||||
window=window,
|
||||
)
|
||||
|
||||
req = self._build_request_async(
|
||||
method="GET",
|
||||
path="/classifications/task",
|
||||
base_url=base_url,
|
||||
url_variables=url_variables,
|
||||
request=request,
|
||||
request_body_required=False,
|
||||
request_has_path_params=False,
|
||||
request_has_query_params=True,
|
||||
user_agent_header="user-agent",
|
||||
accept_header_value="application/json",
|
||||
http_headers=http_headers,
|
||||
_globals=operations.GetTaskClassificationsGlobals(
|
||||
http_referer=self.sdk_configuration.globals.http_referer,
|
||||
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
|
||||
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
|
||||
),
|
||||
security=self.sdk_configuration.security,
|
||||
allow_empty_value=None,
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
|
||||
if retries == UNSET:
|
||||
if self.sdk_configuration.retry_config is not UNSET:
|
||||
retries = self.sdk_configuration.retry_config
|
||||
else:
|
||||
retries = utils.RetryConfig(
|
||||
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
|
||||
)
|
||||
|
||||
retry_config = None
|
||||
if isinstance(retries, utils.RetryConfig):
|
||||
retry_config = (retries, ["5XX"])
|
||||
|
||||
http_res = await self.do_request_async(
|
||||
hook_ctx=HookContext(
|
||||
config=self.sdk_configuration,
|
||||
base_url=base_url or "",
|
||||
operation_id="getTaskClassifications",
|
||||
oauth2_scopes=None,
|
||||
security_source=get_security_from_env(
|
||||
self.sdk_configuration.security, components.Security
|
||||
),
|
||||
),
|
||||
request=req,
|
||||
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
|
||||
retry_config=retry_config,
|
||||
)
|
||||
|
||||
response_data: Any = None
|
||||
if utils.match_response(http_res, "200", "application/json"):
|
||||
return unmarshal_json_response(
|
||||
components.TaskClassificationResponse, http_res
|
||||
)
|
||||
if utils.match_response(http_res, "400", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.BadRequestResponseErrorData, http_res
|
||||
)
|
||||
raise errors.BadRequestResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "401", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.UnauthorizedResponseErrorData, http_res
|
||||
)
|
||||
raise errors.UnauthorizedResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "429", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.TooManyRequestsResponseErrorData, http_res
|
||||
)
|
||||
raise errors.TooManyRequestsResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "500", "application/json"):
|
||||
response_data = unmarshal_json_response(
|
||||
errors.InternalServerResponseErrorData, http_res
|
||||
)
|
||||
raise errors.InternalServerResponseError(response_data, http_res)
|
||||
if utils.match_response(http_res, "4XX", "*"):
|
||||
http_res_text = await utils.stream_to_text_async(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
if utils.match_response(http_res, "5XX", "*"):
|
||||
http_res_text = await utils.stream_to_text_async(http_res)
|
||||
raise errors.OpenRouterDefaultError(
|
||||
"API error occurred", http_res, http_res_text
|
||||
)
|
||||
|
||||
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
|
||||
+3385
-137
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,60 @@
|
||||
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
|
||||
|
||||
from __future__ import annotations
|
||||
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL
|
||||
from pydantic import model_serializer
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
|
||||
class AABenchmarkEntryTypedDict(TypedDict):
|
||||
r"""Artificial Analysis benchmark index scores."""
|
||||
|
||||
agentic_index: Nullable[float]
|
||||
r"""Artificial Analysis Agentic Index score"""
|
||||
coding_index: Nullable[float]
|
||||
r"""Artificial Analysis Coding Index score"""
|
||||
intelligence_index: Nullable[float]
|
||||
r"""Artificial Analysis Intelligence Index score"""
|
||||
|
||||
|
||||
class AABenchmarkEntry(BaseModel):
|
||||
r"""Artificial Analysis benchmark index scores."""
|
||||
|
||||
agentic_index: Nullable[float]
|
||||
r"""Artificial Analysis Agentic Index score"""
|
||||
|
||||
coding_index: Nullable[float]
|
||||
r"""Artificial Analysis Coding Index score"""
|
||||
|
||||
intelligence_index: Nullable[float]
|
||||
r"""Artificial Analysis Intelligence Index score"""
|
||||
|
||||
@model_serializer(mode="wrap")
|
||||
def serialize_model(self, handler):
|
||||
optional_fields = []
|
||||
nullable_fields = ["agentic_index", "coding_index", "intelligence_index"]
|
||||
null_default_fields = []
|
||||
|
||||
serialized = handler(self)
|
||||
|
||||
m = {}
|
||||
|
||||
for n, f in type(self).model_fields.items():
|
||||
k = f.alias or n
|
||||
val = serialized.get(k)
|
||||
serialized.pop(k, None)
|
||||
|
||||
optional_nullable = k in optional_fields and k in nullable_fields
|
||||
is_set = (
|
||||
self.__pydantic_fields_set__.intersection({n})
|
||||
or k in null_default_fields
|
||||
) # pylint: disable=no-member
|
||||
|
||||
if val is not None and val != UNSET_SENTINEL:
|
||||
m[k] = val
|
||||
elif val != UNSET_SENTINEL and (
|
||||
not k in optional_fields or (optional_nullable and is_set)
|
||||
):
|
||||
m[k] = val
|
||||
|
||||
return m
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
|
||||
|
||||
from __future__ import annotations
|
||||
from openrouter.types import BaseModel, Nullable
|
||||
import pydantic
|
||||
from pydantic import ConfigDict
|
||||
from typing import Any, Dict, Optional
|
||||
from typing_extensions import NotRequired, TypedDict
|
||||
|
||||
|
||||
class AdvisorNestedToolTypedDict(TypedDict):
|
||||
r"""A tool made available to the advisor sub-agent. Only OpenRouter server tools (e.g. openrouter:web_search) are supported; function tools are rejected because the advisor has no way to execute them. The advisor tool may not list itself."""
|
||||
|
||||
type: str
|
||||
parameters: NotRequired[Dict[str, Nullable[Any]]]
|
||||
|
||||
|
||||
class AdvisorNestedTool(BaseModel):
|
||||
r"""A tool made available to the advisor sub-agent. Only OpenRouter server tools (e.g. openrouter:web_search) are supported; function tools are rejected because the advisor has no way to execute them. The advisor tool may not list itself."""
|
||||
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True, arbitrary_types_allowed=True, extra="allow"
|
||||
)
|
||||
__pydantic_extra__: Dict[str, Nullable[Any]] = pydantic.Field(init=False)
|
||||
|
||||
type: str
|
||||
|
||||
parameters: Optional[Dict[str, Nullable[Any]]] = None
|
||||
|
||||
@property
|
||||
def additional_properties(self):
|
||||
return self.__pydantic_extra__
|
||||
|
||||
@additional_properties.setter
|
||||
def additional_properties(self, value):
|
||||
self.__pydantic_extra__ = value # pyright: ignore[reportIncompatibleVariableOverride]
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
|
||||
|
||||
from __future__ import annotations
|
||||
from openrouter.types import BaseModel, UnrecognizedStr
|
||||
from openrouter.utils import validate_open_enum
|
||||
from pydantic.functional_validators import PlainValidator
|
||||
from typing import Literal, Optional, Union
|
||||
from typing_extensions import Annotated, NotRequired, TypedDict
|
||||
|
||||
|
||||
AdvisorReasoningEffort = Union[
|
||||
Literal[
|
||||
"max",
|
||||
"xhigh",
|
||||
"high",
|
||||
"medium",
|
||||
"low",
|
||||
"minimal",
|
||||
"none",
|
||||
],
|
||||
UnrecognizedStr,
|
||||
]
|
||||
r"""Reasoning effort level for the advisor call."""
|
||||
|
||||
|
||||
class AdvisorReasoningTypedDict(TypedDict):
|
||||
r"""Reasoning configuration forwarded to the advisor call. Use this to control reasoning effort and token budget for models that support extended thinking."""
|
||||
|
||||
effort: NotRequired[AdvisorReasoningEffort]
|
||||
r"""Reasoning effort level for the advisor call."""
|
||||
max_tokens: NotRequired[int]
|
||||
r"""Maximum number of reasoning tokens the advisor may use."""
|
||||
|
||||
|
||||
class AdvisorReasoning(BaseModel):
|
||||
r"""Reasoning configuration forwarded to the advisor call. Use this to control reasoning effort and token budget for models that support extended thinking."""
|
||||
|
||||
effort: Annotated[
|
||||
Optional[AdvisorReasoningEffort], PlainValidator(validate_open_enum(False))
|
||||
] = None
|
||||
r"""Reasoning effort level for the advisor call."""
|
||||
|
||||
max_tokens: Optional[int] = None
|
||||
r"""Maximum number of reasoning tokens the advisor may use."""
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
|
||||
|
||||
from __future__ import annotations
|
||||
from .advisorservertoolconfig import (
|
||||
AdvisorServerToolConfig,
|
||||
AdvisorServerToolConfigTypedDict,
|
||||
)
|
||||
from openrouter.types import BaseModel
|
||||
from typing import Literal, Optional
|
||||
from typing_extensions import NotRequired, TypedDict
|
||||
|
||||
|
||||
AdvisorServerToolOpenRouterType = Literal["openrouter:advisor",]
|
||||
|
||||
|
||||
class AdvisorServerToolOpenRouterTypedDict(TypedDict):
|
||||
r"""OpenRouter built-in server tool: consults a higher-intelligence advisor model (any OpenRouter model) for guidance mid-generation and returns its response. The advisor may run as a sub-agent with its own tools. Include multiple entries to offer several named advisors; at most one entry may omit `name` to act as the default advisor."""
|
||||
|
||||
type: AdvisorServerToolOpenRouterType
|
||||
parameters: NotRequired[AdvisorServerToolConfigTypedDict]
|
||||
r"""Configuration for one openrouter:advisor server tool entry."""
|
||||
|
||||
|
||||
class AdvisorServerToolOpenRouter(BaseModel):
|
||||
r"""OpenRouter built-in server tool: consults a higher-intelligence advisor model (any OpenRouter model) for guidance mid-generation and returns its response. The advisor may run as a sub-agent with its own tools. Include multiple entries to offer several named advisors; at most one entry may omit `name` to act as the default advisor."""
|
||||
|
||||
type: AdvisorServerToolOpenRouterType
|
||||
|
||||
parameters: Optional[AdvisorServerToolConfig] = None
|
||||
r"""Configuration for one openrouter:advisor server tool entry."""
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
|
||||
|
||||
from __future__ import annotations
|
||||
from .advisornestedtool import AdvisorNestedTool, AdvisorNestedToolTypedDict
|
||||
from .advisorreasoning import AdvisorReasoning, AdvisorReasoningTypedDict
|
||||
from openrouter.types import BaseModel
|
||||
from typing import List, Optional
|
||||
from typing_extensions import NotRequired, TypedDict
|
||||
|
||||
|
||||
class AdvisorServerToolConfigTypedDict(TypedDict):
|
||||
r"""Configuration for one openrouter:advisor server tool entry."""
|
||||
|
||||
forward_transcript: NotRequired[bool]
|
||||
r"""When true, the full parent conversation is forwarded to the advisor so it sees the same context the executor does (and the tool-call `prompt`, if given, is appended as a final user turn). When false or omitted, the advisor receives only the `prompt` the executor passes in the tool call."""
|
||||
instructions: NotRequired[str]
|
||||
r"""System instructions for the advisor sub-agent. When omitted, the advisor responds with no system prompt of its own."""
|
||||
max_completion_tokens: NotRequired[int]
|
||||
r"""Maximum number of output tokens (including reasoning) the advisor may produce. When omitted, the provider's default applies."""
|
||||
max_tool_calls: NotRequired[int]
|
||||
r"""Maximum number of tool-calling steps the advisor sub-agent may take during its agentic loop. Capped at 25. Only relevant when the advisor is given tools."""
|
||||
model: NotRequired[str]
|
||||
r"""Slug of the advisor model to consult (any OpenRouter model). When omitted, the executor can choose it via the tool call's `model` argument; if neither is set, the model from the outer API request is used. The advisor tool itself cannot be the advisor model."""
|
||||
name: NotRequired[str]
|
||||
r"""Optional name for this advisor. The model sees one tool per named advisor (and one default for an unnamed entry). Names must be unique across advisor entries. Letters, digits, spaces, underscores, and dashes; trimmed; 1–64 chars."""
|
||||
reasoning: NotRequired[AdvisorReasoningTypedDict]
|
||||
r"""Reasoning configuration forwarded to the advisor call. Use this to control reasoning effort and token budget for models that support extended thinking."""
|
||||
stream: NotRequired[bool]
|
||||
r"""When true, the advisor's advice streams incrementally as it is produced. In the Responses API this emits `response.output_text.delta` events targeting the advisor output item; the final `advice` field is still set on the completed item. Has no effect on the Chat Completions API (where the advice arrives only as the final tool result). When false or omitted, the advice arrives only as the final result."""
|
||||
temperature: NotRequired[float]
|
||||
r"""Sampling temperature forwarded to the advisor call. When omitted, the provider's default applies."""
|
||||
tools: NotRequired[List[AdvisorNestedToolTypedDict]]
|
||||
r"""Tools the advisor sub-agent may use while forming its advice. The advisor runs as an agentic sub-agent over these tools, then returns its text. Only OpenRouter server tools are supported — function tools are rejected — and the list must not include the advisor tool itself."""
|
||||
|
||||
|
||||
class AdvisorServerToolConfig(BaseModel):
|
||||
r"""Configuration for one openrouter:advisor server tool entry."""
|
||||
|
||||
forward_transcript: Optional[bool] = None
|
||||
r"""When true, the full parent conversation is forwarded to the advisor so it sees the same context the executor does (and the tool-call `prompt`, if given, is appended as a final user turn). When false or omitted, the advisor receives only the `prompt` the executor passes in the tool call."""
|
||||
|
||||
instructions: Optional[str] = None
|
||||
r"""System instructions for the advisor sub-agent. When omitted, the advisor responds with no system prompt of its own."""
|
||||
|
||||
max_completion_tokens: Optional[int] = None
|
||||
r"""Maximum number of output tokens (including reasoning) the advisor may produce. When omitted, the provider's default applies."""
|
||||
|
||||
max_tool_calls: Optional[int] = None
|
||||
r"""Maximum number of tool-calling steps the advisor sub-agent may take during its agentic loop. Capped at 25. Only relevant when the advisor is given tools."""
|
||||
|
||||
model: Optional[str] = None
|
||||
r"""Slug of the advisor model to consult (any OpenRouter model). When omitted, the executor can choose it via the tool call's `model` argument; if neither is set, the model from the outer API request is used. The advisor tool itself cannot be the advisor model."""
|
||||
|
||||
name: Optional[str] = None
|
||||
r"""Optional name for this advisor. The model sees one tool per named advisor (and one default for an unnamed entry). Names must be unique across advisor entries. Letters, digits, spaces, underscores, and dashes; trimmed; 1–64 chars."""
|
||||
|
||||
reasoning: Optional[AdvisorReasoning] = None
|
||||
r"""Reasoning configuration forwarded to the advisor call. Use this to control reasoning effort and token budget for models that support extended thinking."""
|
||||
|
||||
stream: Optional[bool] = None
|
||||
r"""When true, the advisor's advice streams incrementally as it is produced. In the Responses API this emits `response.output_text.delta` events targeting the advisor output item; the final `advice` field is still set on the completed item. Has no effect on the Chat Completions API (where the advice arrives only as the final tool result). When false or omitted, the advice arrives only as the final result."""
|
||||
|
||||
temperature: Optional[float] = None
|
||||
r"""Sampling temperature forwarded to the advisor call. When omitted, the provider's default applies."""
|
||||
|
||||
tools: Optional[List[AdvisorNestedTool]] = None
|
||||
r"""Tools the advisor sub-agent may use while forming its advice. The advisor runs as an agentic sub-agent over these tools, then returns its text. Only OpenRouter server tools are supported — function tools are rejected — and the list must not include the advisor tool itself."""
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
|
||||
|
||||
from __future__ import annotations
|
||||
from .anthropiciterationcachecreation import (
|
||||
AnthropicIterationCacheCreation,
|
||||
AnthropicIterationCacheCreationTypedDict,
|
||||
)
|
||||
from openrouter.types import (
|
||||
BaseModel,
|
||||
Nullable,
|
||||
OptionalNullable,
|
||||
UNSET,
|
||||
UNSET_SENTINEL,
|
||||
)
|
||||
from pydantic import model_serializer
|
||||
from typing import Literal, Optional
|
||||
from typing_extensions import NotRequired, TypedDict
|
||||
|
||||
|
||||
AnthropicAdvisorMessageUsageIterationType = Literal["advisor_message",]
|
||||
|
||||
|
||||
class AnthropicAdvisorMessageUsageIterationTypedDict(TypedDict):
|
||||
model: str
|
||||
type: AnthropicAdvisorMessageUsageIterationType
|
||||
cache_creation: NotRequired[Nullable[AnthropicIterationCacheCreationTypedDict]]
|
||||
cache_creation_input_tokens: NotRequired[int]
|
||||
cache_read_input_tokens: NotRequired[int]
|
||||
input_tokens: NotRequired[int]
|
||||
output_tokens: NotRequired[int]
|
||||
|
||||
|
||||
class AnthropicAdvisorMessageUsageIteration(BaseModel):
|
||||
model: str
|
||||
|
||||
type: AnthropicAdvisorMessageUsageIterationType
|
||||
|
||||
cache_creation: OptionalNullable[AnthropicIterationCacheCreation] = UNSET
|
||||
|
||||
cache_creation_input_tokens: Optional[int] = None
|
||||
|
||||
cache_read_input_tokens: Optional[int] = None
|
||||
|
||||
input_tokens: Optional[int] = None
|
||||
|
||||
output_tokens: Optional[int] = None
|
||||
|
||||
@model_serializer(mode="wrap")
|
||||
def serialize_model(self, handler):
|
||||
optional_fields = [
|
||||
"cache_creation",
|
||||
"cache_creation_input_tokens",
|
||||
"cache_read_input_tokens",
|
||||
"input_tokens",
|
||||
"output_tokens",
|
||||
]
|
||||
nullable_fields = ["cache_creation"]
|
||||
null_default_fields = []
|
||||
|
||||
serialized = handler(self)
|
||||
|
||||
m = {}
|
||||
|
||||
for n, f in type(self).model_fields.items():
|
||||
k = f.alias or n
|
||||
val = serialized.get(k)
|
||||
serialized.pop(k, None)
|
||||
|
||||
optional_nullable = k in optional_fields and k in nullable_fields
|
||||
is_set = (
|
||||
self.__pydantic_fields_set__.intersection({n})
|
||||
or k in null_default_fields
|
||||
) # pylint: disable=no-member
|
||||
|
||||
if val is not None and val != UNSET_SENTINEL:
|
||||
m[k] = val
|
||||
elif val != UNSET_SENTINEL and (
|
||||
not k in optional_fields or (optional_nullable and is_set)
|
||||
):
|
||||
m[k] = val
|
||||
|
||||
return m
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
|
||||
|
||||
from __future__ import annotations
|
||||
from openrouter.types import UnrecognizedStr
|
||||
from typing import Literal, Union
|
||||
|
||||
|
||||
AnthropicAllowedCallers = Union[
|
||||
Literal[
|
||||
"direct",
|
||||
"code_execution_20250825",
|
||||
"code_execution_20260120",
|
||||
],
|
||||
UnrecognizedStr,
|
||||
]
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user